mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-19 14:52:40 +08:00
Co-authored-by: qiuguohua <qiuguohua111@126.com>
This commit is contained in:
@@ -28,6 +28,7 @@ jobs:
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: node scripts/spread-pal.cjs
|
||||
- run: npm run build:debug-infos
|
||||
- name: Download external
|
||||
run: |
|
||||
|
||||
@@ -46,3 +46,11 @@ platforms/runtime/platforms/vivo-mini-game/ral.min.js
|
||||
@types/consts.d.ts
|
||||
|
||||
__TS_ENGINE__/
|
||||
|
||||
# pal 由 @cocos/engine-pal 在 postinstall 挂载(软链/复制),不入库
|
||||
/pal
|
||||
|
||||
# platforms 源码已抽到 @cocos/engine-platforms;其预打包 adapter 由 postinstall 的
|
||||
# spread-adapter.cjs 复制到 bin/adapter(/bin 已忽略)。platforms 源码不再入库。
|
||||
/platforms
|
||||
|
||||
|
||||
+44
-44
@@ -382,70 +382,70 @@
|
||||
"test": "context.buildTimeConstants && context.buildTimeConstants.HTML5",
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/non-minigame.ts",
|
||||
"pal/audio": "pal/audio/web/player.ts",
|
||||
"pal/system-info": "pal/system-info/web/system-info.ts",
|
||||
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.ts",
|
||||
"pal/input": "pal/input/web/index.ts",
|
||||
"pal/env": "pal/env/web/env.ts",
|
||||
"pal/pacer": "pal/pacer/pacer-web.ts",
|
||||
"pal/wasm": "pal/wasm/wasm-web.ts"
|
||||
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||
"pal/audio": "pal/audio/web/player.js",
|
||||
"pal/system-info": "pal/system-info/web/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.js",
|
||||
"pal/input": "pal/input/web/index.js",
|
||||
"pal/env": "pal/env/web/env.js",
|
||||
"pal/pacer": "pal/pacer/pacer-web.js",
|
||||
"pal/wasm": "pal/wasm/wasm-web.js"
|
||||
}
|
||||
},
|
||||
{
|
||||
"test": "context.buildTimeConstants && context.buildTimeConstants.NATIVE",
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/non-minigame.ts",
|
||||
"pal/audio": "pal/audio/native/player.ts",
|
||||
"pal/system-info": "pal/system-info/native/system-info.ts",
|
||||
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.ts",
|
||||
"pal/input": "pal/input/native/index.ts",
|
||||
"pal/env": "pal/env/native/env.ts",
|
||||
"pal/pacer": "pal/pacer/pacer-native.ts",
|
||||
"pal/wasm": "pal/wasm/wasm-native.ts"
|
||||
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||
"pal/audio": "pal/audio/native/player.js",
|
||||
"pal/system-info": "pal/system-info/native/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.js",
|
||||
"pal/input": "pal/input/native/index.js",
|
||||
"pal/env": "pal/env/native/env.js",
|
||||
"pal/pacer": "pal/pacer/pacer-native.js",
|
||||
"pal/wasm": "pal/wasm/wasm-native.js"
|
||||
}
|
||||
},
|
||||
{
|
||||
"test": "context.buildTimeConstants && context.buildTimeConstants.MINIGAME",
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.ts",
|
||||
"pal/audio": "pal/audio/minigame/player.ts",
|
||||
"pal/system-info": "pal/system-info/minigame/system-info.ts",
|
||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
|
||||
"pal/input": "pal/input/minigame/index.ts",
|
||||
"pal/env": "pal/env/minigame/env.ts",
|
||||
"pal/pacer": "pal/pacer/pacer-minigame.ts",
|
||||
"pal/wasm": "pal/wasm/wasm-minigame.ts"
|
||||
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.js",
|
||||
"pal/audio": "pal/audio/minigame/player.js",
|
||||
"pal/system-info": "pal/system-info/minigame/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
|
||||
"pal/input": "pal/input/minigame/index.js",
|
||||
"pal/env": "pal/env/minigame/env.js",
|
||||
"pal/pacer": "pal/pacer/pacer-minigame.js",
|
||||
"pal/wasm": "pal/wasm/wasm-minigame.js"
|
||||
}
|
||||
},
|
||||
{
|
||||
"test": "context.buildTimeConstants && context.buildTimeConstants.RUNTIME_BASED",
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/runtime.ts",
|
||||
"pal/audio": "pal/audio/minigame/player.ts",
|
||||
"pal/system-info": "pal/system-info/minigame/system-info.ts",
|
||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
|
||||
"pal/input": "pal/input/minigame/index.ts",
|
||||
"pal/env": "pal/env/runtime/env.ts",
|
||||
"pal/pacer": "pal/pacer/pacer-minigame.ts",
|
||||
"pal/wasm": "pal/wasm/wasm-minigame.ts"
|
||||
"pal/minigame": "pal/minigame/runtime.js",
|
||||
"pal/audio": "pal/audio/minigame/player.js",
|
||||
"pal/system-info": "pal/system-info/minigame/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
|
||||
"pal/input": "pal/input/minigame/index.js",
|
||||
"pal/env": "pal/env/runtime/env.js",
|
||||
"pal/pacer": "pal/pacer/pacer-minigame.js",
|
||||
"pal/wasm": "pal/wasm/wasm-minigame.js"
|
||||
}
|
||||
},
|
||||
{
|
||||
"test": "context.buildTimeConstants && context.buildTimeConstants.NODEJS",
|
||||
"isVirtualModule": true,
|
||||
"overrides": {
|
||||
"pal/minigame": "pal/minigame/non-minigame.ts",
|
||||
"pal/audio": "pal/audio/nodejs/player.ts",
|
||||
"pal/system-info": "pal/system-info/nodejs/system-info.ts",
|
||||
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.ts",
|
||||
"pal/input": "pal/input/nodejs/index.ts",
|
||||
"pal/env": "pal/env/nodejs/env.ts",
|
||||
"pal/pacer": "pal/pacer/pacer-nodejs.ts",
|
||||
"pal/wasm": "pal/wasm/wasm-nodejs.ts"
|
||||
"pal/minigame": "pal/minigame/non-minigame.js",
|
||||
"pal/audio": "pal/audio/nodejs/player.js",
|
||||
"pal/system-info": "pal/system-info/nodejs/system-info.js",
|
||||
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.js",
|
||||
"pal/input": "pal/input/nodejs/index.js",
|
||||
"pal/env": "pal/env/nodejs/env.js",
|
||||
"pal/pacer": "pal/pacer/pacer-nodejs.js",
|
||||
"pal/wasm": "pal/wasm/wasm-nodejs.js"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -885,10 +885,10 @@
|
||||
"cocos/asset/asset-manager/weak-cache.ts",
|
||||
"cocos/2d/framework/ui-skew-utils.ts",
|
||||
"cocos/spine/lib/spine-binary.ts",
|
||||
"pal/input/minigame/gamepad-input.ts",
|
||||
"pal/input/minigame/handheld-input.ts",
|
||||
"pal/input/minigame/handle-input.ts",
|
||||
"pal/input/minigame/hmd-input.ts"
|
||||
"pal/input/minigame/gamepad-input.js",
|
||||
"pal/input/minigame/handheld-input.js",
|
||||
"pal/input/minigame/handle-input.js",
|
||||
"pal/input/minigame/hmd-input.js"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,12 +21,14 @@
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
import { DEBUG } from 'internal:constants';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { Orientation } from '../../../pal/screen-adapter/enum-type';
|
||||
import {
|
||||
TextureType, TextureUsageBit, Format, RenderPass, Texture, Framebuffer,
|
||||
RenderPassInfo, Device, TextureInfo, FramebufferInfo, Swapchain, SurfaceTransform, TextureFlagBit, TextureFlags,
|
||||
} from '../../gfx';
|
||||
import { warn } from '../../core/platform/debug';
|
||||
import { Root } from '../../root';
|
||||
import { Camera } from '../scene';
|
||||
|
||||
@@ -41,7 +43,10 @@ export interface IRenderWindowInfo {
|
||||
externalFlag?: TextureFlags; // external texture type normal or oes
|
||||
}
|
||||
|
||||
const orientationMap: Record<Orientation, SurfaceTransform> = {
|
||||
// NOTE: `Orientation` is a flag enum whose composite members (LANDSCAPE, AUTO) are never
|
||||
// actual runtime orientations, so this map intentionally only covers the physical ones.
|
||||
// It is therefore typed as Partial rather than a total Record<Orientation, ...>.
|
||||
const orientationMap: Partial<Record<Orientation, SurfaceTransform>> = {
|
||||
[Orientation.PORTRAIT]: SurfaceTransform.IDENTITY,
|
||||
[Orientation.LANDSCAPE_RIGHT]: SurfaceTransform.ROTATE_90,
|
||||
[Orientation.PORTRAIT_UPSIDE_DOWN]: SurfaceTransform.ROTATE_180,
|
||||
@@ -253,7 +258,11 @@ export class RenderWindow {
|
||||
*/
|
||||
public resize (width: number, height: number): void {
|
||||
if (this._swapchain) {
|
||||
this._swapchain.resize(width, height, orientationMap[screenAdapter.orientation]);
|
||||
const surfaceTransform = orientationMap[screenAdapter.orientation];
|
||||
if (DEBUG && surfaceTransform === undefined) {
|
||||
warn(`Unexpected screen orientation: ${screenAdapter.orientation}`);
|
||||
}
|
||||
this._swapchain.resize(width, height, surfaceTransform || SurfaceTransform.IDENTITY);
|
||||
this._width = this._swapchain.width;
|
||||
this._height = this._swapchain.height;
|
||||
} else {
|
||||
|
||||
Generated
+20
-4
@@ -13,8 +13,10 @@
|
||||
"@babel/plugin-proposal-class-properties": "^7.18.6",
|
||||
"@cocos/box2d": "1.0.2",
|
||||
"@cocos/cannon": "1.2.8",
|
||||
"@cocos/ccbuild": "^2.3.16",
|
||||
"@cocos/ccbuild": "^2.3.21",
|
||||
"@cocos/dragonbones-js": "^1.0.1",
|
||||
"@cocos/engine-pal": "^1.0.4",
|
||||
"@cocos/engine-platforms": "^1.0.5",
|
||||
"@types/jest": "^24.9.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -2064,9 +2066,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@cocos/ccbuild": {
|
||||
"version": "2.3.16",
|
||||
"resolved": "https://registry.npmjs.org/@cocos/ccbuild/-/ccbuild-2.3.16.tgz",
|
||||
"integrity": "sha512-ZfY2ZJXs0uIMyjQLuZH9CZ4CGhM4YTdn9eGBPV62tXaSLkIHU/o0Vp99CqVxP1vYM1Ud1Z6a/fArLP/Qe3/IIQ==",
|
||||
"version": "2.3.21",
|
||||
"resolved": "https://registry.npmmirror.com/@cocos/ccbuild/-/ccbuild-2.3.21.tgz",
|
||||
"integrity": "sha512-hwsuAQKW55jGCZvVmH/09Mvz3i6hv8XN5udHGJJrQc2IYOLCctymoHfuyobcQ+LI+qHRSRKKgc+cKN2jWZ0sTA==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"./modules/*"
|
||||
],
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.20.12",
|
||||
"@babel/generator": "^7.22.10",
|
||||
@@ -2561,6 +2567,16 @@
|
||||
"resolved": "https://registry.npmjs.org/@cocos/dragonbones-js/-/dragonbones-js-1.0.1.tgz",
|
||||
"integrity": "sha512-1bWAW8td2WTGicyCqxtpIjc1YuK5EzMWfMEWaJlskPAQwLS0JfxEGka71sZ1BzudiWiKS7hPMg+FvXr5NRnVwQ=="
|
||||
},
|
||||
"node_modules/@cocos/engine-pal": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmmirror.com/@cocos/engine-pal/-/engine-pal-1.0.4.tgz",
|
||||
"integrity": "sha512-VtvO0xE2ZviVtwqWn4P6cysn2BX7QABm9sNc1rfy4gy+FHtiwSMkLLL3l3Faw+yZiTE6EwxjPvnc96Igb7mNuQ=="
|
||||
},
|
||||
"node_modules/@cocos/engine-platforms": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmmirror.com/@cocos/engine-platforms/-/engine-platforms-1.0.5.tgz",
|
||||
"integrity": "sha512-ES004q8DkuexPk8B4teXzCmAZNW8G4iqnLYJn/VZhYEOMDpySF8HhNfBl2M91BMnsCXlvJILABLKEVUCqUL+aA=="
|
||||
},
|
||||
"node_modules/@cocos/rollup-plugin-terser": {
|
||||
"version": "0.4.5",
|
||||
"resolved": "https://registry.npmjs.org/@cocos/rollup-plugin-terser/-/rollup-plugin-terser-0.4.5.tgz",
|
||||
|
||||
+9
-3
@@ -12,7 +12,7 @@
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"postinstall": "npm run build:debug-infos && npm run build:declaration && npm run build:adapter && npm run build:native-pack-tool",
|
||||
"postinstall": "node scripts/spread-pal.cjs && npm run build:debug-infos && npm run build:declaration && node scripts/spread-adapter.cjs && npm run build:native-pack-tool",
|
||||
"build": "npm run build:min && npm run build:declaration",
|
||||
"build:cli": "npm run build:cli-min && npm run build:declaration",
|
||||
"build:adapter": "node ./scripts/build-adapter.js",
|
||||
@@ -81,8 +81,14 @@
|
||||
"@babel/plugin-proposal-class-properties": "^7.18.6",
|
||||
"@cocos/box2d": "1.0.2",
|
||||
"@cocos/cannon": "1.2.8",
|
||||
"@cocos/ccbuild": "^2.3.16",
|
||||
"@cocos/ccbuild": "^2.3.21",
|
||||
"@cocos/dragonbones-js": "^1.0.1",
|
||||
"@cocos/engine-pal": "^1.0.4",
|
||||
"@cocos/engine-platforms": "^1.0.5",
|
||||
"@types/jest": "^24.9.1"
|
||||
}
|
||||
},
|
||||
"creator": {
|
||||
"version": "3.8.8"
|
||||
},
|
||||
"uuid": "8be51d4a-79ad-481c-adbf-265693b5adbf"
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { warnID } from '../../cocos/core/platform/debug';
|
||||
|
||||
/** @mangle */
|
||||
interface CachedAudioBufferData {
|
||||
usedCount: number,
|
||||
audioBuffer: AudioBuffer,
|
||||
}
|
||||
|
||||
interface AudioBufferDataMap {
|
||||
[url: string]: CachedAudioBufferData;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a manager to manage the cache of audio buffer for web audio.
|
||||
* @mangle
|
||||
*/
|
||||
class AudioBufferManager {
|
||||
private _audioBufferDataMap: AudioBufferDataMap = {};
|
||||
|
||||
public addCache (url: string, audioBuffer: AudioBuffer): void {
|
||||
const audioBufferData = this._audioBufferDataMap[url];
|
||||
if (audioBufferData) {
|
||||
warnID(5204, url);
|
||||
return;
|
||||
}
|
||||
this._audioBufferDataMap[url] = {
|
||||
usedCount: 1,
|
||||
audioBuffer,
|
||||
};
|
||||
}
|
||||
|
||||
public retainCache (url: string): void {
|
||||
const audioBufferData = this._audioBufferDataMap[url];
|
||||
if (!audioBufferData) {
|
||||
warnID(5203, url);
|
||||
return;
|
||||
}
|
||||
audioBufferData.usedCount++;
|
||||
}
|
||||
|
||||
public getCache (url: string): AudioBuffer | null | undefined {
|
||||
const audioBufferData = this._audioBufferDataMap[url];
|
||||
return audioBufferData?.audioBuffer;
|
||||
}
|
||||
|
||||
public tryReleasingCache (url: string): void {
|
||||
const audioBufferData = this._audioBufferDataMap[url];
|
||||
if (!audioBufferData) {
|
||||
warnID(5203, url);
|
||||
return;
|
||||
}
|
||||
if (--audioBufferData.usedCount <= 0) {
|
||||
delete this._audioBufferDataMap[url];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const audioBufferManager = new AudioBufferManager();
|
||||
@@ -1,119 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { clamp } from '../../cocos/core/math/utils';
|
||||
|
||||
/**
|
||||
* Tool class to calculate audio current time.
|
||||
* For some platforms where audio.currentTime doesn't work well or isn't implemented.
|
||||
*/
|
||||
|
||||
interface IDuration {
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export default class AudioTimer {
|
||||
private _nativeAudio: IDuration;
|
||||
private _startTime = 0;
|
||||
private _startOffset = 0;
|
||||
private _isPaused = true;
|
||||
|
||||
constructor (nativeAudio: IDuration) {
|
||||
this._nativeAudio = nativeAudio;
|
||||
}
|
||||
|
||||
public destroy (): void {
|
||||
// NOTE: 'undefined' is not assignable to type 'IDuration'
|
||||
this._nativeAudio = undefined as any;
|
||||
}
|
||||
|
||||
get duration (): number {
|
||||
return this._nativeAudio.duration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current time of audio timer.
|
||||
*/
|
||||
get currentTime (): number {
|
||||
if (this._isPaused) {
|
||||
return this._startOffset;
|
||||
} else {
|
||||
return this._calculateCurrentTime();
|
||||
}
|
||||
}
|
||||
|
||||
private _now (): number {
|
||||
return performance.now() / 1000;
|
||||
}
|
||||
|
||||
private _calculateCurrentTime (): number {
|
||||
const timePassed = this._now() - this._startTime;
|
||||
const currentTime = this._startOffset + timePassed;
|
||||
if (currentTime >= this.duration) {
|
||||
// timer loop
|
||||
this._startTime = this._now();
|
||||
this._startOffset = 0;
|
||||
}
|
||||
return currentTime % this.duration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the audio timer.
|
||||
* Call this method when audio is played.
|
||||
*/
|
||||
start (): void {
|
||||
this._isPaused = false;
|
||||
this._startTime = this._now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause the audio timer.
|
||||
* Call this method when audio is paused or interrupted.
|
||||
*/
|
||||
pause (): void {
|
||||
if (this._isPaused) {
|
||||
return;
|
||||
}
|
||||
this._isPaused = true;
|
||||
this._startOffset = this._calculateCurrentTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the audio timer.
|
||||
* Call this method when audio playing ended or audio is stopped.
|
||||
*/
|
||||
stop (): void {
|
||||
this._isPaused = true;
|
||||
this._startOffset = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seek the audio timer.
|
||||
* Call this method when audio is seeked.
|
||||
*/
|
||||
seek (time: number): void {
|
||||
this._startTime = this._now();
|
||||
this._startOffset = clamp(time, 0, this.duration);
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { TAOBAO, TAOBAO_MINIGAME, HUAWEI, VIVO, OPPO } from 'internal:constants';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { AudioEvent, AudioPCMDataView, AudioState, AudioType } from '../type';
|
||||
import { clamp, clamp01 } from '../../../cocos/core';
|
||||
import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue';
|
||||
import { OS } from '../../system-info/enum-type';
|
||||
|
||||
export class OneShotAudioMinigame {
|
||||
private declare _innerAudioContext: InnerAudioContext;
|
||||
private _onPlayCb?: () => void;
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._onPlayCb;
|
||||
}
|
||||
set onPlay (cb) {
|
||||
this._onPlayCb = cb;
|
||||
}
|
||||
|
||||
private _onEndCb?: () => void;
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._onEndCb;
|
||||
}
|
||||
set onEnd (cb) {
|
||||
this._onEndCb = cb;
|
||||
}
|
||||
|
||||
private constructor (nativeAudio: InnerAudioContext, volume: number) {
|
||||
this._innerAudioContext = nativeAudio;
|
||||
nativeAudio.volume = volume;
|
||||
nativeAudio.onPlay(() => {
|
||||
this._onPlayCb?.();
|
||||
});
|
||||
const endCallback = (): void => {
|
||||
if (this._innerAudioContext) {
|
||||
// NOTE: Type 'null' is not assignable to type 'InnerAudioContext'.
|
||||
this._innerAudioContext = null as any;
|
||||
systemInfo.off('hide', this._onInterruptedBegin, this);
|
||||
systemInfo.off('show', this._onInterruptedEnd, this);
|
||||
this._onEndCb?.();
|
||||
/**The destroy interface, in some platform implementations, internally invokes stop,
|
||||
* triggering the onStop callback, consequently leading to an infinite loop. **/
|
||||
nativeAudio.destroy();
|
||||
}
|
||||
};
|
||||
nativeAudio.onEnded(endCallback);
|
||||
nativeAudio.onStop(endCallback);//OneShotAudio can not be reused.
|
||||
|
||||
// event
|
||||
systemInfo.on('hide', this._onInterruptedBegin, this);
|
||||
systemInfo.on('show', this._onInterruptedEnd, this);
|
||||
}
|
||||
|
||||
private _onInterruptedBegin (): void {
|
||||
this._innerAudioContext.pause();
|
||||
}
|
||||
|
||||
private _onInterruptedEnd (): void {
|
||||
this._innerAudioContext.play();
|
||||
}
|
||||
|
||||
public play (): void {
|
||||
this._innerAudioContext.play();
|
||||
}
|
||||
public stop (): void {
|
||||
this._innerAudioContext.stop();
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayerMinigame implements OperationQueueable {
|
||||
private declare _innerAudioContext: InnerAudioContext;
|
||||
private _state: AudioState = AudioState.INIT;
|
||||
private _cacheTime = 0;
|
||||
private _needSeek = false;
|
||||
private _seeking = false;
|
||||
|
||||
private declare _onPlay: () => void;
|
||||
private declare _onPause: () => void;
|
||||
private declare _onStop: () => void;
|
||||
private declare _onSeeked: () => void;
|
||||
private declare _onEnded: () => void;
|
||||
private _readyToHandleOnShow = false;
|
||||
|
||||
private _resetSeekCache (): void {
|
||||
this._cacheTime = 0;
|
||||
this._needSeek = false;
|
||||
this._seeking = false;
|
||||
if ((HUAWEI || VIVO || OPPO) && this._innerAudioContext) {
|
||||
this._innerAudioContext.startTime = 0;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _eventTarget: EventTarget = new EventTarget();
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _operationQueue: OperationInfo[] = [];
|
||||
|
||||
constructor (innerAudioContext: InnerAudioContext) {
|
||||
const self = this;
|
||||
self._innerAudioContext = innerAudioContext;
|
||||
|
||||
// event
|
||||
systemInfo.on('hide', self._onInterruptedBegin, self);
|
||||
systemInfo.on('show', self._onInterruptedEnd, self);
|
||||
const eventTarget = self._eventTarget;
|
||||
self._onPlay = (): void => {
|
||||
self._state = AudioState.PLAYING;
|
||||
eventTarget.emit(AudioEvent.PLAYED);
|
||||
if (self._needSeek) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
self.seek(self._cacheTime).catch((e) => {});
|
||||
}
|
||||
};
|
||||
innerAudioContext.onPlay(self._onPlay);
|
||||
self._onPause = (): void => {
|
||||
self._state = AudioState.PAUSED;
|
||||
try {
|
||||
const currentTime = self._innerAudioContext.currentTime;
|
||||
if (currentTime !== null && currentTime !== undefined) {
|
||||
self._cacheTime = currentTime;
|
||||
}
|
||||
} catch {
|
||||
// Do nothing, cacheTime is not updated.
|
||||
}
|
||||
eventTarget.emit(AudioEvent.PAUSED);
|
||||
};
|
||||
innerAudioContext.onPause(self._onPause);
|
||||
self._onStop = (): void => {
|
||||
self._state = AudioState.STOPPED;
|
||||
// Reset all properties
|
||||
self._resetSeekCache();
|
||||
eventTarget.emit(AudioEvent.STOPPED);
|
||||
if (TAOBAO || TAOBAO_MINIGAME) {
|
||||
/**Unable to seek again after stop; After stop, regardless of whether the starttime has been set,
|
||||
the playback will always start from 0 again**/
|
||||
} else {
|
||||
const currentTime = self._innerAudioContext ? self._innerAudioContext.currentTime : 0;
|
||||
if (currentTime !== 0) {
|
||||
self._innerAudioContext.seek(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
innerAudioContext.onStop(self._onStop);
|
||||
self._onSeeked = (): void => {
|
||||
eventTarget.emit(AudioEvent.SEEKED);
|
||||
self._seeking = false;
|
||||
if (self._needSeek) {
|
||||
self._needSeek = false;
|
||||
if (self._cacheTime.toFixed(2) !== self._innerAudioContext.currentTime.toFixed(2)) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
self.seek(self._cacheTime).catch((e) => {});
|
||||
}
|
||||
}
|
||||
};
|
||||
innerAudioContext.onSeeked(self._onSeeked);
|
||||
self._onEnded = (): void => {
|
||||
self._state = AudioState.INIT;
|
||||
self._resetSeekCache();
|
||||
eventTarget.emit(AudioEvent.ENDED);
|
||||
};
|
||||
innerAudioContext.onEnded(self._onEnded);
|
||||
}
|
||||
destroy (): void {
|
||||
const self = this;
|
||||
systemInfo.off('hide', self._onInterruptedBegin, self);
|
||||
systemInfo.off('show', self._onInterruptedEnd, self);
|
||||
const innerAudioContext = self._innerAudioContext;
|
||||
if (innerAudioContext) {
|
||||
['Play', 'Pause', 'Stop', 'Seeked', 'Ended'].forEach((event) => {
|
||||
self._offEvent(event);
|
||||
});
|
||||
// NOTE: innerAudioContext might not stop the audio playing, have to call it explicitly.
|
||||
innerAudioContext.stop();
|
||||
innerAudioContext.destroy();
|
||||
// NOTE: Type 'null' is not assignable to type 'InnerAudioContext'
|
||||
self._innerAudioContext = null as any;
|
||||
// Restore the state of the audio, otherwise it will cause 'destroy' to be called first and 'stop' to be called later.
|
||||
// this will cause a error.
|
||||
self._state = AudioState.INIT;
|
||||
}
|
||||
}
|
||||
private _onInterruptedBegin (): void {
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
this.pause().then(() => {
|
||||
this._state = AudioState.INTERRUPTED;
|
||||
this._readyToHandleOnShow = true;
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
}).catch((e) => {});
|
||||
}
|
||||
}
|
||||
private _onInterruptedEnd (): void {
|
||||
// We don't know whether onShow or resolve callback in pause promise is called at first.
|
||||
if (!this._readyToHandleOnShow) {
|
||||
this._eventTarget.once(AudioEvent.INTERRUPTION_END, this._onInterruptedEnd, this);
|
||||
return;
|
||||
}
|
||||
if (this._state === AudioState.INTERRUPTED) {
|
||||
this.play().then(() => {
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_END);
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
}).catch((e) => {});
|
||||
}
|
||||
this._readyToHandleOnShow = false;
|
||||
}
|
||||
private _offEvent (eventName: string): void {
|
||||
if (this[`_on${eventName}`]) {
|
||||
this._innerAudioContext[`off${eventName}`](this[`_on${eventName}`]);
|
||||
this[`_on${eventName}`] = null;
|
||||
}
|
||||
}
|
||||
|
||||
get src (): string {
|
||||
return this._innerAudioContext ? this._innerAudioContext.src : '';
|
||||
}
|
||||
get type (): AudioType {
|
||||
return AudioType.MINIGAME_AUDIO;
|
||||
}
|
||||
static load (url: string): Promise<AudioPlayerMinigame> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerMinigame.loadNative(url).then((innerAudioContext) => {
|
||||
resolve(new AudioPlayerMinigame(innerAudioContext as InnerAudioContext));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
static loadNative (url: string): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const innerAudioContext = minigame.createInnerAudioContext();
|
||||
const timer = setTimeout(() => {
|
||||
clearEvent();
|
||||
resolve(innerAudioContext);
|
||||
}, 8000);
|
||||
function clearEvent (): void {
|
||||
innerAudioContext.offCanplay(success);
|
||||
innerAudioContext.offError(fail);
|
||||
}
|
||||
function success (): void {
|
||||
clearEvent();
|
||||
clearTimeout(timer);
|
||||
resolve(innerAudioContext);
|
||||
}
|
||||
function fail (err): void {
|
||||
clearEvent();
|
||||
clearTimeout(timer);
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('failed to load innerAudioContext');
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
reject(new Error(err));
|
||||
}
|
||||
innerAudioContext.onCanplay(success);
|
||||
innerAudioContext.onError(fail);
|
||||
innerAudioContext.src = url;
|
||||
});
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number): Promise<OneShotAudioMinigame> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerMinigame.loadNative(url).then((innerAudioContext) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
resolve(new (OneShotAudioMinigame as any)(innerAudioContext, volume));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
get state (): AudioState {
|
||||
return this._state;
|
||||
}
|
||||
get loop (): boolean {
|
||||
return this._innerAudioContext.loop;
|
||||
}
|
||||
set loop (val: boolean) {
|
||||
this._innerAudioContext.loop = val;
|
||||
}
|
||||
get volume (): number {
|
||||
return this._innerAudioContext.volume;
|
||||
}
|
||||
set volume (val: number) {
|
||||
val = clamp01(val);
|
||||
this._innerAudioContext.volume = val;
|
||||
}
|
||||
get duration (): number {
|
||||
// KNOWN ISSUES: duration doesn't work well
|
||||
// On WeChat platform, duration is 0 at the time audio is loaded.
|
||||
return this._innerAudioContext.duration;
|
||||
}
|
||||
get currentTime (): number {
|
||||
if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) {
|
||||
return this._innerAudioContext.startTime;
|
||||
}
|
||||
if (this._state !== AudioState.PLAYING || this._needSeek || this._seeking) {
|
||||
return this._cacheTime;
|
||||
}
|
||||
return this._innerAudioContext.currentTime;
|
||||
}
|
||||
|
||||
get sampleRate (): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public getPCMData (channelIndex: number): AudioPCMDataView | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
seek (time: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
// KNOWN ISSUES: on Baidu: currentTime returns without numbers on decimal places
|
||||
if (this._state === AudioState.PLAYING && !this._seeking) {
|
||||
time = clamp(time, 0, this.duration);
|
||||
this._seeking = true;
|
||||
this._cacheTime = time;
|
||||
this._eventTarget.once(AudioEvent.SEEKED, resolve);
|
||||
this._innerAudioContext.seek(time);
|
||||
} else {
|
||||
//Huawei, vivo, Oppo platform, after stop, regardless of whether the seek has been called, the playback will always start from 0 again
|
||||
if ((HUAWEI || VIVO || OPPO) && (this._state === AudioState.STOPPED || this._state === AudioState.INIT)) {
|
||||
this._innerAudioContext.startTime = time;
|
||||
} else if (this._cacheTime !== time) { // Skip the invalid seek
|
||||
this._cacheTime = time;
|
||||
this._needSeek = true;
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
play (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this._eventTarget.once(AudioEvent.PLAYED, resolve);
|
||||
this._innerAudioContext.play();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
pause (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (this.state !== AudioState.PLAYING) {
|
||||
resolve();
|
||||
} else {
|
||||
this._eventTarget.once(AudioEvent.PAUSED, resolve);
|
||||
this._innerAudioContext.pause();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
stop (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (AudioState.INIT === this._state) {
|
||||
this._resetSeekCache();
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
this._eventTarget.once(AudioEvent.STOPPED, resolve);
|
||||
this._innerAudioContext.stop();
|
||||
});
|
||||
}
|
||||
|
||||
onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); }
|
||||
onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); }
|
||||
offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); }
|
||||
}
|
||||
@@ -1,323 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { clamp01 } from '../../../cocos/core';
|
||||
import * as debug from '../../../cocos/core/platform/debug';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { audioBufferManager } from '../audio-buffer-manager';
|
||||
import AudioTimer from '../audio-timer';
|
||||
import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue';
|
||||
import { AudioEvent, AudioPCMDataView, AudioState, AudioType } from '../type';
|
||||
import { Game, game } from '../../../cocos/game';
|
||||
|
||||
declare const fsUtils: any;
|
||||
const audioContext = minigame.tt?.getAudioContext?.();
|
||||
|
||||
export class OneShotAudioWeb {
|
||||
private _bufferSourceNode: AudioBufferSourceNode;
|
||||
private _onPlayCb?: () => void;
|
||||
private _url: string;
|
||||
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._onPlayCb;
|
||||
}
|
||||
set onPlay (cb) {
|
||||
this._onPlayCb = cb;
|
||||
}
|
||||
|
||||
private _onEndCb?: () => void;
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._onEndCb;
|
||||
}
|
||||
set onEnd (cb) {
|
||||
this._onEndCb = cb;
|
||||
}
|
||||
|
||||
private constructor (audioBuffer: AudioBuffer, volume: number, url: string) {
|
||||
this._bufferSourceNode = audioContext!.createBufferSource();
|
||||
this._bufferSourceNode.buffer = audioBuffer;
|
||||
this._bufferSourceNode.loop = false;
|
||||
this._url = url;
|
||||
|
||||
const gainNode = audioContext!.createGain();
|
||||
gainNode.gain.value = volume;
|
||||
|
||||
this._bufferSourceNode.connect(gainNode);
|
||||
gainNode.connect(audioContext!.destination);
|
||||
}
|
||||
|
||||
public play (): void {
|
||||
this._bufferSourceNode.start();
|
||||
this.onPlay?.();
|
||||
this._bufferSourceNode.onended = (): void => {
|
||||
audioBufferManager.tryReleasingCache(this._url);
|
||||
this._onEndCb?.();
|
||||
};
|
||||
}
|
||||
|
||||
public stop (): void {
|
||||
this._bufferSourceNode.onended = null; // stop will call ended callback
|
||||
audioBufferManager.tryReleasingCache(this._url);
|
||||
this._bufferSourceNode.stop();
|
||||
this._bufferSourceNode.disconnect();
|
||||
this._bufferSourceNode.buffer = null;
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayerWeb implements OperationQueueable {
|
||||
private _src: string;
|
||||
private _audioBuffer: AudioBuffer;
|
||||
private _sourceNode?: AudioBufferSourceNode;
|
||||
private _gainNode: GainNode;
|
||||
private _volume = 1;
|
||||
private _loop = false;
|
||||
private _state: AudioState = AudioState.INIT;
|
||||
private _audioTimer: AudioTimer;
|
||||
private _readyToHandleOnShow = false;
|
||||
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _eventTarget: EventTarget = new EventTarget();
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _operationQueue: OperationInfo[] = [];
|
||||
|
||||
constructor (audioBuffer: AudioBuffer, url: string) {
|
||||
this._audioBuffer = audioBuffer;
|
||||
this._audioTimer = new AudioTimer(audioBuffer);
|
||||
this._gainNode = audioContext!.createGain();
|
||||
this._gainNode.connect(audioContext!.destination);
|
||||
|
||||
this._src = url;
|
||||
// event
|
||||
game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
}
|
||||
destroy (): void {
|
||||
this._audioTimer.destroy();
|
||||
if (this._audioBuffer) {
|
||||
// NOTE: need to release AudioBuffer instance
|
||||
this._audioBuffer = null as any;
|
||||
}
|
||||
audioBufferManager.tryReleasingCache(this._src);
|
||||
game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
}
|
||||
private _onInterruptedBegin (): void {
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
this.pause().then(() => {
|
||||
this._state = AudioState.INTERRUPTED;
|
||||
this._readyToHandleOnShow = true;
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
|
||||
}).catch((e) => { debug.warn('_onInterruptedBegin error', e); });
|
||||
}
|
||||
}
|
||||
private _onInterruptedEnd (): void {
|
||||
// We don't know whether onShow or resolve callback in pause promise is called at first.
|
||||
if (!this._readyToHandleOnShow) {
|
||||
this._eventTarget.once(AudioEvent.INTERRUPTION_BEGIN, this._onInterruptedEnd, this);
|
||||
return;
|
||||
}
|
||||
if (this._state === AudioState.INTERRUPTED) {
|
||||
this.play().then(() => {
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_END);
|
||||
}).catch((e) => { debug.warn('_onInterruptedEnd error', e); });
|
||||
}
|
||||
this._readyToHandleOnShow = false;
|
||||
}
|
||||
static load (url: string): Promise<AudioPlayerWeb> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerWeb.loadNative(url).then((audioBuffer) => {
|
||||
resolve(new AudioPlayerWeb(audioBuffer, url));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
static loadNative (url: string): Promise<AudioBuffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// NOTE: maybe url is a temp path, which is not reliable.
|
||||
// need to cache the decoded audio buffer.
|
||||
const cachedAudioBuffer = audioBufferManager.getCache(url);
|
||||
if (cachedAudioBuffer) {
|
||||
audioBufferManager.retainCache(url);
|
||||
resolve(cachedAudioBuffer);
|
||||
return;
|
||||
}
|
||||
// TODO: use pal/fs
|
||||
globalThis.fsUtils.readArrayBuffer(url, (err: Error, arrayBuffer: ArrayBuffer) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
audioContext!.decodeAudioData(arrayBuffer).then((decodedAudioBuffer) => {
|
||||
audioBufferManager.addCache(url, decodedAudioBuffer);
|
||||
resolve(decodedAudioBuffer);
|
||||
}).catch(reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static loadOneShotAudio (url: string, volume: number): Promise<OneShotAudioWeb> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerWeb.loadNative(url).then((audioBuffer) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
const oneShotAudio = new (OneShotAudioWeb as any)(audioBuffer, volume, url);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
resolve(oneShotAudio);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
get src (): string {
|
||||
return this._src;
|
||||
}
|
||||
get type (): AudioType {
|
||||
return AudioType.WEB_AUDIO;
|
||||
}
|
||||
get state (): AudioState {
|
||||
return this._state;
|
||||
}
|
||||
get loop (): boolean {
|
||||
return this._loop;
|
||||
}
|
||||
set loop (val: boolean) {
|
||||
this._loop = val;
|
||||
if (this._sourceNode) {
|
||||
this._sourceNode.loop = val;
|
||||
}
|
||||
}
|
||||
get volume (): number {
|
||||
return this._volume;
|
||||
}
|
||||
set volume (val: number) {
|
||||
val = clamp01(val);
|
||||
this._volume = val;
|
||||
this._gainNode.gain.value = val;
|
||||
}
|
||||
get duration (): number {
|
||||
return this._audioBuffer.duration;
|
||||
}
|
||||
get currentTime (): number {
|
||||
return this._audioTimer.currentTime;
|
||||
}
|
||||
|
||||
get sampleRate (): number {
|
||||
return this._audioBuffer.sampleRate;
|
||||
}
|
||||
|
||||
public getPCMData (channelIndex: number): AudioPCMDataView | undefined {
|
||||
return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1);
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
seek (time: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this._audioTimer.seek(time);
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
// one AudioBufferSourceNode can't start twice
|
||||
// need to create a new one to start from the offset
|
||||
this._doPlay().then(resolve).catch((e) => { debug.warn('seek error', e); });
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
play (): Promise<void> {
|
||||
return this._doPlay();
|
||||
}
|
||||
|
||||
// The decorated play() method can't be call in seek()
|
||||
// so we define this method to ensure that the audio seeking works.
|
||||
private _doPlay (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
// one AudioBufferSourceNode can't start twice
|
||||
this._stopSourceNode();
|
||||
this._sourceNode = audioContext!.createBufferSource();
|
||||
this._sourceNode.buffer = this._audioBuffer;
|
||||
this._sourceNode.loop = this._loop;
|
||||
this._sourceNode.connect(this._gainNode);
|
||||
|
||||
this._sourceNode.start(0, this._audioTimer.currentTime);
|
||||
this._state = AudioState.PLAYING;
|
||||
this._audioTimer.start();
|
||||
|
||||
this._sourceNode.onended = (): void => {
|
||||
this._audioTimer.stop();
|
||||
this._eventTarget.emit(AudioEvent.ENDED);
|
||||
this._state = AudioState.INIT;
|
||||
};
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
private _stopSourceNode (): void {
|
||||
try {
|
||||
if (this._sourceNode) {
|
||||
this._sourceNode.onended = null; // stop will call ended callback
|
||||
this._sourceNode.stop();
|
||||
this._sourceNode.disconnect();
|
||||
this._sourceNode.buffer = null;
|
||||
this._sourceNode = undefined;
|
||||
}
|
||||
} catch (e) {
|
||||
// sourceNode can't be stopped twice, especially on Safari.
|
||||
}
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
pause (): Promise<void> {
|
||||
if (this._state !== AudioState.PLAYING || !this._sourceNode) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
this._audioTimer.pause();
|
||||
this._state = AudioState.PAUSED;
|
||||
this._stopSourceNode();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
stop (): Promise<void> {
|
||||
if (!this._sourceNode) {
|
||||
this._audioTimer.stop();
|
||||
this._state = AudioState.STOPPED;
|
||||
return Promise.resolve();
|
||||
}
|
||||
this._audioTimer.stop();
|
||||
this._state = AudioState.STOPPED;
|
||||
this._stopSourceNode();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); }
|
||||
onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); }
|
||||
offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); }
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { legacyCC } from '../../../cocos/core/global-exports';
|
||||
import { AudioLoadOptions, AudioType, AudioState, AudioPCMDataView } from '../type';
|
||||
import { AudioPlayerMinigame, OneShotAudioMinigame } from './player-minigame';
|
||||
import { AudioPlayerWeb, OneShotAudioWeb } from './player-web';
|
||||
|
||||
type AbstractOneShotAudio = OneShotAudioMinigame | OneShotAudioWeb;
|
||||
type AbstractAudioPlayer = AudioPlayerMinigame | AudioPlayerWeb;
|
||||
|
||||
export class OneShotAudio {
|
||||
private _audio: AbstractOneShotAudio;
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._audio.onPlay;
|
||||
}
|
||||
set onPlay (v) {
|
||||
this._audio.onPlay = v;
|
||||
}
|
||||
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._audio.onEnd;
|
||||
}
|
||||
set onEnd (v) {
|
||||
this._audio.onEnd = v;
|
||||
}
|
||||
|
||||
private constructor (audio: AbstractOneShotAudio) {
|
||||
this._audio = audio;
|
||||
}
|
||||
public play (): void {
|
||||
this._audio.play();
|
||||
}
|
||||
public stop (): void {
|
||||
this._audio.stop();
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayer {
|
||||
private _player: AbstractAudioPlayer;
|
||||
constructor (player: AbstractAudioPlayer) {
|
||||
this._player = player;
|
||||
}
|
||||
|
||||
static load (url: string, opts?: AudioLoadOptions): Promise<AudioPlayer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
/*if (typeof minigame.tt === 'object' && typeof minigame.tt.getAudioContext !== 'undefined') {
|
||||
AudioPlayerWeb.load(url).then((webPlayer) => {
|
||||
resolve(new AudioPlayer(webPlayer));
|
||||
}).catch(reject);
|
||||
} else {*/
|
||||
AudioPlayerMinigame.load(url).then((minigamePlayer) => {
|
||||
resolve(new AudioPlayer(minigamePlayer));
|
||||
}).catch(reject);
|
||||
// }
|
||||
});
|
||||
}
|
||||
destroy (): void {
|
||||
this._player.destroy();
|
||||
}
|
||||
static loadNative (url: string, opts?: AudioLoadOptions): Promise<unknown> {
|
||||
/*if (typeof minigame.tt === 'object' && typeof minigame.tt.getAudioContext !== 'undefined') {
|
||||
return AudioPlayerWeb.loadNative(url);
|
||||
}*/
|
||||
return AudioPlayerMinigame.loadNative(url);
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise<OneShotAudio> {
|
||||
return new Promise((resolve, reject) => {
|
||||
/*if (typeof minigame.tt === 'object' && typeof minigame.tt.getAudioContext !== 'undefined') {
|
||||
AudioPlayerWeb.loadOneShotAudio(url, volume).then((oneShotAudioWeb) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
resolve(new (OneShotAudio as any)(oneShotAudioWeb));
|
||||
}).catch(reject);
|
||||
} else {*/
|
||||
AudioPlayerMinigame.loadOneShotAudio(url, volume).then((oneShotAudioMinigame) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
resolve(new (OneShotAudio as any)(oneShotAudioMinigame));
|
||||
}).catch(reject);
|
||||
//}
|
||||
});
|
||||
}
|
||||
static readonly maxAudioChannel = 10;
|
||||
|
||||
get src (): string { return this._player.src; }
|
||||
get type (): AudioType { return this._player.type; }
|
||||
get state (): AudioState { return this._player.state; }
|
||||
get loop (): boolean { return this._player.loop; }
|
||||
set loop (val: boolean) { this._player.loop = val; }
|
||||
get volume (): number { return this._player.volume; }
|
||||
set volume (val: number) { this._player.volume = val; }
|
||||
get duration (): number { return this._player.duration; }
|
||||
get currentTime (): number { return this._player.currentTime; }
|
||||
get sampleRate (): number { return this._player.sampleRate; }
|
||||
getPCMData (channelIndex: number): AudioPCMDataView | undefined { return this._player.getPCMData(channelIndex); }
|
||||
seek (time: number): Promise<void> { return this._player.seek(time); }
|
||||
|
||||
play (): Promise<void> { return this._player.play(); }
|
||||
pause (): Promise<void> { return this._player.pause(); }
|
||||
stop (): Promise<void> { return this._player.stop(); }
|
||||
onInterruptionBegin (cb: () => void): void { this._player.onInterruptionBegin(cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._player.offInterruptionBegin(cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._player.onInterruptionEnd(cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._player.offInterruptionEnd(cb); }
|
||||
onEnded (cb: () => void): void { this._player.onEnded(cb); }
|
||||
offEnded (cb?: () => void): void { this._player.offEnded(cb); }
|
||||
}
|
||||
|
||||
// REMOVE_ME
|
||||
legacyCC.AudioPlayer = AudioPlayer;
|
||||
@@ -1,343 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { AudioType, AudioState, AudioEvent, AudioPCMDataView, AudioBufferView, AudioLoadOptions } from '../type';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { legacyCC } from '../../../cocos/core/global-exports';
|
||||
import { clamp, clamp01 } from '../../../cocos/core';
|
||||
import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue';
|
||||
import { Platform } from '../../system-info/enum-type';
|
||||
import { Game, game } from '../../../cocos/game';
|
||||
|
||||
const urlCount: Record<string, number> = {};
|
||||
const audioEngine = jsb.AudioEngine;
|
||||
const INVALID_AUDIO_ID = -1;
|
||||
|
||||
enum AudioBufferFormat {
|
||||
UNKNOWN = 0,
|
||||
SIGNED_8,
|
||||
UNSIGNED_8,
|
||||
SIGNED_16,
|
||||
UNSIGNED_16,
|
||||
SIGNED_32,
|
||||
UNSIGNED_32,
|
||||
FLOAT_32,
|
||||
FLOAT_64
|
||||
}
|
||||
|
||||
interface AudioBufferInfo {
|
||||
ctor: Constructor<AudioBufferView>,
|
||||
maxValue: number;
|
||||
}
|
||||
|
||||
const bufferConstructorMap: Record<number, AudioBufferInfo | undefined> = {
|
||||
[AudioBufferFormat.UNKNOWN]: undefined,
|
||||
[AudioBufferFormat.SIGNED_8]: { ctor: Int8Array, maxValue: 127 },
|
||||
[AudioBufferFormat.UNSIGNED_8]: { ctor: Uint8Array, maxValue: 255 },
|
||||
[AudioBufferFormat.SIGNED_16]: { ctor: Int16Array, maxValue: 32767 },
|
||||
[AudioBufferFormat.UNSIGNED_16]: { ctor: Uint16Array, maxValue: 65535 },
|
||||
[AudioBufferFormat.SIGNED_32]: { ctor: Int32Array, maxValue: 2147483647 },
|
||||
[AudioBufferFormat.UNSIGNED_32]: { ctor: Uint32Array, maxValue: 4294967295 },
|
||||
// decoded float data is normalized data, so we specify the maxValue as 1.
|
||||
[AudioBufferFormat.FLOAT_32]: { ctor: Float32Array, maxValue: 1 },
|
||||
[AudioBufferFormat.FLOAT_64]: { ctor: Float64Array, maxValue: 1 },
|
||||
};
|
||||
|
||||
export class OneShotAudio {
|
||||
private _id: number = INVALID_AUDIO_ID;
|
||||
private _url: string;
|
||||
private _volume: number;
|
||||
private _onPlayCb?: () => void;
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._onPlayCb;
|
||||
}
|
||||
set onPlay (cb) {
|
||||
this._onPlayCb = cb;
|
||||
}
|
||||
|
||||
private _onEndCb?: () => void;
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._onEndCb;
|
||||
}
|
||||
set onEnd (cb) {
|
||||
this._onEndCb = cb;
|
||||
}
|
||||
|
||||
private constructor (url: string, volume: number) {
|
||||
this._url = url;
|
||||
this._volume = volume;
|
||||
}
|
||||
public play (): void {
|
||||
this._id = jsb.AudioEngine.play2d(this._url, false, this._volume);
|
||||
jsb.AudioEngine.setFinishCallback(this._id, () => {
|
||||
this.onEnd?.();
|
||||
});
|
||||
this.onPlay?.();
|
||||
}
|
||||
public stop (): void {
|
||||
if (this._id === INVALID_AUDIO_ID) {
|
||||
return;
|
||||
}
|
||||
jsb.AudioEngine.stop(this._id);
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayer implements OperationQueueable {
|
||||
private _url: string;
|
||||
private _id: number = INVALID_AUDIO_ID;
|
||||
private _state: AudioState = AudioState.INIT;
|
||||
private _pcmHeader: jsb.PCMHeader | null;
|
||||
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _eventTarget: EventTarget = new EventTarget();
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _operationQueue: OperationInfo[] = [];
|
||||
|
||||
// NOTE: we need to cache the state in case the audio id is invalid.
|
||||
private _cachedState = {
|
||||
duration: 1, // wrong value before playing
|
||||
loop: false,
|
||||
currentTime: 0,
|
||||
volume: 1,
|
||||
}
|
||||
|
||||
constructor (url: string) {
|
||||
this._url = url;
|
||||
// this._pcmHeader = audioEngine.getPCMHeader(url);
|
||||
this._pcmHeader = null;
|
||||
// event
|
||||
game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
}
|
||||
destroy (): void {
|
||||
game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
if (--urlCount[this._url] <= 0) {
|
||||
audioEngine.uncache(this._url);
|
||||
}
|
||||
}
|
||||
private _onInterruptedBegin (): void {
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
this.pause().then(() => {
|
||||
this._state = AudioState.INTERRUPTED;
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
|
||||
}).catch((e) => {});
|
||||
}
|
||||
}
|
||||
private _onInterruptedEnd (): void {
|
||||
if (this._state === AudioState.INTERRUPTED) {
|
||||
this.play().then(() => {
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_END);
|
||||
}).catch((e) => {});
|
||||
}
|
||||
}
|
||||
static load (url: string, opts?: AudioLoadOptions): Promise<AudioPlayer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayer.loadNative(url, opts).then((url) => {
|
||||
resolve(new AudioPlayer(url as string));
|
||||
}).catch((err) => reject(err));
|
||||
});
|
||||
}
|
||||
static loadNative (url: string, opts?: AudioLoadOptions): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (systemInfo.platform === Platform.WIN32) {
|
||||
// NOTE: audioEngine.preload() not works well on Win32 platform.
|
||||
// Especially when there is not audio output device. But still need to preload
|
||||
audioEngine.preload(url, (isSuccess) => {
|
||||
console.debug('somehow preload success on windows');
|
||||
});
|
||||
resolve(url);
|
||||
} else {
|
||||
audioEngine.preload(url, (isSuccess) => {
|
||||
if (isSuccess) {
|
||||
resolve(url);
|
||||
} else {
|
||||
reject(new Error('load audio failed'));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise<OneShotAudio> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayer.loadNative(url, opts).then((url) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
resolve(new (OneShotAudio as any)(url, volume));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
static readonly maxAudioChannel: number = audioEngine.getMaxAudioInstance();
|
||||
|
||||
private get _isValid (): boolean {
|
||||
return this._id !== INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
get src (): string {
|
||||
return this._url;
|
||||
}
|
||||
get type (): AudioType {
|
||||
return AudioType.NATIVE_AUDIO;
|
||||
}
|
||||
get state (): AudioState {
|
||||
return this._state;
|
||||
}
|
||||
get loop (): boolean {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.loop;
|
||||
}
|
||||
return audioEngine.isLoop(this._id);
|
||||
}
|
||||
set loop (val: boolean) {
|
||||
if (this._isValid) {
|
||||
audioEngine.setLoop(this._id, val);
|
||||
}
|
||||
this._cachedState.loop = val;
|
||||
}
|
||||
get volume (): number {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.volume;
|
||||
}
|
||||
return audioEngine.getVolume(this._id);
|
||||
}
|
||||
set volume (val: number) {
|
||||
val = clamp01(val);
|
||||
if (this._isValid) {
|
||||
audioEngine.setVolume(this._id, val);
|
||||
}
|
||||
this._cachedState.volume = val;
|
||||
}
|
||||
get duration (): number {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.duration;
|
||||
}
|
||||
return audioEngine.getDuration(this._id);
|
||||
}
|
||||
get currentTime (): number {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.currentTime;
|
||||
}
|
||||
return audioEngine.getCurrentTime(this._id);
|
||||
}
|
||||
|
||||
get sampleRate (): number {
|
||||
if (this._pcmHeader === null) {
|
||||
this._pcmHeader = jsb.AudioEngine.getPCMHeader(this._url);
|
||||
}
|
||||
return this._pcmHeader.sampleRate;
|
||||
}
|
||||
|
||||
public getPCMData (channelIndex: number): AudioPCMDataView | undefined {
|
||||
const arrayBuffer = audioEngine.getOriginalPCMBuffer(this._url, channelIndex);
|
||||
if (this._pcmHeader === null) {
|
||||
this._pcmHeader = jsb.AudioEngine.getPCMHeader(this._url);
|
||||
}
|
||||
const audioBufferInfo = bufferConstructorMap[this._pcmHeader.audioFormat];
|
||||
if (!arrayBuffer || !audioBufferInfo) {
|
||||
return undefined;
|
||||
}
|
||||
return new AudioPCMDataView(arrayBuffer, audioBufferInfo.ctor, 1 / audioBufferInfo.maxValue);
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
seek (time: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
// Duration is invalid before player
|
||||
// time = clamp(time, 0, this.duration);
|
||||
if (this._isValid) {
|
||||
audioEngine.setCurrentTime(this._id, time);
|
||||
}
|
||||
this._cachedState.currentTime = time;
|
||||
return resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
play (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (this._isValid) {
|
||||
if (this._state === AudioState.PAUSED || this._state === AudioState.INTERRUPTED) {
|
||||
audioEngine.resume(this._id);
|
||||
} else if (this._state === AudioState.PLAYING) {
|
||||
audioEngine.pause(this._id);
|
||||
audioEngine.setCurrentTime(this._id, 0);
|
||||
audioEngine.resume(this._id);
|
||||
}
|
||||
} else {
|
||||
this._id = audioEngine.play2d(this._url, this._cachedState.loop, this._cachedState.volume);
|
||||
if (this._isValid) {
|
||||
if (this._cachedState.currentTime !== 0) {
|
||||
audioEngine.setCurrentTime(this._id, this._cachedState.currentTime);
|
||||
this._cachedState.currentTime = 0;
|
||||
}
|
||||
audioEngine.setFinishCallback(this._id, () => {
|
||||
this._cachedState.currentTime = 0;
|
||||
this._id = INVALID_AUDIO_ID;
|
||||
this._state = AudioState.INIT;
|
||||
this._eventTarget.emit(AudioEvent.ENDED);
|
||||
});
|
||||
}
|
||||
}
|
||||
this._state = AudioState.PLAYING;
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
pause (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (this._isValid) {
|
||||
audioEngine.pause(this._id);
|
||||
}
|
||||
this._state = AudioState.PAUSED;
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
stop (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (this._isValid) {
|
||||
audioEngine.stop(this._id);
|
||||
}
|
||||
this._state = AudioState.STOPPED;
|
||||
this._id = INVALID_AUDIO_ID;
|
||||
this._cachedState.currentTime = 0;
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); }
|
||||
onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); }
|
||||
offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); }
|
||||
}
|
||||
|
||||
// REMOVE_ME
|
||||
legacyCC.AudioPlayer = AudioPlayer;
|
||||
@@ -1,246 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { AudioType, AudioState, AudioEvent, AudioPCMDataView, AudioBufferView, AudioLoadOptions } from '../type';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { legacyCC } from '../../../cocos/core/global-exports';
|
||||
import { clamp, clamp01 } from '../../../cocos/core';
|
||||
import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue';
|
||||
import { Platform } from '../../system-info/enum-type';
|
||||
|
||||
const urlCount: Record<string, number> = {};
|
||||
const INVALID_AUDIO_ID = -1;
|
||||
|
||||
enum AudioBufferFormat {
|
||||
UNKNOWN = 0,
|
||||
SIGNED_8,
|
||||
UNSIGNED_8,
|
||||
SIGNED_16,
|
||||
UNSIGNED_16,
|
||||
SIGNED_32,
|
||||
UNSIGNED_32,
|
||||
FLOAT_32,
|
||||
FLOAT_64
|
||||
}
|
||||
|
||||
interface AudioBufferInfo {
|
||||
ctor: Constructor<AudioBufferView>,
|
||||
maxValue: number;
|
||||
}
|
||||
|
||||
const bufferConstructorMap: Record<number, AudioBufferInfo | undefined> = {
|
||||
[AudioBufferFormat.UNKNOWN]: undefined,
|
||||
[AudioBufferFormat.SIGNED_8]: { ctor: Int8Array, maxValue: 127 },
|
||||
[AudioBufferFormat.UNSIGNED_8]: { ctor: Uint8Array, maxValue: 255 },
|
||||
[AudioBufferFormat.SIGNED_16]: { ctor: Int16Array, maxValue: 32767 },
|
||||
[AudioBufferFormat.UNSIGNED_16]: { ctor: Uint16Array, maxValue: 65535 },
|
||||
[AudioBufferFormat.SIGNED_32]: { ctor: Int32Array, maxValue: 2147483647 },
|
||||
[AudioBufferFormat.UNSIGNED_32]: { ctor: Uint32Array, maxValue: 4294967295 },
|
||||
// decoded float data is normalized data, so we specify the maxValue as 1.
|
||||
[AudioBufferFormat.FLOAT_32]: { ctor: Float32Array, maxValue: 1 },
|
||||
[AudioBufferFormat.FLOAT_64]: { ctor: Float64Array, maxValue: 1 },
|
||||
};
|
||||
|
||||
export class OneShotAudio {
|
||||
private _id: number = INVALID_AUDIO_ID;
|
||||
private _onPlayCb?: () => void;
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._onPlayCb;
|
||||
}
|
||||
set onPlay (cb) {
|
||||
this._onPlayCb = cb;
|
||||
}
|
||||
|
||||
private _onEndCb?: () => void;
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._onEndCb;
|
||||
}
|
||||
set onEnd (cb) {
|
||||
this._onEndCb = cb;
|
||||
}
|
||||
|
||||
private constructor (url: string, volume: number) {
|
||||
}
|
||||
public play (): void {
|
||||
|
||||
}
|
||||
public stop (): void {
|
||||
if (this._id === INVALID_AUDIO_ID) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayer implements OperationQueueable {
|
||||
private _id: number = INVALID_AUDIO_ID;
|
||||
private _state: AudioState = AudioState.INIT;
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _eventTarget: EventTarget = new EventTarget();
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _operationQueue: OperationInfo[] = [];
|
||||
|
||||
// NOTE: we need to cache the state in case the audio id is invalid.
|
||||
private _cachedState = {
|
||||
duration: 1, // wrong value before playing
|
||||
loop: false,
|
||||
currentTime: 0,
|
||||
volume: 1,
|
||||
}
|
||||
|
||||
constructor (url: string) {
|
||||
|
||||
}
|
||||
destroy (): void {
|
||||
|
||||
}
|
||||
|
||||
static load (url: string, opts?: AudioLoadOptions): Promise<AudioPlayer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayer.loadNative(url, opts).then((url) => {
|
||||
resolve(new AudioPlayer(url as string));
|
||||
}).catch((err) => reject(err));
|
||||
});
|
||||
}
|
||||
static loadNative (url: string, opts?: AudioLoadOptions): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Todo(qgh): We need to parse the audio file, but this feature is not yet implemented.
|
||||
console.warn("Audio file parsing is not supported.");
|
||||
resolve(url);
|
||||
});
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise<OneShotAudio> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayer.loadNative(url, opts).then((url) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
resolve(new (OneShotAudio as any)(url, volume));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
private get _isValid (): boolean {
|
||||
return this._id !== INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
get src (): string {
|
||||
return "";
|
||||
}
|
||||
get type (): AudioType {
|
||||
return AudioType.NATIVE_AUDIO;
|
||||
}
|
||||
get state (): AudioState {
|
||||
return this._state;
|
||||
}
|
||||
get loop (): boolean {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.loop;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
set loop (val: boolean) {
|
||||
if (this._isValid) {
|
||||
}
|
||||
this._cachedState.loop = val;
|
||||
}
|
||||
get volume (): number {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.volume;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
set volume (val: number) {
|
||||
val = clamp01(val);
|
||||
if (this._isValid) {
|
||||
}
|
||||
this._cachedState.volume = val;
|
||||
}
|
||||
get duration (): number {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.duration;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
get currentTime (): number {
|
||||
if (!this._isValid) {
|
||||
return this._cachedState.currentTime;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
get sampleRate (): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public getPCMData (channelIndex: number): AudioPCMDataView | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
seek (time: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
// Duration is invalid before player
|
||||
// time = clamp(time, 0, this.duration);
|
||||
if (this._isValid) {
|
||||
}
|
||||
this._cachedState.currentTime = time;
|
||||
return resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
play (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
pause (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
stop (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); }
|
||||
onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); }
|
||||
offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); }
|
||||
}
|
||||
|
||||
// REMOVE_ME
|
||||
legacyCC.AudioPlayer = AudioPlayer;
|
||||
@@ -1,122 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventTarget } from '../../cocos/core';
|
||||
|
||||
type OperationMethod = (...args: any[]) => Promise<void>;
|
||||
export interface OperationInfo {
|
||||
op: string;
|
||||
id: number;
|
||||
func: OperationMethod;
|
||||
args: any[],
|
||||
invoking: boolean,
|
||||
}
|
||||
|
||||
/** @mangle */
|
||||
export interface OperationQueueable {
|
||||
_operationQueue: OperationInfo[];
|
||||
_eventTarget: EventTarget;
|
||||
}
|
||||
|
||||
function removeUnneededCalls (instance: OperationQueueable): void {
|
||||
const size = instance._operationQueue.length;
|
||||
const tmpQueue = instance._operationQueue.slice();
|
||||
const reserveOps: OperationInfo[] = [];
|
||||
let seekSearched = false;
|
||||
for (let i = size - 1; i >= 0; i--) {
|
||||
const opInfo = tmpQueue[i];
|
||||
if (opInfo.op === 'stop') {
|
||||
reserveOps.push(opInfo);
|
||||
break;
|
||||
} else if (opInfo.op === 'seek') {
|
||||
if (!seekSearched) {
|
||||
reserveOps.push(opInfo);
|
||||
seekSearched = true;
|
||||
}
|
||||
} else if (seekSearched) {
|
||||
reserveOps.push(opInfo);
|
||||
break;
|
||||
} else if (reserveOps.length === 0) {
|
||||
reserveOps.push(opInfo);
|
||||
}
|
||||
}
|
||||
instance._operationQueue = reserveOps.reverse();
|
||||
}
|
||||
|
||||
let operationId = 0;
|
||||
function _tryCallingRecursively<T extends OperationQueueable> (target: T, opInfo: OperationInfo): void {
|
||||
if (opInfo.invoking) {
|
||||
return;
|
||||
}
|
||||
opInfo.invoking = true;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
opInfo.func.call(target, ...opInfo.args).then(() => {
|
||||
opInfo.invoking = false;
|
||||
target._operationQueue.shift();
|
||||
target._eventTarget.emit(opInfo.id.toString());
|
||||
target._eventTarget.off(opInfo.id.toString()); // remove the key from _eventTarget._callbackTable
|
||||
removeUnneededCalls(target);
|
||||
const nextOpInfo: OperationInfo = target._operationQueue[0];
|
||||
if (nextOpInfo) {
|
||||
_tryCallingRecursively(target, nextOpInfo);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
}).catch((e) => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a method decorator for media player class such as Audio or Video.
|
||||
* Most of the operations in media player are asynchronous.
|
||||
* When all these asynchronous operations are called concurrently, they need to be queued.
|
||||
*
|
||||
* Note: the decorated class need to implement the interface `OperationQueueable`
|
||||
* and the decorated method should be declared as `(...args: any[]): Promise<void>`.
|
||||
*
|
||||
* When you apply `enqueueOperation` on a method, remember to provide a pure operation implementation.
|
||||
* It means that, for example, you can't call stop in the implementation of play operation,
|
||||
* because that would cause the operation deadlock.
|
||||
*/
|
||||
// eslint-disable-next-line max-len
|
||||
export function enqueueOperation<T extends OperationQueueable> (target: T, propertyKey: string, descriptor: TypedPropertyDescriptor<OperationMethod>): void {
|
||||
const originalOperation = descriptor.value!;
|
||||
// eslint-disable-next-line func-names
|
||||
descriptor.value = function (...args: any[]): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const id = operationId++;
|
||||
const instance = this as OperationQueueable;
|
||||
// enqueue operation
|
||||
instance._operationQueue.push({
|
||||
op: propertyKey,
|
||||
id,
|
||||
func: originalOperation,
|
||||
args,
|
||||
invoking: false,
|
||||
});
|
||||
// call resolve when this operation id is finishied
|
||||
instance._eventTarget.once(id.toString(), resolve);
|
||||
const opInfo: OperationInfo = instance._operationQueue[0];
|
||||
_tryCallingRecursively(instance, opInfo);
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum AudioEvent {
|
||||
PLAYED = 'play',
|
||||
PAUSED = 'pause',
|
||||
STOPPED = 'stop',
|
||||
SEEKED = 'seeked',
|
||||
ENDED = 'ended',
|
||||
INTERRUPTION_BEGIN = 'interruptionBegin',
|
||||
INTERRUPTION_END = 'interruptionEnd',
|
||||
USER_GESTURE = 'on_gesture', // only web needed
|
||||
}
|
||||
|
||||
export enum AudioType {
|
||||
DOM_AUDIO,
|
||||
WEB_AUDIO,
|
||||
MINIGAME_AUDIO,
|
||||
NATIVE_AUDIO,
|
||||
UNKNOWN_AUDIO,
|
||||
}
|
||||
|
||||
export interface AudioLoadOptions {
|
||||
audioLoadMode?: AudioType,
|
||||
}
|
||||
|
||||
export enum AudioState {
|
||||
INIT,
|
||||
PLAYING,
|
||||
PAUSED,
|
||||
STOPPED,
|
||||
INTERRUPTED,
|
||||
}
|
||||
|
||||
export type AudioBufferView = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
|
||||
|
||||
export class AudioPCMDataView {
|
||||
private _bufferView: AudioBufferView;
|
||||
private _normalizeFactor = 1;
|
||||
|
||||
constructor (arrayBufferView: AudioBufferView, normalizeFactor: number);
|
||||
constructor (arrayBuffer: ArrayBuffer, Ctor: Constructor<AudioBufferView>, normalizeFactor: number);
|
||||
constructor (...args: any[]) {
|
||||
if (args.length === 2) {
|
||||
this._bufferView = args[0] as AudioBufferView;
|
||||
this._normalizeFactor = args[1] as number;
|
||||
} else {
|
||||
const arrayBuffer = args[0] as ArrayBuffer;
|
||||
const Ctor = args[1] as Constructor<AudioBufferView>;
|
||||
const normalizeFactor = args[2] as number;
|
||||
this._bufferView = new Ctor(arrayBuffer);
|
||||
this._normalizeFactor = normalizeFactor;
|
||||
}
|
||||
}
|
||||
|
||||
get length (): number {
|
||||
return this._bufferView.length;
|
||||
}
|
||||
|
||||
public getData (offset: number): number {
|
||||
return this._bufferView[offset] * this._normalizeFactor;
|
||||
}
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { AudioEvent, AudioState, AudioPCMDataView, AudioType } from '../type';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { clamp, clamp01 } from '../../../cocos/core';
|
||||
import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue';
|
||||
import { BrowserType, OS } from '../../system-info/enum-type';
|
||||
import { Game, game } from '../../../cocos/game';
|
||||
|
||||
function ensurePlaying (domAudio: HTMLAudioElement): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const promise = domAudio.play();
|
||||
if (promise === undefined) { // Chrome50/Firefox53 below
|
||||
return resolve();
|
||||
}
|
||||
promise.then(resolve).catch((): void => {
|
||||
const onGesture = (): void => {
|
||||
domAudio.play().then(() => {
|
||||
// HACK NOTE: if the user slide after touch start, the context cannot be resumed correctly.
|
||||
canvas?.removeEventListener('touchend', onGesture, { capture: true });
|
||||
canvas?.removeEventListener('mouseup', onGesture, { capture: true });
|
||||
}).catch((e) => {});
|
||||
resolve();
|
||||
};
|
||||
const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
|
||||
canvas?.addEventListener('touchend', onGesture, { capture: true });
|
||||
canvas?.addEventListener('mouseup', onGesture, { capture: true });
|
||||
});
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
export class OneShotAudioDOM {
|
||||
private _domAudio: HTMLAudioElement;
|
||||
private _onPlayCb?: () => void;
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._onPlayCb;
|
||||
}
|
||||
set onPlay (cb) {
|
||||
this._onPlayCb = cb;
|
||||
}
|
||||
|
||||
private _onEndCb?: () => void;
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._onEndCb;
|
||||
}
|
||||
set onEnd (cb) {
|
||||
if (this._onEndCb) {
|
||||
this._domAudio.removeEventListener('ended', this._onEndCb);
|
||||
}
|
||||
this._onEndCb = cb;
|
||||
if (cb) {
|
||||
this._domAudio.addEventListener('ended', cb);
|
||||
}
|
||||
}
|
||||
|
||||
private constructor (nativeAudio: HTMLAudioElement, volume: number) {
|
||||
this._domAudio = nativeAudio;
|
||||
nativeAudio.volume = volume;
|
||||
}
|
||||
public play (): void {
|
||||
ensurePlaying(this._domAudio).then(() => {
|
||||
this.onPlay?.();
|
||||
}).catch((e) => {});
|
||||
}
|
||||
public stop (): void {
|
||||
this._domAudio.pause();
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayerDOM implements OperationQueueable {
|
||||
private _domAudio: HTMLAudioElement;
|
||||
private _state: AudioState = AudioState.INIT;
|
||||
private _onEnded: () => void;
|
||||
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _eventTarget: EventTarget = new EventTarget();
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _operationQueue: OperationInfo[] = [];
|
||||
|
||||
constructor (nativeAudio: HTMLAudioElement) {
|
||||
this._domAudio = nativeAudio;
|
||||
|
||||
// event
|
||||
game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
this._onEnded = (): void => {
|
||||
this.seek(0).catch((e) => {});
|
||||
this._state = AudioState.INIT;
|
||||
this._eventTarget.emit(AudioEvent.ENDED);
|
||||
};
|
||||
this._domAudio.addEventListener('ended', this._onEnded);
|
||||
}
|
||||
|
||||
destroy (): void {
|
||||
game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
this._domAudio.removeEventListener('ended', this._onEnded);
|
||||
// NOTE: need to release DOM Audio instance
|
||||
this._domAudio = null as any;
|
||||
}
|
||||
static load (url: string): Promise<AudioPlayerDOM> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerDOM.loadNative(url).then((domAudio) => {
|
||||
resolve(new AudioPlayerDOM(domAudio));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
static loadNative (url: string): Promise<HTMLAudioElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const domAudio = document.createElement('audio');
|
||||
let loadedEvent = 'canplaythrough';
|
||||
if (systemInfo.os === OS.IOS) {
|
||||
// iOS no event that used to parse completed callback
|
||||
// this time is not complete, can not play
|
||||
loadedEvent = 'loadedmetadata';
|
||||
} else if (systemInfo.browserType === BrowserType.FIREFOX) {
|
||||
loadedEvent = 'canplay';
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (domAudio.readyState === 0) {
|
||||
failure();
|
||||
} else {
|
||||
success();
|
||||
}
|
||||
}, 8000);
|
||||
const clearEvent = (): void => {
|
||||
clearTimeout(timer);
|
||||
domAudio.removeEventListener(loadedEvent, success, false);
|
||||
domAudio.removeEventListener('error', failure, false);
|
||||
};
|
||||
const success = (): void => {
|
||||
clearEvent();
|
||||
resolve(domAudio);
|
||||
};
|
||||
const failure = (): void => {
|
||||
clearEvent();
|
||||
const message = `load audio failure - ${url}`;
|
||||
reject(new Error(message));
|
||||
};
|
||||
domAudio.addEventListener(loadedEvent, success, false);
|
||||
domAudio.addEventListener('error', failure, false);
|
||||
domAudio.src = url;
|
||||
});
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number): Promise<OneShotAudioDOM> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerDOM.loadNative(url).then((domAudio) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
const oneShotAudio = new (OneShotAudioDOM as any)(domAudio, volume);
|
||||
resolve(oneShotAudio);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
private _onInterruptedBegin (): void {
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
this.pause().then(() => {
|
||||
this._state = AudioState.INTERRUPTED;
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
|
||||
}).catch((e) => {});
|
||||
}
|
||||
}
|
||||
private _onInterruptedEnd (): void {
|
||||
if (this._state === AudioState.INTERRUPTED) {
|
||||
this.play().then(() => {
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_END);
|
||||
}).catch((e) => {});
|
||||
}
|
||||
}
|
||||
|
||||
get src (): string {
|
||||
return this._domAudio ? this._domAudio.src : '';
|
||||
}
|
||||
get type (): AudioType {
|
||||
return AudioType.DOM_AUDIO;
|
||||
}
|
||||
get state (): AudioState {
|
||||
return this._state;
|
||||
}
|
||||
get loop (): boolean {
|
||||
return this._domAudio.loop;
|
||||
}
|
||||
set loop (val: boolean) {
|
||||
this._domAudio.loop = val;
|
||||
}
|
||||
get volume (): number {
|
||||
return this._domAudio.volume;
|
||||
}
|
||||
set volume (val: number) {
|
||||
val = clamp01(val);
|
||||
this._domAudio.volume = val;
|
||||
}
|
||||
get duration (): number {
|
||||
return this._domAudio.duration;
|
||||
}
|
||||
get currentTime (): number {
|
||||
return this._domAudio.currentTime;
|
||||
}
|
||||
|
||||
get sampleRate (): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public getPCMData (channelIndex: number): AudioPCMDataView | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
seek (time: number): Promise<void> {
|
||||
time = clamp(time, 0, this.duration);
|
||||
this._domAudio.currentTime = time;
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
play (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
ensurePlaying(this._domAudio).then(() => {
|
||||
this._state = AudioState.PLAYING;
|
||||
resolve();
|
||||
}).catch((e) => {});
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
pause (): Promise<void> {
|
||||
this._domAudio.pause();
|
||||
this._state = AudioState.PAUSED;
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
stop (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this._domAudio.pause();
|
||||
this._domAudio.currentTime = 0;
|
||||
this._state = AudioState.STOPPED;
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); }
|
||||
onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); }
|
||||
offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); }
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants';
|
||||
import { AudioPCMDataView, AudioEvent, AudioState, AudioType } from '../type';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { clamp01 } from '../../../cocos/core';
|
||||
import * as debug from '../../../cocos/core/platform/debug';
|
||||
import { enqueueOperation, OperationInfo, OperationQueueable } from '../operation-queue';
|
||||
import AudioTimer from '../audio-timer';
|
||||
import { audioBufferManager } from '../audio-buffer-manager';
|
||||
import { Game, game } from '../../../cocos/game';
|
||||
|
||||
// NOTE: fix CI
|
||||
const AudioContextClass = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
|
||||
const _contextRunningEvent = 'on-context-running';
|
||||
|
||||
export class AudioContextAgent {
|
||||
public static support = !!AudioContextClass;
|
||||
|
||||
private _eventTarget: EventTarget;
|
||||
private _context: AudioContext;
|
||||
private _isRunning = false;
|
||||
constructor () {
|
||||
this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
|
||||
this._eventTarget = new EventTarget();
|
||||
this._context.onstatechange = (): void => {
|
||||
if (this._context.state === 'running') {
|
||||
this._isRunning = true;
|
||||
this._eventTarget.emit(_contextRunningEvent);
|
||||
} else {
|
||||
this._isRunning = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get isRunning (): boolean {
|
||||
return this._isRunning;
|
||||
}
|
||||
|
||||
get currentTime (): number {
|
||||
return this._context.currentTime;
|
||||
}
|
||||
|
||||
public onceRunning (cb: (...args: any[]) => void, target?: any): void {
|
||||
this._eventTarget.once(_contextRunningEvent, cb, target);
|
||||
}
|
||||
|
||||
public offRunning (cb?: (...args: any[]) => void, target?: any): void {
|
||||
this._eventTarget.off(_contextRunningEvent, cb, target);
|
||||
}
|
||||
|
||||
public decodeAudioData (audioData: ArrayBuffer): Promise<AudioBuffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const promise = this._context.decodeAudioData(audioData, (audioBuffer) => {
|
||||
resolve(audioBuffer);
|
||||
}, (err) => {
|
||||
// TODO: need to reject the error.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('failed to load Web Audio', err);
|
||||
});
|
||||
promise?.catch(reject); // Safari doesn't support the promise based decodeAudioData
|
||||
});
|
||||
}
|
||||
|
||||
public runContext (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (this.isRunning) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const context = this._context;
|
||||
if (!context.resume) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
// only state is suspended can involve resume function
|
||||
if (context.state === 'suspended') {
|
||||
context.resume().catch((e) => { debug.warn('runContext error', e); });
|
||||
} else if (context.state === 'running') {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
// Force running audio context if state is not 'running', may be 'suspended' or 'interrupted'.
|
||||
const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
|
||||
// HACK NOTE: if the user slide after touch start, the context cannot be resumed correctly.
|
||||
const onGesture = (): void => {
|
||||
context.resume().then(() => {
|
||||
canvas?.removeEventListener('touchend', onGesture, { capture: true });
|
||||
canvas?.removeEventListener('mouseup', onGesture, { capture: true });
|
||||
resolve();
|
||||
}).catch((e) => { debug.warn('onGesture resume error', e); });
|
||||
};
|
||||
canvas?.addEventListener('touchend', onGesture, { capture: true });
|
||||
canvas?.addEventListener('mouseup', onGesture, { capture: true });
|
||||
});
|
||||
}
|
||||
|
||||
public createBufferSource (audioBuffer?: AudioBuffer, loop?: boolean): AudioBufferSourceNode {
|
||||
const sourceBufferNode = this._context.createBufferSource();
|
||||
if (audioBuffer !== undefined) {
|
||||
sourceBufferNode.buffer = audioBuffer;
|
||||
}
|
||||
if (loop !== undefined) {
|
||||
sourceBufferNode.loop = loop;
|
||||
}
|
||||
return sourceBufferNode;
|
||||
}
|
||||
|
||||
public createGain (volume = 1): GainNode {
|
||||
const gainNode = this._context.createGain();
|
||||
this.setGainValue(gainNode, volume);
|
||||
return gainNode;
|
||||
}
|
||||
|
||||
public setGainValue (gain: GainNode, volume: number): void {
|
||||
if (gain.gain.setTargetAtTime) {
|
||||
try {
|
||||
gain.gain.setTargetAtTime(volume, this._context.currentTime, 0);
|
||||
} catch (e) {
|
||||
// Some unknown browsers may crash if timeConstant is 0
|
||||
gain.gain.setTargetAtTime(volume, this._context.currentTime, 0.01);
|
||||
}
|
||||
} else {
|
||||
gain.gain.value = volume;
|
||||
}
|
||||
}
|
||||
|
||||
public connectContext (audioNode: GainNode): void {
|
||||
if (!this._context) {
|
||||
return;
|
||||
}
|
||||
audioNode.connect(this._context.destination);
|
||||
}
|
||||
}
|
||||
|
||||
let audioContextAgent: AudioContextAgent | undefined;
|
||||
if (AudioContextAgent.support) {
|
||||
audioContextAgent = new AudioContextAgent();
|
||||
}
|
||||
|
||||
export class OneShotAudioWeb {
|
||||
private _duration: number;
|
||||
private _bufferSourceNode: AudioBufferSourceNode;
|
||||
private _onPlayCb?: () => void;
|
||||
private _currentTimer = 0;
|
||||
private _url: string;
|
||||
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._onPlayCb;
|
||||
}
|
||||
set onPlay (cb) {
|
||||
this._onPlayCb = cb;
|
||||
}
|
||||
|
||||
private _onEndCb?: () => void;
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._onEndCb;
|
||||
}
|
||||
set onEnd (cb) {
|
||||
this._onEndCb = cb;
|
||||
}
|
||||
|
||||
private constructor (audioBuffer: AudioBuffer, volume: number, url: string) {
|
||||
this._duration = audioBuffer.duration;
|
||||
this._url = url;
|
||||
this._bufferSourceNode = audioContextAgent!.createBufferSource(audioBuffer, false);
|
||||
const gainNode = audioContextAgent!.createGain(volume);
|
||||
this._bufferSourceNode.connect(gainNode);
|
||||
audioContextAgent!.connectContext(gainNode);
|
||||
}
|
||||
|
||||
public play (): void {
|
||||
if (EDITOR_NOT_IN_PREVIEW) {
|
||||
return;
|
||||
}
|
||||
this._bufferSourceNode.start();
|
||||
// audioContextAgent does exist
|
||||
audioContextAgent!.runContext().then(() => {
|
||||
this.onPlay?.();
|
||||
this._currentTimer = window.setTimeout(() => {
|
||||
audioBufferManager.tryReleasingCache(this._url);
|
||||
this.onEnd?.();
|
||||
}, this._duration * 1000);
|
||||
}).catch((e) => { debug.warn('play error', e); });
|
||||
}
|
||||
|
||||
public stop (): void {
|
||||
clearTimeout(this._currentTimer);
|
||||
audioBufferManager.tryReleasingCache(this._url);
|
||||
this._bufferSourceNode.stop();
|
||||
this._bufferSourceNode.disconnect();
|
||||
this._bufferSourceNode.buffer = null;
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayerWeb implements OperationQueueable {
|
||||
private _src: string;
|
||||
private _audioBuffer: AudioBuffer;
|
||||
private _sourceNode?: AudioBufferSourceNode;
|
||||
private _gainNode: GainNode;
|
||||
private _currentTimer = 0;
|
||||
private _volume = 1;
|
||||
private _loop = false;
|
||||
private _state: AudioState = AudioState.INIT;
|
||||
private _audioTimer: AudioTimer;
|
||||
private _runningCallback?: () => void;
|
||||
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _eventTarget: EventTarget = new EventTarget();
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _operationQueue: OperationInfo[] = [];
|
||||
|
||||
constructor (audioBuffer: AudioBuffer, url: string) {
|
||||
this._audioBuffer = audioBuffer;
|
||||
this._audioTimer = new AudioTimer(audioBuffer);
|
||||
this._gainNode = audioContextAgent!.createGain();
|
||||
audioContextAgent!.connectContext(this._gainNode);
|
||||
this._src = url;
|
||||
// event
|
||||
game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
}
|
||||
destroy (): void {
|
||||
window.clearTimeout(this._currentTimer);
|
||||
this._audioTimer.destroy();
|
||||
if (this._audioBuffer) {
|
||||
// NOTE: need to release AudioBuffer instance
|
||||
this._audioBuffer = null as any;
|
||||
}
|
||||
audioBufferManager.tryReleasingCache(this._src);
|
||||
game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
|
||||
game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
|
||||
this.offRunning();
|
||||
}
|
||||
static load (url: string): Promise<AudioPlayerWeb> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerWeb.loadNative(url).then((audioBuffer) => {
|
||||
resolve(new AudioPlayerWeb(audioBuffer, url));
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
static loadNative (url: string): Promise<AudioBuffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const cachedAudioBuffer = audioBufferManager.getCache(url);
|
||||
if (cachedAudioBuffer) {
|
||||
audioBufferManager.retainCache(url);
|
||||
resolve(cachedAudioBuffer);
|
||||
return;
|
||||
}
|
||||
const xhr = new XMLHttpRequest();
|
||||
const errInfo = `load audio failed: ${url}, status: `;
|
||||
xhr.open('GET', url, true);
|
||||
xhr.responseType = 'arraybuffer';
|
||||
|
||||
xhr.onload = (): void => {
|
||||
if (xhr.status === 200 || xhr.status === 0) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
audioContextAgent!.decodeAudioData(xhr.response).then((decodedAudioBuffer) => {
|
||||
audioBufferManager.addCache(url, decodedAudioBuffer);
|
||||
resolve(decodedAudioBuffer);
|
||||
}).catch((e) => { debug.warn('loadNative error', url, e); });
|
||||
} else {
|
||||
reject(new Error(`${errInfo}${xhr.status}(no response)`));
|
||||
}
|
||||
};
|
||||
xhr.onerror = (): void => { reject(new Error(`${errInfo}${xhr.status}(error)`)); };
|
||||
xhr.ontimeout = (): void => { reject(new Error(`${errInfo}${xhr.status}(time out)`)); };
|
||||
xhr.onabort = (): void => { reject(new Error(`${errInfo}${xhr.status}(abort)`)); };
|
||||
|
||||
xhr.send(null);
|
||||
});
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number): Promise<OneShotAudioWeb> {
|
||||
return new Promise((resolve, reject) => {
|
||||
AudioPlayerWeb.loadNative(url).then((audioBuffer) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
const oneShotAudio = new (OneShotAudioWeb as any)(audioBuffer, volume, url);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
resolve(oneShotAudio);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
get sampleRate (): number {
|
||||
return this._audioBuffer.sampleRate;
|
||||
}
|
||||
|
||||
public getPCMData (channelIndex: number): AudioPCMDataView | undefined {
|
||||
return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1);
|
||||
}
|
||||
|
||||
private _onInterruptedBegin (): void {
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
this.pause().then(() => {
|
||||
this._state = AudioState.INTERRUPTED;
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
|
||||
}).catch((e) => { debug.warn('_onInterruptedBegin error', e); });
|
||||
}
|
||||
}
|
||||
private _onInterruptedEnd (): void {
|
||||
if (this._state === AudioState.INTERRUPTED) {
|
||||
this.play().then(() => {
|
||||
this._eventTarget.emit(AudioEvent.INTERRUPTION_END);
|
||||
}).catch((e) => { debug.warn('_onInterruptedEnd error', e); });
|
||||
}
|
||||
}
|
||||
|
||||
get src (): string {
|
||||
return this._src;
|
||||
}
|
||||
get type (): AudioType {
|
||||
return AudioType.WEB_AUDIO;
|
||||
}
|
||||
get state (): AudioState {
|
||||
return this._state;
|
||||
}
|
||||
get loop (): boolean {
|
||||
return this._loop;
|
||||
}
|
||||
set loop (val: boolean) {
|
||||
this._loop = val;
|
||||
if (this._sourceNode) {
|
||||
this._sourceNode.loop = val;
|
||||
}
|
||||
}
|
||||
get volume (): number {
|
||||
return this._volume;
|
||||
}
|
||||
set volume (val: number) {
|
||||
val = clamp01(val);
|
||||
this._volume = val;
|
||||
audioContextAgent!.setGainValue(this._gainNode, val);
|
||||
}
|
||||
get duration (): number {
|
||||
return this._audioBuffer.duration;
|
||||
}
|
||||
get currentTime (): number {
|
||||
return this._audioTimer.currentTime;
|
||||
}
|
||||
private offRunning (): void {
|
||||
if (this._runningCallback) {
|
||||
audioContextAgent!.offRunning(this._runningCallback);
|
||||
this._runningCallback = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
seek (time: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
this.offRunning();
|
||||
this._audioTimer.seek(time);
|
||||
if (this._state === AudioState.PLAYING) {
|
||||
// one AudioBufferSourceNode can't start twice
|
||||
// need to create a new one to start from the offset
|
||||
this._doPlay().then(resolve).catch((e) => { debug.warn('seek error', e); });
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
play (): Promise<void> {
|
||||
this.offRunning();
|
||||
if (EDITOR_NOT_IN_PREVIEW) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return this._doPlay();
|
||||
}
|
||||
|
||||
// The decorated play() method can't be call in seek()
|
||||
// so we define this method to ensure that the audio seeking works.
|
||||
private _doPlay (): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (audioContextAgent!.isRunning) {
|
||||
this._startSourceNode();
|
||||
resolve();
|
||||
} else {
|
||||
this.offRunning();
|
||||
this._runningCallback = (): void => {
|
||||
this._startSourceNode();
|
||||
resolve();
|
||||
};
|
||||
// Running event may be emit when:
|
||||
// - manually resume audio context.
|
||||
// - system automatically resume audio context when enter foreground from background.
|
||||
audioContextAgent!.onceRunning(this._runningCallback);
|
||||
// Ensure resume context.
|
||||
audioContextAgent!.runContext().catch((e) => { debug.warn('doPlay error', e); });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private _startSourceNode (): void {
|
||||
// one AudioBufferSourceNode can't start twice
|
||||
this._stopSourceNode();
|
||||
this._sourceNode = audioContextAgent!.createBufferSource(this._audioBuffer, this.loop);
|
||||
this._sourceNode.connect(this._gainNode);
|
||||
this._sourceNode.loop = this._loop;
|
||||
this._sourceNode.start(0, this._audioTimer.currentTime);
|
||||
this._state = AudioState.PLAYING;
|
||||
this._audioTimer.start();
|
||||
|
||||
/* still not supported by all platforms *
|
||||
this._sourceNode.onended = this._onEnded;
|
||||
/* doing it manually for now */
|
||||
const checkEnded = (): void => {
|
||||
if (this.loop) {
|
||||
this._currentTimer = window.setTimeout(checkEnded, this._audioBuffer.duration * 1000);
|
||||
} else { // do ended
|
||||
this._audioTimer.stop();
|
||||
this._eventTarget.emit(AudioEvent.ENDED);
|
||||
this._state = AudioState.INIT;
|
||||
}
|
||||
};
|
||||
window.clearTimeout(this._currentTimer);
|
||||
this._currentTimer = window.setTimeout(checkEnded, (this._audioBuffer.duration - this._audioTimer.currentTime) * 1000);
|
||||
}
|
||||
|
||||
private _stopSourceNode (): void {
|
||||
try {
|
||||
if (this._sourceNode) {
|
||||
this._sourceNode.stop();
|
||||
this._sourceNode.disconnect();
|
||||
this._sourceNode.buffer = null;
|
||||
this._sourceNode = undefined;
|
||||
}
|
||||
} catch (e) {
|
||||
// sourceNode can't be stopped twice, especially on Safari.
|
||||
}
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
pause (): Promise<void> {
|
||||
this.offRunning();
|
||||
if (this._state !== AudioState.PLAYING || !this._sourceNode) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
this._audioTimer.pause();
|
||||
this._state = AudioState.PAUSED;
|
||||
window.clearTimeout(this._currentTimer);
|
||||
this._stopSourceNode();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@enqueueOperation
|
||||
stop (): Promise<void> {
|
||||
this.offRunning();
|
||||
if (!this._sourceNode) {
|
||||
this._audioTimer.stop();
|
||||
this._state = AudioState.STOPPED;
|
||||
return Promise.resolve();
|
||||
}
|
||||
this._audioTimer.stop();
|
||||
this._state = AudioState.STOPPED;
|
||||
window.clearTimeout(this._currentTimer);
|
||||
this._stopSourceNode();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
onInterruptionBegin (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb); }
|
||||
onEnded (cb: () => void): void { this._eventTarget.on(AudioEvent.ENDED, cb); }
|
||||
offEnded (cb?: () => void): void { this._eventTarget.off(AudioEvent.ENDED, cb); }
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { warnID } from '../../../cocos/core';
|
||||
import { AudioLoadOptions, AudioType, AudioState, AudioPCMDataView } from '../type';
|
||||
import { AudioPlayerDOM, OneShotAudioDOM } from './player-dom';
|
||||
import { AudioContextAgent, AudioPlayerWeb, OneShotAudioWeb } from './player-web';
|
||||
|
||||
type AbstractOneShotAudio = OneShotAudioDOM | OneShotAudioWeb;
|
||||
type AbstractAudioPlayer = AudioPlayerDOM | AudioPlayerWeb;
|
||||
|
||||
export class OneShotAudio {
|
||||
private _audio: AbstractOneShotAudio;
|
||||
get onPlay (): (() => void) | undefined {
|
||||
return this._audio.onPlay;
|
||||
}
|
||||
set onPlay (v) {
|
||||
this._audio.onPlay = v;
|
||||
}
|
||||
|
||||
get onEnd (): (() => void) | undefined {
|
||||
return this._audio.onEnd;
|
||||
}
|
||||
set onEnd (v) {
|
||||
this._audio.onEnd = v;
|
||||
}
|
||||
|
||||
private constructor (audio: AbstractOneShotAudio) {
|
||||
this._audio = audio;
|
||||
}
|
||||
public play (): void {
|
||||
this._audio.play();
|
||||
}
|
||||
public stop (): void {
|
||||
this._audio.stop();
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioPlayer {
|
||||
private _player: AbstractAudioPlayer;
|
||||
constructor (player: AbstractAudioPlayer) {
|
||||
this._player = player;
|
||||
}
|
||||
|
||||
static load (url: string, opts?: AudioLoadOptions): Promise<AudioPlayer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (opts?.audioLoadMode === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
|
||||
if (!AudioContextAgent.support) { warnID(5201); }
|
||||
AudioPlayerDOM.load(url).then((domPlayer) => {
|
||||
resolve(new AudioPlayer(domPlayer));
|
||||
}).catch(reject);
|
||||
} else {
|
||||
AudioPlayerWeb.load(url).then((webPlayer) => {
|
||||
resolve(new AudioPlayer(webPlayer));
|
||||
}).catch(reject);
|
||||
}
|
||||
});
|
||||
}
|
||||
destroy (): void {
|
||||
this._player.destroy();
|
||||
}
|
||||
static loadNative (url: string, opts?: AudioLoadOptions): Promise<unknown> {
|
||||
if (opts?.audioLoadMode === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
|
||||
if (!AudioContextAgent.support) { warnID(5201); }
|
||||
return AudioPlayerDOM.loadNative(url);
|
||||
}
|
||||
return AudioPlayerWeb.loadNative(url);
|
||||
}
|
||||
static loadOneShotAudio (url: string, volume: number, opts?: AudioLoadOptions): Promise<OneShotAudio> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (opts?.audioLoadMode === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
|
||||
if (!AudioContextAgent.support) { warnID(5201); }
|
||||
AudioPlayerDOM.loadOneShotAudio(url, volume).then((oneShotAudioDOM) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
resolve(new (OneShotAudio as any)(oneShotAudioDOM));
|
||||
}).catch(reject);
|
||||
} else {
|
||||
AudioPlayerWeb.loadOneShotAudio(url, volume).then((oneShotAudioWeb) => {
|
||||
// HACK: AudioPlayer should be a friend class in OneShotAudio
|
||||
resolve(new (OneShotAudio as any)(oneShotAudioWeb));
|
||||
}).catch(reject);
|
||||
}
|
||||
});
|
||||
}
|
||||
static readonly maxAudioChannel = 24;
|
||||
|
||||
get src (): string { return this._player.src; }
|
||||
get type (): AudioType { return this._player.type; }
|
||||
get state (): AudioState { return this._player.state; }
|
||||
get loop (): boolean { return this._player.loop; }
|
||||
set loop (val: boolean) { this._player.loop = val; }
|
||||
get volume (): number { return this._player.volume; }
|
||||
set volume (val: number) { this._player.volume = val; }
|
||||
get duration (): number { return this._player.duration; }
|
||||
get currentTime (): number { return this._player.currentTime; }
|
||||
get sampleRate (): number { return this._player.sampleRate; }
|
||||
getPCMData (channelIndex: number): AudioPCMDataView | undefined { return this._player.getPCMData(channelIndex); }
|
||||
seek (time: number): Promise<void> { return this._player.seek(time); }
|
||||
|
||||
play (): Promise<void> { return this._player.play(); }
|
||||
pause (): Promise<void> { return this._player.pause(); }
|
||||
stop (): Promise<void> { return this._player.stop(); }
|
||||
onInterruptionBegin (cb: () => void): void { this._player.onInterruptionBegin(cb); }
|
||||
offInterruptionBegin (cb?: () => void): void { this._player.offInterruptionBegin(cb); }
|
||||
onInterruptionEnd (cb: () => void): void { this._player.onInterruptionEnd(cb); }
|
||||
offInterruptionEnd (cb?: () => void): void { this._player.offInterruptionEnd(cb); }
|
||||
onEnded (cb: () => void): void { this._player.onEnded(cb); }
|
||||
offEnded (cb?: () => void): void { this._player.offEnded(cb); }
|
||||
}
|
||||
Vendored
-56
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* eslint-disable import/no-dynamic-require */
|
||||
import { TAOBAO, TAOBAO_MINIGAME, WECHAT, WECHAT_MINI_PROGRAM, XIAOMI } from 'internal:constants';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
declare const require: (path: string) => any;
|
||||
declare const __baiduRequire: (path: string) => any;
|
||||
declare const __wxRequire: (path: string) => any;
|
||||
declare const __taobaoRequire: (path: string) => any;
|
||||
|
||||
export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } {
|
||||
const container = document.createElement('div');
|
||||
return { frame: container, canvas: window.canvas, container };
|
||||
}
|
||||
|
||||
export function loadJsFile (path: string): any {
|
||||
if (XIAOMI) {
|
||||
return require(`../../${path}`);
|
||||
}
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM) {
|
||||
return __wxRequire(path);
|
||||
}
|
||||
if (TAOBAO_MINIGAME) {
|
||||
return globalThis.__taobaoRequire(path);
|
||||
}
|
||||
if (TAOBAO) {
|
||||
// NOTE: Taobao doesn't support dynamic require
|
||||
return undefined;
|
||||
}
|
||||
return require(`../${path}`);
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/env')>(withImpl<typeof import('./env')>());
|
||||
Vendored
-74
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { NATIVE, PREVIEW } from 'internal:constants';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
declare const require: (path: string) => Promise<void>;
|
||||
|
||||
const ccwindow = typeof globalThis.jsb !== 'undefined' ? (typeof jsb.window !== 'undefined' ? jsb.window : window) : window;
|
||||
const ccdocument = ccwindow.document;
|
||||
|
||||
export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } {
|
||||
const container = ccdocument.createElement('div');
|
||||
const frame = ccdocument.documentElement as HTMLDivElement;
|
||||
const canvas = ccwindow.__canvas;
|
||||
return { frame, canvas, container };
|
||||
}
|
||||
|
||||
export function loadJsFile (path: string): Promise<void> {
|
||||
if (NATIVE && window.oh && window.scriptEngineType === 'napi') {
|
||||
// TODO(qgh):OpenHarmony does not currently support dynamic require expressions
|
||||
window.oh.loadModule(path);
|
||||
return Promise.resolve();
|
||||
} else {
|
||||
if (PREVIEW) {
|
||||
// NOTE: in native preview (simulator), we need to request script with url http://x.x.x.x:xxxx/plugins/xxx.js
|
||||
// so that the editor preview server would resolve the plugin script and return the code.
|
||||
// here we use window.eval() function to execute the code of plugin script.
|
||||
return new Promise((resolve, reject) => {
|
||||
const sourceURL = window.location.href + path;
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.onload = (): void => {
|
||||
if (xhr.status !== 200) {
|
||||
reject(new Error(`load js file failed: ${sourceURL}, error status: ${xhr.status}`));
|
||||
return;
|
||||
}
|
||||
// eslint-disable-next-line no-eval
|
||||
window.eval(`${xhr.response as string}\n//# sourceURL=${sourceURL}`);
|
||||
resolve();
|
||||
};
|
||||
xhr.onerror = (): void => {
|
||||
reject(new Error(`load js file failed: ${sourceURL}`));
|
||||
};
|
||||
xhr.open('GET', sourceURL, true);
|
||||
xhr.send(null);
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line import/no-dynamic-require
|
||||
return require(`${path}`);
|
||||
}
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/env')>(withImpl<typeof import('./env')>());
|
||||
Vendored
-40
@@ -1,40 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } {
|
||||
const frame = document.querySelector('#GameDiv') as HTMLDivElement;
|
||||
const container = document.querySelector('#Cocos3dGameContainer') as HTMLDivElement;
|
||||
const canvas = document.querySelector('#GameCanvas') as HTMLCanvasElement;
|
||||
|
||||
return { frame, container, canvas };
|
||||
}
|
||||
|
||||
export function loadJsFile (path: string): Promise<void> {
|
||||
// eslint-disable-next-line import/no-dynamic-require
|
||||
return globalThis.nodeEnv.require(`${path}`);
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/env')>(withImpl<typeof import('./env')>());
|
||||
Vendored
-50
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HUAWEI, OPPO, VIVO } from 'internal:constants';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
declare const require: (path: string) => Promise<void>;
|
||||
declare const ral: any;
|
||||
|
||||
export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } {
|
||||
const container = document.createElement('div');
|
||||
const frame = container.parentNode === document.body ? document.documentElement : container.parentNode as any;
|
||||
|
||||
let canvas;
|
||||
if (VIVO) {
|
||||
canvas = window.mainCanvas;
|
||||
window.mainCanvas = undefined;
|
||||
} else {
|
||||
canvas = ral.createCanvas();
|
||||
}
|
||||
return { frame, canvas, container };
|
||||
}
|
||||
|
||||
export function loadJsFile (path: string): Promise<void> {
|
||||
// eslint-disable-next-line import/no-dynamic-require
|
||||
return require(`${path}`);
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/env')>(withImpl<typeof import('./env')>());
|
||||
Vendored
-68
@@ -1,68 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement } {
|
||||
const frame = document.querySelector('#GameDiv') as HTMLDivElement;
|
||||
const container = document.querySelector('#Cocos3dGameContainer') as HTMLDivElement;
|
||||
const canvas = document.querySelector('#GameCanvas') as HTMLCanvasElement;
|
||||
|
||||
return { frame, container, canvas };
|
||||
}
|
||||
|
||||
export function loadJsFile (path: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let err;
|
||||
function windowErrorListener (evt): void {
|
||||
if (evt.filename === path) {
|
||||
err = evt.error;
|
||||
}
|
||||
}
|
||||
window.addEventListener('error', windowErrorListener);
|
||||
const script = document.createElement('script');
|
||||
script.charset = 'utf-8';
|
||||
script.async = true;
|
||||
script.crossOrigin = 'anonymous';
|
||||
script.addEventListener('error', () => {
|
||||
window.removeEventListener('error', windowErrorListener);
|
||||
reject(Error(`Error loading ${path}`));
|
||||
});
|
||||
script.addEventListener('load', () => {
|
||||
window.removeEventListener('error', windowErrorListener);
|
||||
document.head.removeChild(script);
|
||||
// Note that if an error occurs that isn't caught by this if statement,
|
||||
// that getRegister will return null and a "did not instantiate" error will be thrown.
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
script.src = path.replace('#', '%23');
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/env')>(withImpl<typeof import('./env')>());
|
||||
@@ -1,327 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022 Chukong Technologies Inc.
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { Vec2, Vec3, Quat } from '../../cocos/core/math';
|
||||
|
||||
/**
|
||||
* @en The abstract class for input source, which is used to control the input signal of a mono input source
|
||||
* @zh InputSource 抽象类,该类用于控制单一输入源的输入信号
|
||||
*/
|
||||
export abstract class InputSource<T> {
|
||||
/**
|
||||
* @en Get the signal value of the input source
|
||||
* @zh 获取输入源的信号值
|
||||
*/
|
||||
abstract getValue (): T;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of 1D Axis, which is used to control the input signal of a mono input source
|
||||
* @zh 1D 轴的 InputSource 类,该类用于控制单一输入源的输入信号
|
||||
*/
|
||||
export class InputSourceAxis1D extends InputSource<number> {
|
||||
/**
|
||||
* @en Get the signal value of the input source, ranged from -1 to 1
|
||||
* @zh 获取输入源的信号值,取值范围从 -1 到 1
|
||||
*/
|
||||
getValue (): number {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of 2D Axis, which is used to control the input signal of a mono input source
|
||||
* @zh 2D 轴的 InputSource 类,该类用于控制单一输入源的输入信号
|
||||
*/
|
||||
export class InputSourceAxis2D extends InputSource<Vec2> {
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Vec2 object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Vec2 对象
|
||||
*/
|
||||
getValue (): Vec2 {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of 3D Axis, which is used to control the input signal of a mono input source
|
||||
* @zh 3D 轴的 InputSource 类,该类用于控制单一输入源的输入信号
|
||||
*/
|
||||
export class InputSourceAxis3D extends InputSource<Vec3> {
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Vec3 object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Vec3 对象
|
||||
*/
|
||||
getValue (): Vec3 {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of Quaternion, which is used to control the input signal of a mono input source
|
||||
* @zh 四元数的 InputSource 类,该类用于控制单一输入源的输入信号
|
||||
*/
|
||||
export class InputSourceQuat extends InputSource<Quat> {
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Quat object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Quat 对象
|
||||
*/
|
||||
getValue (): Quat {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of 1D Axis, which is used to control the input signal of a composite of multi input source
|
||||
* @zh 1D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号
|
||||
*/
|
||||
export class CompositeInputSourceAxis1D extends InputSourceAxis1D {
|
||||
/**
|
||||
* @en The input source object of positive 1D axis
|
||||
* @zh 1D 轴的正向的输入源对象
|
||||
*/
|
||||
public declare positive: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of negative 1D axis
|
||||
* @zh 1D 轴的负向的输入源对象
|
||||
*/
|
||||
public declare negative: InputSourceButton;
|
||||
constructor (options: {positive: InputSourceButton, negative: InputSourceButton}) {
|
||||
super();
|
||||
this.positive = options.positive;
|
||||
this.negative = options.negative;
|
||||
}
|
||||
/**
|
||||
* @en Get the signal value of the input source, ranged from -1 to 1.
|
||||
* @zh 获取输入源的信号值,取值范围从 -1 到 1
|
||||
*/
|
||||
public getValue (): number {
|
||||
const positiveValue = this.positive.getValue();
|
||||
const negativeValue = this.negative.getValue();
|
||||
if (Math.abs(positiveValue) > Math.abs(negativeValue)) {
|
||||
return positiveValue;
|
||||
}
|
||||
return -negativeValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of 2D Axis, which is used to control the input signal of a composite of multi input source
|
||||
* @zh 2D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号
|
||||
*/
|
||||
export class CompositeInputSourceAxis2D extends InputSourceAxis2D {
|
||||
/**
|
||||
* @en The input source object of up direction of 2D axis
|
||||
* @zh 2D 轴的向上的输入源对象
|
||||
*/
|
||||
public declare up: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of down direction of 2D axis
|
||||
* @zh 2D 轴的向下的输入源对象
|
||||
*/
|
||||
public declare down: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of left direction of 2D axis
|
||||
* @zh 2D 轴的向左的输入源对象
|
||||
*/
|
||||
public declare left: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of right direction of 2D axis
|
||||
* @zh 2D 轴的向右的输入源对象
|
||||
*/
|
||||
public declare right: InputSourceButton;
|
||||
|
||||
/**
|
||||
* @en The composite input source object on the x axis of 2D axis
|
||||
* @zh 2D 轴在 x 轴上的组合输入源对象
|
||||
*/
|
||||
public declare xAxis: CompositeInputSourceAxis1D;
|
||||
/**
|
||||
* @en The composite input source object on the y axis of 2D axis
|
||||
* @zh 2D 轴在 y 轴上的组合输入源对象
|
||||
*/
|
||||
public declare yAxis: CompositeInputSourceAxis1D;
|
||||
constructor (options: {up: InputSourceButton, down: InputSourceButton, left: InputSourceButton, right: InputSourceButton}) {
|
||||
super();
|
||||
this.up = options.up;
|
||||
this.down = options.down;
|
||||
this.left = options.left;
|
||||
this.right = options.right;
|
||||
this.xAxis = new CompositeInputSourceAxis1D({ positive: this.right, negative: this.left });
|
||||
this.yAxis = new CompositeInputSourceAxis1D({ positive: this.up, negative: this.down });
|
||||
}
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Vec2 object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Vec2 对象
|
||||
*/
|
||||
getValue (): Vec2 {
|
||||
return new Vec2(this.xAxis.getValue(), this.yAxis.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of 3D Axis, which is used to control the input signal of a composite of multi input source
|
||||
* @zh 3D 轴的 InputSource 类,该类用于控制多个输入源组合的输入信号
|
||||
*/
|
||||
export class CompositeInputSourceAxis3D extends InputSourceAxis3D {
|
||||
/**
|
||||
* @en The input source object of up direction of 3D axis
|
||||
* @zh 3D 轴的向上的输入源对象
|
||||
*/
|
||||
public declare up: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of down direction of 3D axis
|
||||
* @zh 3D 轴的向下的输入源对象
|
||||
*/
|
||||
public declare down: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of left direction of 3D axis
|
||||
* @zh 3D 轴的向左的输入源对象
|
||||
*/
|
||||
public declare left: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of right direction of 3D axis
|
||||
* @zh 3D 轴的向右的输入源对象
|
||||
*/
|
||||
public declare right: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of forward direction of 3D axis
|
||||
* @zh 3D 轴的向前的输入源对象
|
||||
*/
|
||||
public declare forward: InputSourceButton;
|
||||
/**
|
||||
* @en The input source object of backward direction of 3D axis
|
||||
* @zh 3D 轴的向后的输入源对象
|
||||
*/
|
||||
public declare backward: InputSourceButton;
|
||||
|
||||
/**
|
||||
* @en The composite input source object on the x axis of 3D axis
|
||||
* @zh 3D 轴在 x 轴上的组合输入源对象
|
||||
*/
|
||||
public declare xAxis: CompositeInputSourceAxis1D;
|
||||
/**
|
||||
* @en The composite input source object on the y axis of 3D axis
|
||||
* @zh 3D 轴在 y 轴上的组合输入源对象
|
||||
*/
|
||||
public declare yAxis: CompositeInputSourceAxis1D;
|
||||
/**
|
||||
* @en The composite input source object on the z axis of 3D axis
|
||||
* @zh 3D 轴在 z 轴上的组合输入源对象
|
||||
*/
|
||||
public declare zAxis: CompositeInputSourceAxis1D;
|
||||
constructor (options: {up: InputSourceButton, down: InputSourceButton, left: InputSourceButton,
|
||||
right: InputSourceButton, forward: InputSourceButton, backward: InputSourceButton}) {
|
||||
super();
|
||||
this.up = options.up;
|
||||
this.down = options.down;
|
||||
this.left = options.left;
|
||||
this.right = options.right;
|
||||
this.forward = options.forward;
|
||||
this.backward = options.backward;
|
||||
|
||||
this.xAxis = new CompositeInputSourceAxis1D({ positive: this.right, negative: this.left });
|
||||
this.yAxis = new CompositeInputSourceAxis1D({ positive: this.up, negative: this.down });
|
||||
this.zAxis = new CompositeInputSourceAxis1D({ positive: this.forward, negative: this.backward });
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Vec3 object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Vec3 对象
|
||||
*/
|
||||
getValue (): Vec3 {
|
||||
return new Vec3(this.xAxis.getValue(), this.yAxis.getValue(), this.zAxis.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of mono button, whose input signal value is ranged from 0 to 1
|
||||
* @zh 单一按键输入源类, 输入信号源的取值范围是 0 到 1
|
||||
*/
|
||||
export class InputSourceButton extends InputSourceAxis1D {
|
||||
/**
|
||||
* @en Get the signal value of the input source, ranged from 0 to 1
|
||||
* @zh 获取输入源的信号值,取值范围从 0 到 1
|
||||
*/
|
||||
getValue (): number {
|
||||
return super.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of dpad, whose input signal value a Vec2 object
|
||||
* @zh 手柄方向键输入源类, 输入信号源的取值是一个 Vec2 对象
|
||||
*/
|
||||
export class InputSourceDpad extends CompositeInputSourceAxis2D {
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of stick, whose input signal value a Vec2 object
|
||||
* @zh 摇杆输入源类, 输入信号源的取值是一个 Vec2 对象
|
||||
*/
|
||||
export class InputSourceStick extends CompositeInputSourceAxis2D {
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of orientation, whose input signal value a Quat object
|
||||
* @zh 方向输入源类, 输入信号源的取值是一个 Quat 对象
|
||||
*/
|
||||
export class InputSourceOrientation extends InputSourceQuat {
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Quat object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Quat 对象
|
||||
*/
|
||||
getValue (): Quat {
|
||||
return super.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of position, whose input signal value a Vec3 object
|
||||
* @zh 坐标输入源类, 输入信号源的取值是一个 Vec3 对象
|
||||
*/
|
||||
export class InputSourcePosition extends InputSourceAxis3D {
|
||||
/**
|
||||
* @en Get the signal value of the input source, which returns a Vec3 object.
|
||||
* @zh 获取输入源的信号值,该方法返回一个 Vec3 对象
|
||||
*/
|
||||
getValue (): Vec3 {
|
||||
return super.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en The class for input source of mono button touch, whose input signal value is ranged from 0 or 1
|
||||
* @zh 单一按键触摸输入源类, 输入信号源的取值范围是 0 或 1
|
||||
*/
|
||||
export class InputSourceTouch extends InputSourceAxis1D {
|
||||
/**
|
||||
* @en Get the signal value of the input source, ranged from 0 or 1
|
||||
* @zh 获取输入源的信号值,取值范围从 0 或 1
|
||||
*/
|
||||
getValue (): number {
|
||||
return super.getValue();
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { KeyCode } from '../../cocos/input/types';
|
||||
|
||||
export const code2KeyCode: Record<string, KeyCode> = {
|
||||
Backspace: KeyCode.BACKSPACE,
|
||||
Tab: KeyCode.TAB,
|
||||
Enter: KeyCode.ENTER,
|
||||
ShiftLeft: KeyCode.SHIFT_LEFT,
|
||||
ControlLeft: KeyCode.CTRL_LEFT,
|
||||
AltLeft: KeyCode.ALT_LEFT,
|
||||
ShiftRight: KeyCode.SHIFT_RIGHT,
|
||||
ControlRight: KeyCode.CTRL_RIGHT,
|
||||
AltRight: KeyCode.ALT_RIGHT,
|
||||
Pause: KeyCode.PAUSE,
|
||||
CapsLock: KeyCode.CAPS_LOCK,
|
||||
Escape: KeyCode.ESCAPE,
|
||||
Space: KeyCode.SPACE,
|
||||
PageUp: KeyCode.PAGE_UP,
|
||||
PageDown: KeyCode.PAGE_DOWN,
|
||||
End: KeyCode.END,
|
||||
Home: KeyCode.HOME,
|
||||
ArrowLeft: KeyCode.ARROW_LEFT,
|
||||
ArrowUp: KeyCode.ARROW_UP,
|
||||
ArrowRight: KeyCode.ARROW_RIGHT,
|
||||
ArrowDown: KeyCode.ARROW_DOWN,
|
||||
Insert: KeyCode.INSERT,
|
||||
Delete: KeyCode.DELETE,
|
||||
Digit0: KeyCode.DIGIT_0,
|
||||
Digit1: KeyCode.DIGIT_1,
|
||||
Digit2: KeyCode.DIGIT_2,
|
||||
Digit3: KeyCode.DIGIT_3,
|
||||
Digit4: KeyCode.DIGIT_4,
|
||||
Digit5: KeyCode.DIGIT_5,
|
||||
Digit6: KeyCode.DIGIT_6,
|
||||
Digit7: KeyCode.DIGIT_7,
|
||||
Digit8: KeyCode.DIGIT_8,
|
||||
Digit9: KeyCode.DIGIT_9,
|
||||
KeyA: KeyCode.KEY_A,
|
||||
KeyB: KeyCode.KEY_B,
|
||||
KeyC: KeyCode.KEY_C,
|
||||
KeyD: KeyCode.KEY_D,
|
||||
KeyE: KeyCode.KEY_E,
|
||||
KeyF: KeyCode.KEY_F,
|
||||
KeyG: KeyCode.KEY_G,
|
||||
KeyH: KeyCode.KEY_H,
|
||||
KeyI: KeyCode.KEY_I,
|
||||
KeyJ: KeyCode.KEY_J,
|
||||
KeyK: KeyCode.KEY_K,
|
||||
KeyL: KeyCode.KEY_L,
|
||||
KeyM: KeyCode.KEY_M,
|
||||
KeyN: KeyCode.KEY_N,
|
||||
KeyO: KeyCode.KEY_O,
|
||||
KeyP: KeyCode.KEY_P,
|
||||
KeyQ: KeyCode.KEY_Q,
|
||||
KeyR: KeyCode.KEY_R,
|
||||
KeyS: KeyCode.KEY_S,
|
||||
KeyT: KeyCode.KEY_T,
|
||||
KeyU: KeyCode.KEY_U,
|
||||
KeyV: KeyCode.KEY_V,
|
||||
KeyW: KeyCode.KEY_W,
|
||||
KeyX: KeyCode.KEY_X,
|
||||
KeyY: KeyCode.KEY_Y,
|
||||
KeyZ: KeyCode.KEY_Z,
|
||||
Numpad0: KeyCode.NUM_0,
|
||||
Numpad1: KeyCode.NUM_1,
|
||||
Numpad2: KeyCode.NUM_2,
|
||||
Numpad3: KeyCode.NUM_3,
|
||||
Numpad4: KeyCode.NUM_4,
|
||||
Numpad5: KeyCode.NUM_5,
|
||||
Numpad6: KeyCode.NUM_6,
|
||||
Numpad7: KeyCode.NUM_7,
|
||||
Numpad8: KeyCode.NUM_8,
|
||||
Numpad9: KeyCode.NUM_9,
|
||||
NumpadMultiply: KeyCode.NUM_MULTIPLY,
|
||||
NumpadAdd: KeyCode.NUM_PLUS,
|
||||
NumpadSubtract: KeyCode.NUM_SUBTRACT,
|
||||
NumpadDecimal: KeyCode.NUM_DECIMAL,
|
||||
NumpadDivide: KeyCode.NUM_DIVIDE,
|
||||
NumpadEnter: KeyCode.NUM_ENTER,
|
||||
F1: KeyCode.F1,
|
||||
F2: KeyCode.F2,
|
||||
F3: KeyCode.F3,
|
||||
F4: KeyCode.F4,
|
||||
F5: KeyCode.F5,
|
||||
F6: KeyCode.F6,
|
||||
F7: KeyCode.F7,
|
||||
F8: KeyCode.F8,
|
||||
F9: KeyCode.F9,
|
||||
F10: KeyCode.F10,
|
||||
F11: KeyCode.F11,
|
||||
F12: KeyCode.F12,
|
||||
NumLock: KeyCode.NUM_LOCK,
|
||||
ScrollLock: KeyCode.SCROLL_LOCK,
|
||||
Semicolon: KeyCode.SEMICOLON,
|
||||
Equal: KeyCode.EQUAL,
|
||||
Comma: KeyCode.COMMA,
|
||||
Minus: KeyCode.DASH,
|
||||
Period: KeyCode.PERIOD,
|
||||
Slash: KeyCode.SLASH,
|
||||
Backquote: KeyCode.BACK_QUOTE,
|
||||
BracketLeft: KeyCode.BRACKET_LEFT,
|
||||
Backslash: KeyCode.BACKSLASH,
|
||||
BracketRight: KeyCode.BRACKET_RIGHT,
|
||||
Quote: KeyCode.QUOTE,
|
||||
};
|
||||
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { AccelerometerCallback } from 'pal/input';
|
||||
import { minigame, AccelerometerIntervalMode } from 'pal/minigame';
|
||||
import { Acceleration, EventAcceleration } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { errorID } from '../../../cocos/core/platform/debug';
|
||||
|
||||
export class AccelerometerInputSource {
|
||||
private _isStarted = false;
|
||||
private _accelMode: AccelerometerIntervalMode = 'normal';
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private declare _didAccelerateFunc: (event: AccelerometerData) => void;
|
||||
|
||||
constructor () {
|
||||
this._didAccelerateFunc = this._didAccelerate.bind(this);
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
minigame.onAccelerometerChange(this._didAccelerateFunc);
|
||||
}
|
||||
|
||||
private _unregisterEvent (): void {
|
||||
minigame.offAccelerometerChange(this._didAccelerateFunc);
|
||||
}
|
||||
|
||||
private _didAccelerate (event: AccelerometerData): void {
|
||||
const timestamp = performance.now();
|
||||
const acceleration = new Acceleration(event.x, event.y, event.z, timestamp);
|
||||
const eventAcceleration = new EventAcceleration(acceleration);
|
||||
this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration);
|
||||
}
|
||||
|
||||
public start (): void {
|
||||
this._registerEvent();
|
||||
minigame.startAccelerometer({
|
||||
interval: this._accelMode,
|
||||
success: () => {
|
||||
this._isStarted = true;
|
||||
},
|
||||
});
|
||||
}
|
||||
public stop (): void {
|
||||
minigame.stopAccelerometer({
|
||||
success: () => {
|
||||
this._isStarted = false;
|
||||
},
|
||||
fail () {
|
||||
errorID(16305);
|
||||
},
|
||||
});
|
||||
this._unregisterEvent();
|
||||
}
|
||||
public setInterval (intervalInMileseconds: number): void {
|
||||
// reference: https://developers.weixin.qq.com/minigame/dev/api/device/accelerometer/wx.startAccelerometer.html
|
||||
if (intervalInMileseconds >= 200) {
|
||||
this._accelMode = 'normal';
|
||||
} else if (intervalInMileseconds >= 60) {
|
||||
this._accelMode = 'ui';
|
||||
} else {
|
||||
this._accelMode = 'game';
|
||||
}
|
||||
if (this._isStarted) {
|
||||
// restart accelerometer
|
||||
this.stop();
|
||||
this.start();
|
||||
}
|
||||
}
|
||||
public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { GamepadCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source';
|
||||
import { Quat, Vec3 } from '../../../cocos/core';
|
||||
|
||||
export class GamepadInputDevice {
|
||||
public static all: GamepadInputDevice[] = [];
|
||||
public static xr: (GamepadInputDevice | null) = null;
|
||||
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonL1 (): InputSourceButton { return this._buttonL1; }
|
||||
public get buttonL2 (): InputSourceButton { return this._buttonL2; }
|
||||
public get buttonL3 (): InputSourceButton { return this._buttonL3; }
|
||||
public get buttonR1 (): InputSourceButton { return this._buttonR1; }
|
||||
public get buttonR2 (): InputSourceButton { return this._buttonR2; }
|
||||
public get buttonR3 (): InputSourceButton { return this._buttonR3; }
|
||||
// public get buttonTouchPad () { return this._buttonTouchPad; }
|
||||
// public get buttonHome () { return this._buttonHome; }
|
||||
public get buttonShare (): InputSourceButton { return this._buttonShare; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get dpad (): InputSourceDpad { return this._dpad; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
|
||||
public get deviceId (): number {
|
||||
return this._deviceId;
|
||||
}
|
||||
public get connected (): boolean {
|
||||
return this._connected;
|
||||
}
|
||||
|
||||
private static _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonL1: InputSourceButton;
|
||||
private declare _buttonL2: InputSourceButton;
|
||||
private declare _buttonL3: InputSourceButton;
|
||||
private declare _buttonR1: InputSourceButton;
|
||||
private declare _buttonR2: InputSourceButton;
|
||||
private declare _buttonR3: InputSourceButton;
|
||||
// private declare buttonTouchPad: InputSourceButton;
|
||||
// private declare buttonHome: InputSourceButton;
|
||||
private declare _buttonShare: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _dpad: InputSourceDpad;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
|
||||
private _deviceId = -1;
|
||||
private _connected = false;
|
||||
|
||||
constructor (deviceId: number) {
|
||||
this._deviceId = deviceId;
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _init (): void {
|
||||
// not supported
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void {
|
||||
GamepadInputDevice._eventTarget.on(eventType, cb, target);
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
const self = this;
|
||||
self._buttonNorth = new InputSourceButton();
|
||||
self._buttonNorth.getValue = (): number => 0;
|
||||
self._buttonEast = new InputSourceButton();
|
||||
self._buttonEast.getValue = (): number => 0;
|
||||
self._buttonWest = new InputSourceButton();
|
||||
self._buttonWest.getValue = (): number => 0;
|
||||
self._buttonSouth = new InputSourceButton();
|
||||
self._buttonSouth.getValue = (): number => 0;
|
||||
|
||||
self._buttonL1 = new InputSourceButton();
|
||||
self._buttonL1.getValue = (): number => 0;
|
||||
self._buttonL2 = new InputSourceButton();
|
||||
self._buttonL2.getValue = (): number => 0;
|
||||
self._buttonL3 = new InputSourceButton();
|
||||
self._buttonL3.getValue = (): number => 0;
|
||||
self._buttonR1 = new InputSourceButton();
|
||||
self._buttonR1.getValue = (): number => 0;
|
||||
self._buttonR2 = new InputSourceButton();
|
||||
self._buttonR2.getValue = (): number => 0;
|
||||
self._buttonR3 = new InputSourceButton();
|
||||
self._buttonR3.getValue = (): number => 0;
|
||||
|
||||
// self._buttonTouchPad = new InputSourceButton();
|
||||
// self._buttonTouchPad.getValue = () => 0;
|
||||
// self._buttonHome = new InputSourceButton();
|
||||
// self._buttonHome.getValue = () => 0;
|
||||
|
||||
self._buttonShare = new InputSourceButton();
|
||||
self._buttonShare.getValue = (): number => 0;
|
||||
self._buttonOptions = new InputSourceButton();
|
||||
self._buttonOptions.getValue = (): number => 0;
|
||||
|
||||
const dpadUp = new InputSourceButton();
|
||||
dpadUp.getValue = (): number => 0;
|
||||
const dpadDown = new InputSourceButton();
|
||||
dpadDown.getValue = (): number => 0;
|
||||
const dpadLeft = new InputSourceButton();
|
||||
dpadLeft.getValue = (): number => 0;
|
||||
const dpadRight = new InputSourceButton();
|
||||
dpadRight.getValue = (): number => 0;
|
||||
self._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight });
|
||||
|
||||
const leftStickUp = new InputSourceButton();
|
||||
leftStickUp.getValue = (): number => 0;
|
||||
const leftStickDown = new InputSourceButton();
|
||||
leftStickDown.getValue = (): number => 0;
|
||||
const leftStickLeft = new InputSourceButton();
|
||||
leftStickLeft.getValue = (): number => 0;
|
||||
const leftStickRight = new InputSourceButton();
|
||||
leftStickRight.getValue = (): number => 0;
|
||||
self._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight });
|
||||
|
||||
const rightStickUp = new InputSourceButton();
|
||||
rightStickUp.getValue = (): number => 0;
|
||||
const rightStickDown = new InputSourceButton();
|
||||
rightStickDown.getValue = (): number => 0;
|
||||
const rightStickLeft = new InputSourceButton();
|
||||
rightStickLeft.getValue = (): number => 0;
|
||||
const rightStickRight = new InputSourceButton();
|
||||
rightStickRight.getValue = (): number => 0;
|
||||
self._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight });
|
||||
|
||||
self._buttonStart = new InputSourceButton();
|
||||
self._buttonStart.getValue = (): number => 0;
|
||||
|
||||
self._gripLeft = new InputSourceButton();
|
||||
self._gripLeft.getValue = (): number => 0;
|
||||
self._gripRight = new InputSourceButton();
|
||||
self._gripRight.getValue = (): number => 0;
|
||||
|
||||
self._handLeftPosition = new InputSourcePosition();
|
||||
self._handLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._handLeftOrientation = new InputSourceOrientation();
|
||||
self._handLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._handRightPosition = new InputSourcePosition();
|
||||
self._handRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._handRightOrientation = new InputSourceOrientation();
|
||||
self._handRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._aimLeftPosition = new InputSourcePosition();
|
||||
self._aimLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._aimLeftOrientation = new InputSourceOrientation();
|
||||
self._aimLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._aimRightPosition = new InputSourcePosition();
|
||||
self._aimRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._aimRightOrientation = new InputSourceOrientation();
|
||||
self._aimRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HandheldCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Quat, Vec3 } from '../../../cocos/core/math';
|
||||
|
||||
export class HandheldInputDevice {
|
||||
public get handheldPosition (): InputSourcePosition { return this._handheldPosition; }
|
||||
public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _handheldPosition: InputSourcePosition;
|
||||
private declare _handheldOrientation: InputSourceOrientation;
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._handheldPosition = new InputSourcePosition();
|
||||
this._handheldPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._handheldOrientation = new InputSourceOrientation();
|
||||
this._handheldOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HandleCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export class HandleInputDevice {
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; }
|
||||
public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; }
|
||||
public get triggerLeft (): InputSourceButton { return this._triggerLeft; }
|
||||
public get triggerRight (): InputSourceButton { return this._triggerRight; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; }
|
||||
public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
public get touchButtonA (): InputSourceTouch { return this._touchButtonA; }
|
||||
public get touchButtonB (): InputSourceTouch { return this._touchButtonB; }
|
||||
public get touchButtonX (): InputSourceTouch { return this._touchButtonX; }
|
||||
public get touchButtonY (): InputSourceTouch { return this._touchButtonY; }
|
||||
public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; }
|
||||
public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; }
|
||||
public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; }
|
||||
public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonTriggerLeft: InputSourceButton;
|
||||
private declare _buttonTriggerRight: InputSourceButton;
|
||||
private declare _triggerLeft: InputSourceButton;
|
||||
private declare _triggerRight: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonLeftStick: InputSourceButton;
|
||||
private declare _buttonRightStick: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
private declare _touchButtonA: InputSourceTouch;
|
||||
private declare _touchButtonB: InputSourceTouch;
|
||||
private declare _touchButtonX: InputSourceTouch;
|
||||
private declare _touchButtonY: InputSourceTouch;
|
||||
private declare _touchButtonTriggerLeft: InputSourceTouch;
|
||||
private declare _touchButtonTriggerRight: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickLeft: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickRight: InputSourceTouch;
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
const self = this;
|
||||
self._buttonNorth = new InputSourceButton();
|
||||
self._buttonNorth.getValue = (): number => 0;
|
||||
self._buttonEast = new InputSourceButton();
|
||||
self._buttonEast.getValue = (): number => 0;
|
||||
self._buttonWest = new InputSourceButton();
|
||||
self._buttonWest.getValue = (): number => 0;
|
||||
self._buttonSouth = new InputSourceButton();
|
||||
self._buttonSouth.getValue = (): number => 0;
|
||||
|
||||
self._buttonTriggerLeft = new InputSourceButton();
|
||||
self._buttonTriggerLeft.getValue = (): number => 0;
|
||||
self._buttonTriggerRight = new InputSourceButton();
|
||||
self._buttonTriggerRight.getValue = (): number => 0;
|
||||
self._triggerLeft = new InputSourceButton();
|
||||
self._triggerLeft.getValue = (): number => 0;
|
||||
self._triggerRight = new InputSourceButton();
|
||||
self._triggerRight.getValue = (): number => 0;
|
||||
self._gripLeft = new InputSourceButton();
|
||||
self._gripLeft.getValue = (): number => 0;
|
||||
self._gripRight = new InputSourceButton();
|
||||
self._gripRight.getValue = (): number => 0;
|
||||
|
||||
self._buttonLeftStick = new InputSourceButton();
|
||||
self._buttonLeftStick.getValue = (): number => 0;
|
||||
const leftStickUp = new InputSourceButton();
|
||||
leftStickUp.getValue = (): number => 0;
|
||||
const leftStickDown = new InputSourceButton();
|
||||
leftStickDown.getValue = (): number => 0;
|
||||
const leftStickLeft = new InputSourceButton();
|
||||
leftStickLeft.getValue = (): number => 0;
|
||||
const leftStickRight = new InputSourceButton();
|
||||
leftStickRight.getValue = (): number => 0;
|
||||
self._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight });
|
||||
|
||||
self._buttonRightStick = new InputSourceButton();
|
||||
self._buttonRightStick.getValue = (): number => 0;
|
||||
const rightStickUp = new InputSourceButton();
|
||||
rightStickUp.getValue = (): number => 0;
|
||||
const rightStickDown = new InputSourceButton();
|
||||
rightStickDown.getValue = (): number => 0;
|
||||
const rightStickLeft = new InputSourceButton();
|
||||
rightStickLeft.getValue = (): number => 0;
|
||||
const rightStickRight = new InputSourceButton();
|
||||
rightStickRight.getValue = (): number => 0;
|
||||
self._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight });
|
||||
|
||||
self._buttonOptions = new InputSourceButton();
|
||||
self._buttonOptions.getValue = (): number => 0;
|
||||
self._buttonStart = new InputSourceButton();
|
||||
self._buttonStart.getValue = (): number => 0;
|
||||
|
||||
self._handLeftPosition = new InputSourcePosition();
|
||||
self._handLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._handLeftOrientation = new InputSourceOrientation();
|
||||
self._handLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._handRightPosition = new InputSourcePosition();
|
||||
self._handRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._handRightOrientation = new InputSourceOrientation();
|
||||
self._handRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._aimLeftPosition = new InputSourcePosition();
|
||||
self._aimLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._aimLeftOrientation = new InputSourceOrientation();
|
||||
self._aimLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._aimRightPosition = new InputSourcePosition();
|
||||
self._aimRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._aimRightOrientation = new InputSourceOrientation();
|
||||
self._aimRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._touchButtonA = new InputSourceTouch();
|
||||
self._touchButtonA.getValue = (): number => 0;
|
||||
self._touchButtonB = new InputSourceTouch();
|
||||
self._touchButtonB.getValue = (): number => 0;
|
||||
self._touchButtonX = new InputSourceTouch();
|
||||
self._touchButtonX.getValue = (): number => 0;
|
||||
self._touchButtonY = new InputSourceTouch();
|
||||
self._touchButtonY.getValue = (): number => 0;
|
||||
self._touchButtonTriggerLeft = new InputSourceTouch();
|
||||
self._touchButtonTriggerLeft.getValue = (): number => 0;
|
||||
self._touchButtonTriggerRight = new InputSourceTouch();
|
||||
self._touchButtonTriggerRight.getValue = (): number => 0;
|
||||
self._touchButtonThumbStickLeft = new InputSourceTouch();
|
||||
self._touchButtonThumbStickLeft.getValue = (): number => 0;
|
||||
self._touchButtonThumbStickRight = new InputSourceTouch();
|
||||
self._touchButtonThumbStickRight.getValue = (): number => 0;
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HMDCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export class HMDInputDevice {
|
||||
public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; }
|
||||
public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; }
|
||||
public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; }
|
||||
public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; }
|
||||
public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; }
|
||||
public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _viewLeftPosition: InputSourcePosition;
|
||||
private declare _viewLeftOrientation: InputSourceOrientation;
|
||||
private declare _viewRightPosition: InputSourcePosition;
|
||||
private declare _viewRightOrientation: InputSourceOrientation;
|
||||
private declare _headMiddlePosition: InputSourcePosition;
|
||||
private declare _headMiddleOrientation: InputSourceOrientation;
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
const self = this;
|
||||
self._viewLeftPosition = new InputSourcePosition();
|
||||
self._viewLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._viewLeftOrientation = new InputSourceOrientation();
|
||||
self._viewLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._viewRightPosition = new InputSourcePosition();
|
||||
self._viewRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._viewRightOrientation = new InputSourceOrientation();
|
||||
self._viewRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
self._headMiddlePosition = new InputSourcePosition();
|
||||
self._headMiddlePosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
self._headMiddleOrientation = new InputSourceOrientation();
|
||||
self._headMiddleOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
export * from './accelerometer-input';
|
||||
export * from './gamepad-input';
|
||||
export * from './handle-input';
|
||||
export * from './hmd-input';
|
||||
export * from './handheld-input';
|
||||
export * from './keyboard-input';
|
||||
export * from './mouse-input';
|
||||
export * from './touch-input';
|
||||
|
||||
checkPalIntegrity<typeof import('pal/input')>(withImpl<typeof import('./index')>());
|
||||
@@ -1,181 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { KeyboardCallback } from 'pal/input';
|
||||
import { KeyboardEventData, minigame } from 'pal/minigame';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { KeyCode, EventKeyboard } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
|
||||
const code2KeyCode: Record<string, KeyCode> = {
|
||||
Backspace: KeyCode.BACKSPACE,
|
||||
Tab: KeyCode.TAB,
|
||||
Enter: KeyCode.ENTER,
|
||||
ShiftLeft: KeyCode.SHIFT_LEFT,
|
||||
ControlLeft: KeyCode.CTRL_LEFT,
|
||||
AltLeft: KeyCode.ALT_LEFT,
|
||||
ShiftRight: KeyCode.SHIFT_RIGHT,
|
||||
ControlRight: KeyCode.CTRL_RIGHT,
|
||||
AltRight: KeyCode.ALT_RIGHT,
|
||||
Pause: KeyCode.PAUSE,
|
||||
CapsLock: KeyCode.CAPS_LOCK,
|
||||
Escape: KeyCode.ESCAPE,
|
||||
Space: KeyCode.SPACE,
|
||||
PageUp: KeyCode.PAGE_UP,
|
||||
PageDown: KeyCode.PAGE_DOWN,
|
||||
End: KeyCode.END,
|
||||
Home: KeyCode.HOME,
|
||||
ArrowLeft: KeyCode.ARROW_LEFT,
|
||||
ArrowUp: KeyCode.ARROW_UP,
|
||||
ArrowRight: KeyCode.ARROW_RIGHT,
|
||||
ArrowDown: KeyCode.ARROW_DOWN,
|
||||
Insert: KeyCode.INSERT,
|
||||
Delete: KeyCode.DELETE,
|
||||
Digit0: KeyCode.DIGIT_0,
|
||||
Digit1: KeyCode.DIGIT_1,
|
||||
Digit2: KeyCode.DIGIT_2,
|
||||
Digit3: KeyCode.DIGIT_3,
|
||||
Digit4: KeyCode.DIGIT_4,
|
||||
Digit5: KeyCode.DIGIT_5,
|
||||
Digit6: KeyCode.DIGIT_6,
|
||||
Digit7: KeyCode.DIGIT_7,
|
||||
Digit8: KeyCode.DIGIT_8,
|
||||
Digit9: KeyCode.DIGIT_9,
|
||||
KeyA: KeyCode.KEY_A,
|
||||
KeyB: KeyCode.KEY_B,
|
||||
KeyC: KeyCode.KEY_C,
|
||||
KeyD: KeyCode.KEY_D,
|
||||
KeyE: KeyCode.KEY_E,
|
||||
KeyF: KeyCode.KEY_F,
|
||||
KeyG: KeyCode.KEY_G,
|
||||
KeyH: KeyCode.KEY_H,
|
||||
KeyI: KeyCode.KEY_I,
|
||||
KeyJ: KeyCode.KEY_J,
|
||||
KeyK: KeyCode.KEY_K,
|
||||
KeyL: KeyCode.KEY_L,
|
||||
KeyM: KeyCode.KEY_M,
|
||||
KeyN: KeyCode.KEY_N,
|
||||
KeyO: KeyCode.KEY_O,
|
||||
KeyP: KeyCode.KEY_P,
|
||||
KeyQ: KeyCode.KEY_Q,
|
||||
KeyR: KeyCode.KEY_R,
|
||||
KeyS: KeyCode.KEY_S,
|
||||
KeyT: KeyCode.KEY_T,
|
||||
KeyU: KeyCode.KEY_U,
|
||||
KeyV: KeyCode.KEY_V,
|
||||
KeyW: KeyCode.KEY_W,
|
||||
KeyX: KeyCode.KEY_X,
|
||||
KeyY: KeyCode.KEY_Y,
|
||||
KeyZ: KeyCode.KEY_Z,
|
||||
Numpad0: KeyCode.NUM_0,
|
||||
Numpad1: KeyCode.NUM_1,
|
||||
Numpad2: KeyCode.NUM_2,
|
||||
Numpad3: KeyCode.NUM_3,
|
||||
Numpad4: KeyCode.NUM_4,
|
||||
Numpad5: KeyCode.NUM_5,
|
||||
Numpad6: KeyCode.NUM_6,
|
||||
Numpad7: KeyCode.NUM_7,
|
||||
Numpad8: KeyCode.NUM_8,
|
||||
Numpad9: KeyCode.NUM_9,
|
||||
NumpadMultiply: KeyCode.NUM_MULTIPLY,
|
||||
NumpadAdd: KeyCode.NUM_PLUS,
|
||||
NumpadSubtract: KeyCode.NUM_SUBTRACT,
|
||||
NumpadDecimal: KeyCode.NUM_DECIMAL,
|
||||
NumpadDivide: KeyCode.NUM_DIVIDE,
|
||||
NumpadEnter: KeyCode.NUM_ENTER,
|
||||
F1: KeyCode.F1,
|
||||
F2: KeyCode.F2,
|
||||
F3: KeyCode.F3,
|
||||
F4: KeyCode.F4,
|
||||
F5: KeyCode.F5,
|
||||
F6: KeyCode.F6,
|
||||
F7: KeyCode.F7,
|
||||
F8: KeyCode.F8,
|
||||
F9: KeyCode.F9,
|
||||
F10: KeyCode.F10,
|
||||
F11: KeyCode.F11,
|
||||
F12: KeyCode.F12,
|
||||
NumLock: KeyCode.NUM_LOCK,
|
||||
ScrollLock: KeyCode.SCROLL_LOCK,
|
||||
Semicolon: KeyCode.SEMICOLON,
|
||||
Equal: KeyCode.EQUAL,
|
||||
Comma: KeyCode.COMMA,
|
||||
Minus: KeyCode.DASH,
|
||||
Period: KeyCode.PERIOD,
|
||||
Slash: KeyCode.SLASH,
|
||||
Backquote: KeyCode.BACK_QUOTE,
|
||||
BracketLeft: KeyCode.BRACKET_LEFT,
|
||||
Backslash: KeyCode.BACKSLASH,
|
||||
BracketRight: KeyCode.BRACKET_RIGHT,
|
||||
Quote: KeyCode.QUOTE,
|
||||
};
|
||||
|
||||
function getKeyCode (code: string): KeyCode {
|
||||
return code2KeyCode[code] || KeyCode.NONE;
|
||||
}
|
||||
|
||||
export class KeyboardInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
// KeyboardEvent.repeat is not supported on Wechat PC platform.
|
||||
private _keyStateMap: Record<number, boolean> = {};
|
||||
|
||||
constructor () {
|
||||
if (systemInfo.hasFeature(Feature.EVENT_KEYBOARD)) {
|
||||
this._registerEvent();
|
||||
}
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
minigame.wx?.onKeyDown?.((res) => {
|
||||
const keyCode = getKeyCode(res.code);
|
||||
if (!this._keyStateMap[keyCode]) {
|
||||
const eventKeyDown = this._getInputEvent(res, InputEventType.KEY_DOWN);
|
||||
this._eventTarget.emit(InputEventType.KEY_DOWN, eventKeyDown);
|
||||
} else {
|
||||
const eventKeyPressing = this._getInputEvent(res, InputEventType.KEY_PRESSING);
|
||||
this._eventTarget.emit(InputEventType.KEY_PRESSING, eventKeyPressing);
|
||||
}
|
||||
this._keyStateMap[keyCode] = true;
|
||||
});
|
||||
minigame.wx?.onKeyUp?.((res) => {
|
||||
const keyCode = getKeyCode(res.code);
|
||||
const eventKeyUp = this._getInputEvent(res, InputEventType.KEY_UP);
|
||||
this._keyStateMap[keyCode] = false;
|
||||
this._eventTarget.emit(InputEventType.KEY_UP, eventKeyUp);
|
||||
});
|
||||
}
|
||||
|
||||
private _getInputEvent (event: KeyboardEventData, eventType: InputEventType): EventKeyboard {
|
||||
const keyCode = getKeyCode(event.code);
|
||||
const eventKeyboard = new EventKeyboard(keyCode, eventType);
|
||||
return eventKeyboard;
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { MouseCallback } from 'pal/input';
|
||||
import { MouseEventData, MouseWheelEventData, minigame } from 'pal/minigame';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { Vec2 } from '../../../cocos/core/math';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { EventMouse } from '../../../cocos/input/types';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
|
||||
export class MouseInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private _isPressed = false;
|
||||
private _preMousePos: Vec2 = new Vec2();
|
||||
|
||||
constructor () {
|
||||
if (systemInfo.hasFeature(Feature.EVENT_MOUSE)) {
|
||||
this._registerEvent();
|
||||
}
|
||||
}
|
||||
|
||||
private _getLocation (event: MouseEventData): Vec2 {
|
||||
const windowSize = screenAdapter.windowSize;
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
const x = event.x * dpr;
|
||||
const y = windowSize.height - event.y * dpr;
|
||||
return new Vec2(x, y);
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
minigame.wx?.onMouseDown?.(this._createCallback(InputEventType.MOUSE_DOWN));
|
||||
minigame.wx?.onMouseMove?.(this._createCallback(InputEventType.MOUSE_MOVE));
|
||||
minigame.wx?.onMouseUp?.(this._createCallback(InputEventType.MOUSE_UP));
|
||||
minigame.wx?.onWheel?.(this._handleMouseWheel.bind(this));
|
||||
}
|
||||
|
||||
private _createCallback (eventType: InputEventType) {
|
||||
return (event: MouseEventData): void => {
|
||||
const location = this._getLocation(event);
|
||||
let button = event.button;
|
||||
switch (eventType) {
|
||||
case InputEventType.MOUSE_DOWN:
|
||||
this._isPressed = true;
|
||||
break;
|
||||
case InputEventType.MOUSE_UP:
|
||||
this._isPressed = false;
|
||||
break;
|
||||
case InputEventType.MOUSE_MOVE:
|
||||
if (!this._isPressed) {
|
||||
button = EventMouse.BUTTON_MISSING;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const eventMouse = new EventMouse(eventType, false, this._preMousePos);
|
||||
eventMouse.setLocation(location.x, location.y);
|
||||
eventMouse.setButton(button);
|
||||
eventMouse.movementX = location.x - this._preMousePos.x;
|
||||
eventMouse.movementY = this._preMousePos.y - location.y;
|
||||
|
||||
// update previous mouse position.
|
||||
this._preMousePos.set(location.x, location.y);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
};
|
||||
}
|
||||
|
||||
private _handleMouseWheel (event: MouseWheelEventData): void {
|
||||
const eventType = InputEventType.MOUSE_WHEEL;
|
||||
const location = this._getLocation(event);
|
||||
const button = event.button;
|
||||
|
||||
const eventMouse = new EventMouse(eventType, false, this._preMousePos);
|
||||
eventMouse.setLocation(location.x, location.y);
|
||||
eventMouse.setButton(button);
|
||||
eventMouse.movementX = location.x - this._preMousePos.x;
|
||||
eventMouse.movementY = this._preMousePos.y - location.y;
|
||||
|
||||
eventMouse.setScrollData(event.deltaX, -event.deltaY);
|
||||
// update previous mouse position.
|
||||
this._preMousePos.set(location.x, location.y);
|
||||
this._eventTarget.emit(InputEventType.MOUSE_WHEEL, eventMouse);
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: MouseCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { TouchCallback } from 'pal/input';
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { Size, Vec2 } from '../../../cocos/core/math';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { EventTouch, Touch } from '../../../cocos/input/types';
|
||||
import { touchManager } from '../touch-manager';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
|
||||
export class TouchInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
constructor () {
|
||||
if (systemInfo.hasFeature(Feature.INPUT_TOUCH)) {
|
||||
this._registerEvent();
|
||||
}
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
minigame.onTouchStart(this._createCallback(InputEventType.TOUCH_START));
|
||||
minigame.onTouchMove(this._createCallback(InputEventType.TOUCH_MOVE));
|
||||
minigame.onTouchEnd(this._createCallback(InputEventType.TOUCH_END));
|
||||
minigame.onTouchCancel(this._createCallback(InputEventType.TOUCH_CANCEL));
|
||||
}
|
||||
|
||||
private _createCallback (eventType: InputEventType) {
|
||||
return (event: TouchEvent): void => {
|
||||
const handleTouches: Touch[] = [];
|
||||
const windowSize = screenAdapter.windowSize;
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
const length = event.changedTouches.length;
|
||||
for (let i = 0; i < length; ++i) {
|
||||
const changedTouch = event.changedTouches[i];
|
||||
const touchID = changedTouch.identifier;
|
||||
if (touchID === null) {
|
||||
continue;
|
||||
}
|
||||
const location = this._getLocation(changedTouch, windowSize, dpr);
|
||||
const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y);
|
||||
if (!touch) {
|
||||
continue;
|
||||
}
|
||||
if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) {
|
||||
touchManager.releaseTouch(touchID);
|
||||
}
|
||||
handleTouches.push(touch);
|
||||
}
|
||||
if (handleTouches.length > 0) {
|
||||
const eventTouch = new EventTouch(
|
||||
handleTouches,
|
||||
false,
|
||||
eventType,
|
||||
touchManager.getAllTouches(),
|
||||
);
|
||||
this._eventTarget.emit(eventType, eventTouch);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private _getLocation (touch: globalThis.Touch, windowSize: Size, dpr: number): Vec2 {
|
||||
const x = touch.clientX * dpr;
|
||||
const y = windowSize.height - touch.clientY * dpr;
|
||||
return new Vec2(x, y);
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: TouchCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { OS } from '../../system-info/enum-type';
|
||||
import { Orientation } from '../../screen-adapter/enum-type';
|
||||
import { Acceleration, EventAcceleration } from '../../../cocos/input/types';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
|
||||
export type AccelerometerCallback = (res: EventAcceleration) => void;
|
||||
|
||||
export class AccelerometerInputSource {
|
||||
private _intervalInSeconds = 0.2;
|
||||
private _intervalId?: number;
|
||||
private _isEnabled = false;
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private declare _didAccelerateFunc: () => void;
|
||||
|
||||
constructor () {
|
||||
this._didAccelerateFunc = this._didAccelerate.bind(this);
|
||||
}
|
||||
|
||||
private _didAccelerate (): void {
|
||||
const deviceMotionValue = jsb.device.getDeviceMotionValue();
|
||||
let x = deviceMotionValue[3] * 0.1;
|
||||
let y = deviceMotionValue[4] * 0.1;
|
||||
const z = deviceMotionValue[5] * 0.1;
|
||||
|
||||
const orientation = screenAdapter.orientation;
|
||||
const tmpX = x;
|
||||
if (orientation === Orientation.LANDSCAPE_RIGHT) {
|
||||
x = -y;
|
||||
y = tmpX;
|
||||
} else if (orientation === Orientation.LANDSCAPE_LEFT) {
|
||||
x = y;
|
||||
y = -tmpX;
|
||||
} else if (orientation === Orientation.PORTRAIT_UPSIDE_DOWN) {
|
||||
x = -x;
|
||||
y = -y;
|
||||
}
|
||||
|
||||
// fix android acc values are opposite
|
||||
if (systemInfo.os === OS.ANDROID || systemInfo.os === OS.OHOS || systemInfo.os === OS.OPENHARMONY) {
|
||||
x = -x;
|
||||
y = -y;
|
||||
}
|
||||
|
||||
const timestamp = performance.now();
|
||||
const acceleration = new Acceleration(x, y, z, timestamp);
|
||||
const eventAcceleration = new EventAcceleration(acceleration);
|
||||
this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration);
|
||||
}
|
||||
|
||||
public start (): void {
|
||||
if (this._intervalId) {
|
||||
clearInterval(this._intervalId);
|
||||
}
|
||||
this._intervalId = setInterval(this._didAccelerateFunc, this._intervalInSeconds * 1000);
|
||||
jsb.device.setAccelerometerInterval(this._intervalInSeconds);
|
||||
jsb.device.setAccelerometerEnabled(true);
|
||||
this._isEnabled = true;
|
||||
}
|
||||
public stop (): void {
|
||||
if (this._intervalId) {
|
||||
clearInterval(this._intervalId);
|
||||
this._intervalId = undefined;
|
||||
}
|
||||
jsb.device.setAccelerometerEnabled(false);
|
||||
this._isEnabled = false;
|
||||
}
|
||||
public setInterval (intervalInMileseconds: number): void {
|
||||
this._intervalInSeconds = intervalInMileseconds / 1000;
|
||||
jsb.device.setAccelerometerInterval(this._intervalInSeconds);
|
||||
if (this._isEnabled) {
|
||||
// restart accelerometer
|
||||
jsb.device.setAccelerometerEnabled(false);
|
||||
jsb.device.setAccelerometerEnabled(true);
|
||||
}
|
||||
}
|
||||
public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,427 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* eslint-disable brace-style */
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventGamepad } from '../../../cocos/input/types';
|
||||
import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source';
|
||||
import { Quat, Vec3, js } from '../../../cocos/core';
|
||||
|
||||
export type GamepadCallback = (res: EventGamepad) => void;
|
||||
|
||||
enum Button {
|
||||
BUTTON_SOUTH,
|
||||
BUTTON_EAST,
|
||||
BUTTON_WEST,
|
||||
BUTTON_NORTH,
|
||||
NS_MINUS,
|
||||
NS_PLUS,
|
||||
BUTTON_L1,
|
||||
BUTTON_L2,
|
||||
BUTTON_L3,
|
||||
BUTTON_R1,
|
||||
BUTTON_R2,
|
||||
BUTTON_R3,
|
||||
DPAD_UP,
|
||||
DPAD_DOWN,
|
||||
DPAD_LEFT,
|
||||
DPAD_RIGHT,
|
||||
LEFT_STICK_UP,
|
||||
LEFT_STICK_DOWN,
|
||||
LEFT_STICK_LEFT,
|
||||
LEFT_STICK_RIGHT,
|
||||
RIGHT_STICK_UP,
|
||||
RIGHT_STICK_DOWN,
|
||||
RIGHT_STICK_LEFT,
|
||||
RIGHT_STICK_RIGHT,
|
||||
ROKID_MENU,
|
||||
ROKID_START,
|
||||
}
|
||||
|
||||
type NativeButtonState = Record<Button, number>
|
||||
|
||||
const _nativeButtonMap = {
|
||||
1: Button.BUTTON_EAST,
|
||||
2: Button.BUTTON_SOUTH,
|
||||
3: Button.BUTTON_NORTH,
|
||||
4: Button.BUTTON_WEST,
|
||||
5: Button.BUTTON_L1,
|
||||
6: Button.BUTTON_R1,
|
||||
7: Button.NS_MINUS,
|
||||
8: Button.NS_PLUS,
|
||||
9: Button.BUTTON_L3,
|
||||
10: Button.BUTTON_R3,
|
||||
11: Button.ROKID_MENU,
|
||||
12: Button.ROKID_START,
|
||||
};
|
||||
|
||||
interface IAxisValue {
|
||||
negative: number;
|
||||
positive: number;
|
||||
}
|
||||
|
||||
export class GamepadInputDevice {
|
||||
public static all: GamepadInputDevice[] = [];
|
||||
public static xr: (GamepadInputDevice | null) = null;
|
||||
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonL1 (): InputSourceButton { return this._buttonL1; }
|
||||
public get buttonL2 (): InputSourceButton { return this._buttonL2; }
|
||||
public get buttonL3 (): InputSourceButton { return this._buttonL3; }
|
||||
public get buttonR1 (): InputSourceButton { return this._buttonR1; }
|
||||
public get buttonR2 (): InputSourceButton { return this._buttonR2; }
|
||||
public get buttonR3 (): InputSourceButton { return this._buttonR3; }
|
||||
// public get buttonTouchPad () { return this._buttonTouchPad; }
|
||||
// public get buttonHome () { return this._buttonHome; }
|
||||
public get buttonShare (): InputSourceButton { return this._buttonShare; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get dpad (): InputSourceDpad { return this._dpad; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
|
||||
public get deviceId (): number {
|
||||
return this._deviceId;
|
||||
}
|
||||
public get connected (): boolean {
|
||||
return this._connected;
|
||||
}
|
||||
|
||||
private static _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonL1: InputSourceButton;
|
||||
private declare _buttonL2: InputSourceButton;
|
||||
private declare _buttonL3: InputSourceButton;
|
||||
private declare _buttonR1: InputSourceButton;
|
||||
private declare _buttonR2: InputSourceButton;
|
||||
private declare _buttonR3: InputSourceButton;
|
||||
// private declare buttonTouchPad: InputSourceButton;
|
||||
// private declare buttonHome: InputSourceButton;
|
||||
private declare _buttonShare: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _dpad: InputSourceDpad;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
|
||||
private _deviceId = -1;
|
||||
private _connected = false;
|
||||
private _nativeButtonState: NativeButtonState = {
|
||||
[Button.BUTTON_SOUTH]: 0,
|
||||
[Button.BUTTON_EAST]: 0,
|
||||
[Button.BUTTON_WEST]: 0,
|
||||
[Button.BUTTON_NORTH]: 0,
|
||||
[Button.NS_MINUS]: 0,
|
||||
[Button.NS_PLUS]: 0,
|
||||
[Button.BUTTON_L1]: 0,
|
||||
[Button.BUTTON_L2]: 0,
|
||||
[Button.BUTTON_L3]: 0,
|
||||
[Button.BUTTON_R1]: 0,
|
||||
[Button.BUTTON_R2]: 0,
|
||||
[Button.BUTTON_R3]: 0,
|
||||
[Button.DPAD_UP]: 0,
|
||||
[Button.DPAD_DOWN]: 0,
|
||||
[Button.DPAD_LEFT]: 0,
|
||||
[Button.DPAD_RIGHT]: 0,
|
||||
[Button.LEFT_STICK_UP]: 0,
|
||||
[Button.LEFT_STICK_DOWN]: 0,
|
||||
[Button.LEFT_STICK_LEFT]: 0,
|
||||
[Button.LEFT_STICK_RIGHT]: 0,
|
||||
[Button.RIGHT_STICK_UP]: 0,
|
||||
[Button.RIGHT_STICK_DOWN]: 0,
|
||||
[Button.RIGHT_STICK_LEFT]: 0,
|
||||
[Button.RIGHT_STICK_RIGHT]: 0,
|
||||
[Button.ROKID_MENU]: 0,
|
||||
[Button.ROKID_START]: 0,
|
||||
};
|
||||
|
||||
constructor (deviceId: number) {
|
||||
this._deviceId = deviceId;
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _init (): void {
|
||||
if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) {
|
||||
return;
|
||||
}
|
||||
GamepadInputDevice._registerEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void {
|
||||
GamepadInputDevice._eventTarget.on(eventType, cb, target);
|
||||
}
|
||||
|
||||
private static _removeInputDevice (id: number): void {
|
||||
const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id);
|
||||
if (removeIndex === -1) {
|
||||
return;
|
||||
}
|
||||
js.array.fastRemoveAt(GamepadInputDevice.all, removeIndex);
|
||||
}
|
||||
private static _getInputDevice (id: number): GamepadInputDevice | undefined {
|
||||
return GamepadInputDevice.all.find((device) => device.deviceId === id);
|
||||
}
|
||||
private static _createInputDevice (id: number, connected: boolean): GamepadInputDevice {
|
||||
const device = new GamepadInputDevice(id);
|
||||
device._connected = connected;
|
||||
GamepadInputDevice.all.push(device);
|
||||
return device;
|
||||
}
|
||||
private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice {
|
||||
let device = GamepadInputDevice._getInputDevice(id);
|
||||
if (!device) {
|
||||
device = GamepadInputDevice._createInputDevice(id, connected);
|
||||
}
|
||||
device._connected = connected;
|
||||
return device;
|
||||
}
|
||||
|
||||
private static _registerEvent (): void {
|
||||
jsb.onControllerInput = (infoList: jsb.ControllerInfo[]): void => {
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
const device = GamepadInputDevice._getOrCreateInputDevice(info.id, true);
|
||||
device._updateNativeButtonState(info);
|
||||
GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device));
|
||||
}
|
||||
};
|
||||
|
||||
jsb.onControllerChange = (controllerIds): void => {
|
||||
// check connecting
|
||||
for (let i = 0; i < controllerIds.length; ++i) {
|
||||
const id = controllerIds[i];
|
||||
let device = GamepadInputDevice._getInputDevice(id);
|
||||
if (!device) {
|
||||
device = GamepadInputDevice._createInputDevice(id, true);
|
||||
GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
|
||||
}
|
||||
}
|
||||
// check disconnecting
|
||||
const allDevices = GamepadInputDevice.all;
|
||||
for (let i = 0; i < allDevices.length; ++i) {
|
||||
const device = allDevices[i];
|
||||
if (!controllerIds.includes(device.deviceId)) {
|
||||
GamepadInputDevice._removeInputDevice(device.deviceId);
|
||||
device._connected = false;
|
||||
GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private _axisToButtons (axisValue: number): IAxisValue {
|
||||
const value = Math.abs(axisValue);
|
||||
if (axisValue > 0) {
|
||||
return { negative: 0, positive: value };
|
||||
} else if (axisValue < 0) {
|
||||
return { negative: value, positive: 0 };
|
||||
} else {
|
||||
return { negative: 0, positive: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
private _updateNativeButtonState (info: jsb.ControllerInfo): void {
|
||||
const { buttonInfoList, axisInfoList } = info;
|
||||
for (let i = 0; i < buttonInfoList.length; ++i) {
|
||||
const buttonInfo = buttonInfoList[i];
|
||||
const button = _nativeButtonMap[buttonInfo.code];
|
||||
this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0;
|
||||
}
|
||||
for (let i = 0; i < axisInfoList.length; ++i) {
|
||||
const axisInfo = axisInfoList[i];
|
||||
const { code, value } = axisInfo;
|
||||
let negativeButton: Button | undefined;
|
||||
let positiveButton: Button | undefined;
|
||||
let axisValue: IAxisValue | undefined;
|
||||
switch (code) {
|
||||
case 1:
|
||||
negativeButton = Button.DPAD_LEFT;
|
||||
positiveButton = Button.DPAD_RIGHT;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case 2:
|
||||
negativeButton = Button.DPAD_DOWN;
|
||||
positiveButton = Button.DPAD_UP;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case 3:
|
||||
negativeButton = Button.LEFT_STICK_LEFT;
|
||||
positiveButton = Button.LEFT_STICK_RIGHT;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case 4:
|
||||
negativeButton = Button.LEFT_STICK_DOWN;
|
||||
positiveButton = Button.LEFT_STICK_UP;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case 5:
|
||||
negativeButton = Button.RIGHT_STICK_LEFT;
|
||||
positiveButton = Button.RIGHT_STICK_RIGHT;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case 6:
|
||||
negativeButton = Button.RIGHT_STICK_DOWN;
|
||||
positiveButton = Button.RIGHT_STICK_UP;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
default:
|
||||
if (code === 7) { this._nativeButtonState[Button.BUTTON_L2] = value; }
|
||||
else if (code === 8) { this._nativeButtonState[Button.BUTTON_R2] = value; }
|
||||
break;
|
||||
}
|
||||
if (negativeButton && positiveButton && axisValue) {
|
||||
this._nativeButtonState[negativeButton] = axisValue.negative;
|
||||
this._nativeButtonState[positiveButton] = axisValue.positive;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._buttonNorth = new InputSourceButton();
|
||||
this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH];
|
||||
this._buttonEast = new InputSourceButton();
|
||||
this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST];
|
||||
this._buttonWest = new InputSourceButton();
|
||||
this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST];
|
||||
this._buttonSouth = new InputSourceButton();
|
||||
this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH];
|
||||
|
||||
this._buttonL1 = new InputSourceButton();
|
||||
this._buttonL1.getValue = (): number => this._nativeButtonState[Button.BUTTON_L1];
|
||||
this._buttonL2 = new InputSourceButton();
|
||||
this._buttonL2.getValue = (): number => this._nativeButtonState[Button.BUTTON_L2];
|
||||
this._buttonL3 = new InputSourceButton();
|
||||
this._buttonL3.getValue = (): number => this._nativeButtonState[Button.BUTTON_L3];
|
||||
this._buttonR1 = new InputSourceButton();
|
||||
this._buttonR1.getValue = (): number => this._nativeButtonState[Button.BUTTON_R1];
|
||||
this._buttonR2 = new InputSourceButton();
|
||||
this._buttonR2.getValue = (): number => this._nativeButtonState[Button.BUTTON_R2];
|
||||
this._buttonR3 = new InputSourceButton();
|
||||
this._buttonR3.getValue = (): number => this._nativeButtonState[Button.BUTTON_R3];
|
||||
|
||||
// this._buttonTouchPad = new InputSourceButton();
|
||||
// this._buttonTouchPad.getValue = () => 0; // TODO: NX unavailable
|
||||
// this._buttonHome = new InputSourceButton();
|
||||
// this._buttonHome.getValue = () => 0; // TODO: NX unavailable
|
||||
|
||||
this._buttonShare = new InputSourceButton();
|
||||
this._buttonShare.getValue = (): number => this._nativeButtonState[Button.NS_MINUS]; // TODO: NX only for now
|
||||
this._buttonOptions = new InputSourceButton();
|
||||
this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.NS_PLUS] || this._nativeButtonState[Button.ROKID_MENU];
|
||||
|
||||
const dpadUp = new InputSourceButton();
|
||||
dpadUp.getValue = (): number => this._nativeButtonState[Button.DPAD_UP];
|
||||
const dpadDown = new InputSourceButton();
|
||||
dpadDown.getValue = (): number => this._nativeButtonState[Button.DPAD_DOWN];
|
||||
const dpadLeft = new InputSourceButton();
|
||||
dpadLeft.getValue = (): number => this._nativeButtonState[Button.DPAD_LEFT];
|
||||
const dpadRight = new InputSourceButton();
|
||||
dpadRight.getValue = (): number => this._nativeButtonState[Button.DPAD_RIGHT];
|
||||
this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight });
|
||||
|
||||
const leftStickUp = new InputSourceButton();
|
||||
leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP];
|
||||
const leftStickDown = new InputSourceButton();
|
||||
leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN];
|
||||
const leftStickLeft = new InputSourceButton();
|
||||
leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT];
|
||||
const leftStickRight = new InputSourceButton();
|
||||
leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT];
|
||||
this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight });
|
||||
|
||||
const rightStickUp = new InputSourceButton();
|
||||
rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP];
|
||||
const rightStickDown = new InputSourceButton();
|
||||
rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN];
|
||||
const rightStickLeft = new InputSourceButton();
|
||||
rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT];
|
||||
const rightStickRight = new InputSourceButton();
|
||||
rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT];
|
||||
this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight });
|
||||
|
||||
this._buttonStart = new InputSourceButton();
|
||||
this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START]; // TODO: Rokid only for now
|
||||
|
||||
this._gripLeft = new InputSourceButton();
|
||||
this._gripLeft.getValue = (): number => 0;
|
||||
this._gripRight = new InputSourceButton();
|
||||
this._gripRight.getValue = (): number => 0;
|
||||
|
||||
this._handLeftPosition = new InputSourcePosition();
|
||||
this._handLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._handLeftOrientation = new InputSourceOrientation();
|
||||
this._handLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
this._handRightPosition = new InputSourcePosition();
|
||||
this._handRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._handRightOrientation = new InputSourceOrientation();
|
||||
this._handRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
this._aimLeftPosition = new InputSourcePosition();
|
||||
this._aimLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._aimLeftOrientation = new InputSourceOrientation();
|
||||
this._aimLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
this._aimRightPosition = new InputSourcePosition();
|
||||
this._aimRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._aimRightOrientation = new InputSourceOrientation();
|
||||
this._aimRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHandheld } from '../../../cocos/input/types';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export type HandheldCallback = (res: EventHandheld) => void;
|
||||
|
||||
enum Pose {
|
||||
AR_MOBILE,
|
||||
}
|
||||
|
||||
interface IPoseValue {
|
||||
position: Vec3;
|
||||
orientation: Quat;
|
||||
}
|
||||
|
||||
type NativePoseState = Record<Pose, IPoseValue>
|
||||
|
||||
export class HandheldInputDevice {
|
||||
public get handheldPosition (): InputSourcePosition { return this._handheldPosition; }
|
||||
public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _handheldPosition: InputSourcePosition;
|
||||
private declare _handheldOrientation: InputSourceOrientation;
|
||||
|
||||
private _nativePoseState: NativePoseState = {
|
||||
[Pose.AR_MOBILE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
};
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onHandheldPoseInput = (infoList: jsb.PoseInfo[]): void => {
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
this._updateNativePoseState(info);
|
||||
}
|
||||
|
||||
this._eventTarget.emit(InputEventType.HANDHELD_POSE_INPUT, new EventHandheld(InputEventType.HANDHELD_POSE_INPUT, this));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _updateNativePoseState (info: jsb.PoseInfo): void {
|
||||
switch (info.code) {
|
||||
case 7:
|
||||
this._nativePoseState[Pose.AR_MOBILE] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._handheldPosition = new InputSourcePosition();
|
||||
this._handheldPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AR_MOBILE].position;
|
||||
|
||||
this._handheldOrientation = new InputSourceOrientation();
|
||||
this._handheldOrientation.getValue = (): Quat => this._nativePoseState[Pose.AR_MOBILE].orientation;
|
||||
}
|
||||
}
|
||||
@@ -1,478 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHandle } from '../../../cocos/input/types';
|
||||
import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export type HandleCallback = (res: EventHandle) => void;
|
||||
|
||||
enum Button {
|
||||
BUTTON_EAST,
|
||||
BUTTON_SOUTH,
|
||||
BUTTON_WEST,
|
||||
BUTTON_NORTH,
|
||||
BUTTON_TRIGGER_LEFT,
|
||||
BUTTON_TRIGGER_RIGHT,
|
||||
TRIGGER_LEFT,
|
||||
TRIGGER_RIGHT,
|
||||
GRIP_LEFT,
|
||||
GRIP_RIGHT,
|
||||
BUTTON_LEFT_STICK,
|
||||
LEFT_STICK_UP,
|
||||
LEFT_STICK_DOWN,
|
||||
LEFT_STICK_LEFT,
|
||||
LEFT_STICK_RIGHT,
|
||||
BUTTON_RIGHT_STICK,
|
||||
RIGHT_STICK_UP,
|
||||
RIGHT_STICK_DOWN,
|
||||
RIGHT_STICK_LEFT,
|
||||
RIGHT_STICK_RIGHT,
|
||||
ROKID_MENU,
|
||||
ROKID_START,
|
||||
}
|
||||
|
||||
enum Pose {
|
||||
HAND_LEFT,
|
||||
HAND_RIGHT,
|
||||
AIM_LEFT,
|
||||
AIM_RIGHT,
|
||||
}
|
||||
|
||||
enum StickKeyCode {
|
||||
UNDEFINE = 0,
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
L1,
|
||||
R1,
|
||||
MINUS,
|
||||
PLUS,
|
||||
L3,
|
||||
R3,
|
||||
MENU,
|
||||
START,
|
||||
TRIGGER_LEFT,
|
||||
TRIGGER_RIGHT,
|
||||
}
|
||||
|
||||
enum StickAxisCode {
|
||||
UNDEFINE = 0,
|
||||
X,
|
||||
Y,
|
||||
LEFT_STICK_X,
|
||||
LEFT_STICK_Y,
|
||||
RIGHT_STICK_X,
|
||||
RIGHT_STICK_Y,
|
||||
L2,
|
||||
R2,
|
||||
LEFT_GRIP,
|
||||
RIGHT_GRIP,
|
||||
}
|
||||
|
||||
enum StickTouchCode {
|
||||
UNDEFINE = 0,
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
LEFT_TRIGGER,
|
||||
RIGHT_TRIGGER,
|
||||
LEFT_THUMBSTICK,
|
||||
RIGHT_THUMBSTICK,
|
||||
}
|
||||
|
||||
interface IPoseValue {
|
||||
position: Vec3;
|
||||
orientation: Quat;
|
||||
}
|
||||
|
||||
type NativeButtonState = Record<Button, number>
|
||||
type NativeTouchState = Record<StickTouchCode, number>
|
||||
type NativePoseState = Record<Pose, IPoseValue>
|
||||
|
||||
const _nativeButtonMap = {
|
||||
1: Button.BUTTON_EAST,
|
||||
2: Button.BUTTON_SOUTH,
|
||||
3: Button.BUTTON_NORTH,
|
||||
4: Button.BUTTON_WEST,
|
||||
9: Button.BUTTON_LEFT_STICK,
|
||||
10: Button.BUTTON_RIGHT_STICK,
|
||||
11: Button.ROKID_MENU,
|
||||
12: Button.ROKID_START,
|
||||
13: Button.BUTTON_TRIGGER_LEFT,
|
||||
14: Button.BUTTON_TRIGGER_RIGHT,
|
||||
};
|
||||
|
||||
interface IAxisValue {
|
||||
negative: number;
|
||||
positive: number;
|
||||
}
|
||||
|
||||
export class HandleInputDevice {
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; }
|
||||
public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; }
|
||||
public get triggerLeft (): InputSourceButton { return this._triggerLeft; }
|
||||
public get triggerRight (): InputSourceButton { return this._triggerRight; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; }
|
||||
public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
public get touchButtonA (): InputSourceTouch { return this._touchButtonA; }
|
||||
public get touchButtonB (): InputSourceTouch { return this._touchButtonB; }
|
||||
public get touchButtonX (): InputSourceTouch { return this._touchButtonX; }
|
||||
public get touchButtonY (): InputSourceTouch { return this._touchButtonY; }
|
||||
public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; }
|
||||
public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; }
|
||||
public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; }
|
||||
public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonTriggerLeft: InputSourceButton;
|
||||
private declare _buttonTriggerRight: InputSourceButton;
|
||||
private declare _triggerLeft: InputSourceButton;
|
||||
private declare _triggerRight: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonLeftStick: InputSourceButton;
|
||||
private declare _buttonRightStick: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
private declare _touchButtonA: InputSourceTouch;
|
||||
private declare _touchButtonB: InputSourceTouch;
|
||||
private declare _touchButtonX: InputSourceTouch;
|
||||
private declare _touchButtonY: InputSourceTouch;
|
||||
private declare _touchButtonTriggerLeft: InputSourceTouch;
|
||||
private declare _touchButtonTriggerRight: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickLeft: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickRight: InputSourceTouch;
|
||||
|
||||
private _nativeButtonState: NativeButtonState = {
|
||||
[Button.BUTTON_SOUTH]: 0,
|
||||
[Button.BUTTON_EAST]: 0,
|
||||
[Button.BUTTON_WEST]: 0,
|
||||
[Button.BUTTON_NORTH]: 0,
|
||||
[Button.BUTTON_TRIGGER_LEFT]: 0,
|
||||
[Button.BUTTON_TRIGGER_RIGHT]: 0,
|
||||
[Button.TRIGGER_LEFT]: 0,
|
||||
[Button.TRIGGER_RIGHT]: 0,
|
||||
[Button.GRIP_LEFT]: 0,
|
||||
[Button.GRIP_RIGHT]: 0,
|
||||
[Button.LEFT_STICK_UP]: 0,
|
||||
[Button.LEFT_STICK_DOWN]: 0,
|
||||
[Button.LEFT_STICK_LEFT]: 0,
|
||||
[Button.LEFT_STICK_RIGHT]: 0,
|
||||
[Button.RIGHT_STICK_UP]: 0,
|
||||
[Button.RIGHT_STICK_DOWN]: 0,
|
||||
[Button.RIGHT_STICK_LEFT]: 0,
|
||||
[Button.RIGHT_STICK_RIGHT]: 0,
|
||||
[Button.BUTTON_LEFT_STICK]: 0,
|
||||
[Button.BUTTON_RIGHT_STICK]: 0,
|
||||
[Button.ROKID_MENU]: 0,
|
||||
[Button.ROKID_START]: 0,
|
||||
};
|
||||
|
||||
private _nativeTouchState: NativeTouchState = {
|
||||
[StickTouchCode.UNDEFINE]: 0,
|
||||
[StickTouchCode.A]: 0,
|
||||
[StickTouchCode.B]: 0,
|
||||
[StickTouchCode.X]: 0,
|
||||
[StickTouchCode.Y]: 0,
|
||||
[StickTouchCode.LEFT_TRIGGER]: 0,
|
||||
[StickTouchCode.RIGHT_TRIGGER]: 0,
|
||||
[StickTouchCode.LEFT_THUMBSTICK]: 0,
|
||||
[StickTouchCode.RIGHT_THUMBSTICK]: 0,
|
||||
};
|
||||
|
||||
private _nativePoseState: NativePoseState = {
|
||||
[Pose.HAND_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.HAND_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.AIM_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.AIM_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
};
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onHandleInput = (infoList: jsb.ControllerInfo[]): void => {
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
this._updateNativeButtonState(info);
|
||||
this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, this));
|
||||
}
|
||||
};
|
||||
|
||||
jsb.onHandlePoseInput = (infoList: jsb.PoseInfo[]): void => {
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
this._updateNativePoseState(info);
|
||||
}
|
||||
this._eventTarget.emit(InputEventType.HANDLE_POSE_INPUT, new EventHandle(InputEventType.HANDLE_POSE_INPUT, this));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _axisToButtons (axisValue: number): IAxisValue {
|
||||
const value = Math.abs(axisValue);
|
||||
if (axisValue > 0) {
|
||||
return { negative: 0, positive: value };
|
||||
} else if (axisValue < 0) {
|
||||
return { negative: value, positive: 0 };
|
||||
} else {
|
||||
return { negative: 0, positive: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
private _updateNativeButtonState (info: jsb.ControllerInfo): void {
|
||||
const { buttonInfoList, axisInfoList, touchInfoList } = info;
|
||||
for (let i = 0; i < buttonInfoList.length; ++i) {
|
||||
const buttonInfo = buttonInfoList[i];
|
||||
const button = _nativeButtonMap[buttonInfo.code];
|
||||
this._nativeButtonState[button] = buttonInfo.isPressed ? 1 : 0;
|
||||
}
|
||||
for (let i = 0; i < axisInfoList.length; ++i) {
|
||||
const axisInfo = axisInfoList[i];
|
||||
const { code, value } = axisInfo;
|
||||
let negativeButton: Button | undefined;
|
||||
let positiveButton: Button | undefined;
|
||||
let axisValue: IAxisValue | undefined;
|
||||
switch (code) {
|
||||
case StickAxisCode.LEFT_STICK_X:
|
||||
negativeButton = Button.LEFT_STICK_LEFT;
|
||||
positiveButton = Button.LEFT_STICK_RIGHT;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case StickAxisCode.LEFT_STICK_Y:
|
||||
negativeButton = Button.LEFT_STICK_DOWN;
|
||||
positiveButton = Button.LEFT_STICK_UP;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case StickAxisCode.RIGHT_STICK_X:
|
||||
negativeButton = Button.RIGHT_STICK_LEFT;
|
||||
positiveButton = Button.RIGHT_STICK_RIGHT;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case StickAxisCode.RIGHT_STICK_Y:
|
||||
negativeButton = Button.RIGHT_STICK_DOWN;
|
||||
positiveButton = Button.RIGHT_STICK_UP;
|
||||
axisValue = this._axisToButtons(value);
|
||||
break;
|
||||
case StickAxisCode.L2:
|
||||
this._nativeButtonState[Button.TRIGGER_LEFT] = value;
|
||||
break;
|
||||
case StickAxisCode.R2:
|
||||
this._nativeButtonState[Button.TRIGGER_RIGHT] = value;
|
||||
break;
|
||||
case StickAxisCode.LEFT_GRIP:
|
||||
this._nativeButtonState[Button.GRIP_LEFT] = value;
|
||||
break;
|
||||
case StickAxisCode.RIGHT_GRIP:
|
||||
this._nativeButtonState[Button.GRIP_RIGHT] = value;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (negativeButton && positiveButton && axisValue) {
|
||||
this._nativeButtonState[negativeButton] = axisValue.negative;
|
||||
this._nativeButtonState[positiveButton] = axisValue.positive;
|
||||
}
|
||||
}
|
||||
|
||||
if (touchInfoList) {
|
||||
for (let i = 0; i < touchInfoList.length; ++i) {
|
||||
const touchInfo = touchInfoList[i];
|
||||
const { code, value } = touchInfo;
|
||||
switch (code) {
|
||||
case StickTouchCode.A:
|
||||
case StickTouchCode.B:
|
||||
case StickTouchCode.X:
|
||||
case StickTouchCode.Y:
|
||||
case StickTouchCode.LEFT_TRIGGER:
|
||||
case StickTouchCode.RIGHT_TRIGGER:
|
||||
case StickTouchCode.LEFT_THUMBSTICK:
|
||||
case StickTouchCode.RIGHT_THUMBSTICK:
|
||||
this._nativeTouchState[code] = value;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _updateNativePoseState (info: jsb.PoseInfo): void {
|
||||
switch (info.code) {
|
||||
case 1:
|
||||
this._nativePoseState[Pose.HAND_LEFT] = { position: new Vec3(info.x, info.y, info.z),
|
||||
orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
case 2:
|
||||
this._nativePoseState[Pose.AIM_LEFT] = { position: new Vec3(info.x, info.y, info.z),
|
||||
orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
case 4:
|
||||
this._nativePoseState[Pose.HAND_RIGHT] = { position: new Vec3(info.x, info.y, info.z),
|
||||
orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
case 5:
|
||||
this._nativePoseState[Pose.AIM_RIGHT] = { position: new Vec3(info.x, info.y, info.z),
|
||||
orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._buttonNorth = new InputSourceButton();
|
||||
this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH];
|
||||
this._buttonEast = new InputSourceButton();
|
||||
this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST];
|
||||
this._buttonWest = new InputSourceButton();
|
||||
this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST];
|
||||
this._buttonSouth = new InputSourceButton();
|
||||
this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH];
|
||||
|
||||
this._buttonTriggerLeft = new InputSourceButton();
|
||||
this._buttonTriggerLeft.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT];
|
||||
this._buttonTriggerRight = new InputSourceButton();
|
||||
this._buttonTriggerRight.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT];
|
||||
this._triggerLeft = new InputSourceButton();
|
||||
this._triggerLeft.getValue = (): number => this._nativeButtonState[Button.TRIGGER_LEFT];
|
||||
this._triggerRight = new InputSourceButton();
|
||||
this._triggerRight.getValue = (): number => this._nativeButtonState[Button.TRIGGER_RIGHT];
|
||||
this._gripLeft = new InputSourceButton();
|
||||
this._gripLeft.getValue = (): number => this._nativeButtonState[Button.GRIP_LEFT];
|
||||
this._gripRight = new InputSourceButton();
|
||||
this._gripRight.getValue = (): number => this._nativeButtonState[Button.GRIP_RIGHT];
|
||||
|
||||
this._buttonLeftStick = new InputSourceButton();
|
||||
this._buttonLeftStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_LEFT_STICK];
|
||||
const leftStickUp = new InputSourceButton();
|
||||
leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP];
|
||||
const leftStickDown = new InputSourceButton();
|
||||
leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN];
|
||||
const leftStickLeft = new InputSourceButton();
|
||||
leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT];
|
||||
const leftStickRight = new InputSourceButton();
|
||||
leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT];
|
||||
this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight });
|
||||
|
||||
this._buttonRightStick = new InputSourceButton();
|
||||
this._buttonRightStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_RIGHT_STICK];
|
||||
const rightStickUp = new InputSourceButton();
|
||||
rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP];
|
||||
const rightStickDown = new InputSourceButton();
|
||||
rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN];
|
||||
const rightStickLeft = new InputSourceButton();
|
||||
rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT];
|
||||
const rightStickRight = new InputSourceButton();
|
||||
rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT];
|
||||
this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight });
|
||||
|
||||
this._buttonOptions = new InputSourceButton();
|
||||
this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.ROKID_MENU];
|
||||
this._buttonStart = new InputSourceButton();
|
||||
this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START];
|
||||
|
||||
this._handLeftPosition = new InputSourcePosition();
|
||||
this._handLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.HAND_LEFT].position;
|
||||
this._handLeftOrientation = new InputSourceOrientation();
|
||||
this._handLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.HAND_LEFT].orientation;
|
||||
|
||||
this._handRightPosition = new InputSourcePosition();
|
||||
this._handRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.HAND_RIGHT].position;
|
||||
this._handRightOrientation = new InputSourceOrientation();
|
||||
this._handRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.HAND_RIGHT].orientation;
|
||||
|
||||
this._aimLeftPosition = new InputSourcePosition();
|
||||
this._aimLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AIM_LEFT].position;
|
||||
this._aimLeftOrientation = new InputSourceOrientation();
|
||||
this._aimLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.AIM_LEFT].orientation;
|
||||
|
||||
this._aimRightPosition = new InputSourcePosition();
|
||||
this._aimRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.AIM_RIGHT].position;
|
||||
this._aimRightOrientation = new InputSourceOrientation();
|
||||
this._aimRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.AIM_RIGHT].orientation;
|
||||
this._touchButtonA = new InputSourceTouch();
|
||||
this._touchButtonA.getValue = (): number => this._nativeTouchState[StickTouchCode.A];
|
||||
this._touchButtonB = new InputSourceTouch();
|
||||
this._touchButtonB.getValue = (): number => this._nativeTouchState[StickTouchCode.B];
|
||||
this._touchButtonX = new InputSourceTouch();
|
||||
this._touchButtonX.getValue = (): number => this._nativeTouchState[StickTouchCode.X];
|
||||
this._touchButtonY = new InputSourceTouch();
|
||||
this._touchButtonY.getValue = (): number => this._nativeTouchState[StickTouchCode.Y];
|
||||
this._touchButtonTriggerLeft = new InputSourceTouch();
|
||||
this._touchButtonTriggerLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_TRIGGER];
|
||||
this._touchButtonTriggerRight = new InputSourceTouch();
|
||||
this._touchButtonTriggerRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_TRIGGER];
|
||||
this._touchButtonThumbStickLeft = new InputSourceTouch();
|
||||
this._touchButtonThumbStickLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_THUMBSTICK];
|
||||
this._touchButtonThumbStickRight = new InputSourceTouch();
|
||||
this._touchButtonThumbStickRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_THUMBSTICK];
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHMD } from '../../../cocos/input/types';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export type HMDCallback = (res: EventHMD) => void;
|
||||
|
||||
enum Pose {
|
||||
VIEW_LEFT,
|
||||
VIEW_RIGHT,
|
||||
HEAD_MIDDLE,
|
||||
}
|
||||
|
||||
interface IPoseValue {
|
||||
position: Vec3;
|
||||
orientation: Quat;
|
||||
}
|
||||
|
||||
type NativePoseState = Record<Pose, IPoseValue>
|
||||
|
||||
export class HMDInputDevice {
|
||||
public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; }
|
||||
public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; }
|
||||
public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; }
|
||||
public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; }
|
||||
public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; }
|
||||
public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _viewLeftPosition: InputSourcePosition;
|
||||
private declare _viewLeftOrientation: InputSourceOrientation;
|
||||
private declare _viewRightPosition: InputSourcePosition;
|
||||
private declare _viewRightOrientation: InputSourceOrientation;
|
||||
private declare _headMiddlePosition: InputSourcePosition;
|
||||
private declare _headMiddleOrientation: InputSourceOrientation;
|
||||
|
||||
private _nativePoseState: NativePoseState = {
|
||||
[Pose.VIEW_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.VIEW_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.HEAD_MIDDLE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
};
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onHMDPoseInput = (infoList: jsb.PoseInfo[]): void => {
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
this._updateNativePoseState(info);
|
||||
}
|
||||
this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _updateNativePoseState (info: jsb.PoseInfo): void {
|
||||
switch (info.code) {
|
||||
case 0:
|
||||
this._nativePoseState[Pose.VIEW_LEFT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
case 3:
|
||||
this._nativePoseState[Pose.VIEW_RIGHT] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
case 6:
|
||||
this._nativePoseState[Pose.HEAD_MIDDLE] = { position: new Vec3(info.x, info.y, info.z), orientation: new Quat(info.quaternionX, info.quaternionY, info.quaternionZ, info.quaternionW) };
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._viewLeftPosition = new InputSourcePosition();
|
||||
this._viewLeftPosition.getValue = (): Vec3 => this._nativePoseState[Pose.VIEW_LEFT].position;
|
||||
this._viewLeftOrientation = new InputSourceOrientation();
|
||||
this._viewLeftOrientation.getValue = (): Quat => this._nativePoseState[Pose.VIEW_LEFT].orientation;
|
||||
|
||||
this._viewRightPosition = new InputSourcePosition();
|
||||
this._viewRightPosition.getValue = (): Vec3 => this._nativePoseState[Pose.VIEW_RIGHT].position;
|
||||
this._viewRightOrientation = new InputSourceOrientation();
|
||||
this._viewRightOrientation.getValue = (): Quat => this._nativePoseState[Pose.VIEW_RIGHT].orientation;
|
||||
|
||||
this._headMiddlePosition = new InputSourcePosition();
|
||||
this._headMiddlePosition.getValue = (): Vec3 => this._nativePoseState[Pose.HEAD_MIDDLE].position;
|
||||
this._headMiddleOrientation = new InputSourceOrientation();
|
||||
this._headMiddleOrientation.getValue = (): Quat => this._nativePoseState[Pose.HEAD_MIDDLE].orientation;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
export * from './accelerometer-input';
|
||||
export * from './gamepad-input';
|
||||
export * from './handle-input';
|
||||
export * from './hmd-input';
|
||||
export * from './handheld-input';
|
||||
export * from './keyboard-input';
|
||||
export * from './mouse-input';
|
||||
export * from './touch-input';
|
||||
|
||||
checkPalIntegrity<typeof import('pal/input')>(withImpl<typeof import('./index')>());
|
||||
@@ -1,109 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { KeyCode, EventKeyboard } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { code2KeyCode } from '../keycodes';
|
||||
|
||||
export type KeyboardCallback = (res: EventKeyboard) => void;
|
||||
|
||||
const nativeKeyCode2KeyCode: Record<number, KeyCode> = {
|
||||
12: KeyCode.NUM_LOCK,
|
||||
10048: KeyCode.NUM_0,
|
||||
10049: KeyCode.NUM_1,
|
||||
10050: KeyCode.NUM_2,
|
||||
10051: KeyCode.NUM_3,
|
||||
10052: KeyCode.NUM_4,
|
||||
10053: KeyCode.NUM_5,
|
||||
10054: KeyCode.NUM_6,
|
||||
10055: KeyCode.NUM_7,
|
||||
10056: KeyCode.NUM_8,
|
||||
10057: KeyCode.NUM_9,
|
||||
20013: KeyCode.NUM_ENTER,
|
||||
20016: KeyCode.SHIFT_RIGHT,
|
||||
20017: KeyCode.CTRL_RIGHT,
|
||||
20018: KeyCode.ALT_RIGHT,
|
||||
};
|
||||
|
||||
function getKeyCode (event: jsb.KeyboardEvent): KeyCode {
|
||||
if (event.code) {
|
||||
if (event.code in code2KeyCode) {
|
||||
return code2KeyCode[event.code];
|
||||
} else {
|
||||
console.error(`Can not find keyCode for code: ${event.code}`);
|
||||
}
|
||||
}
|
||||
return nativeKeyCode2KeyCode[event.keyCode] || event.keyCode;
|
||||
}
|
||||
|
||||
export class KeyboardInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
// On native platform, KeyboardEvent.repeat is always false, so we need a map to manage the key state.
|
||||
private _keyStateMap: Record<number, boolean> = {};
|
||||
|
||||
private _handleKeyboardDown: (event: jsb.KeyboardEvent) => void;
|
||||
private _handleKeyboardUp: (event: jsb.KeyboardEvent) => void;
|
||||
|
||||
constructor () {
|
||||
this._handleKeyboardDown = (event: jsb.KeyboardEvent): void => {
|
||||
const keyCode = getKeyCode(event);
|
||||
if (!this._keyStateMap[keyCode]) {
|
||||
const eventKeyDown = this._getInputEvent(event, InputEventType.KEY_DOWN);
|
||||
this._eventTarget.emit(InputEventType.KEY_DOWN, eventKeyDown);
|
||||
} else {
|
||||
const eventKeyPressing = this._getInputEvent(event, InputEventType.KEY_PRESSING);
|
||||
this._eventTarget.emit(InputEventType.KEY_PRESSING, eventKeyPressing);
|
||||
}
|
||||
this._keyStateMap[keyCode] = true;
|
||||
};
|
||||
this._handleKeyboardUp = (event: jsb.KeyboardEvent): void => {
|
||||
const keyCode = getKeyCode(event);
|
||||
const eventKeyUp = this._getInputEvent(event, InputEventType.KEY_UP);
|
||||
this._keyStateMap[keyCode] = false;
|
||||
this._eventTarget.emit(InputEventType.KEY_UP, eventKeyUp);
|
||||
};
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
public dispatchKeyboardDownEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { this._handleKeyboardDown(nativeKeyboardEvent); }
|
||||
public dispatchKeyboardUpEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { this._handleKeyboardUp(nativeKeyboardEvent); }
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onKeyDown = this._handleKeyboardDown;
|
||||
jsb.onKeyUp = this._handleKeyboardUp;
|
||||
}
|
||||
|
||||
private _getInputEvent (event: jsb.KeyboardEvent, eventType: InputEventType): EventKeyboard {
|
||||
const keyCode = getKeyCode(event);
|
||||
const eventKeyboard = new EventKeyboard(keyCode, eventType);
|
||||
eventKeyboard.windowId = event.windowId;
|
||||
return eventKeyboard;
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { EventMouse } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { Vec2 } from '../../../cocos/core/math';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { OS } from '../../system-info/enum-type';
|
||||
|
||||
export type MouseCallback = (res: EventMouse) => void;
|
||||
|
||||
declare const jsb: any;
|
||||
|
||||
class MouseEventElement {
|
||||
type: InputEventType | null = null;
|
||||
mouseEvent = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
xDelta: 0,
|
||||
yDelta: 0,
|
||||
button: 0,
|
||||
windowId: 0,
|
||||
wheelDeltaX: 0,
|
||||
wheelDeltaY: 0,
|
||||
};
|
||||
}
|
||||
|
||||
class MouseEventCache {
|
||||
private _events: MouseEventElement[] = [];
|
||||
private _length = 0;
|
||||
|
||||
push (eventType: InputEventType, mouseEvent?: any): void {
|
||||
const events = this._events;
|
||||
const index = this._length;
|
||||
if (index >= events.length) {
|
||||
events.push(new MouseEventElement());
|
||||
}
|
||||
const e = events[index];
|
||||
e.type = eventType;
|
||||
const cachedEvent = e.mouseEvent;
|
||||
if (mouseEvent) {
|
||||
Object.assign(cachedEvent, mouseEvent);
|
||||
} else {
|
||||
cachedEvent.x = cachedEvent.y = cachedEvent.xDelta = cachedEvent.yDelta = 0;
|
||||
cachedEvent.button = cachedEvent.windowId = cachedEvent.wheelDeltaX = cachedEvent.wheelDeltaY = 0;
|
||||
}
|
||||
|
||||
++this._length;
|
||||
}
|
||||
|
||||
clear (): void {
|
||||
this._length = 0;
|
||||
}
|
||||
|
||||
forEach (cb: ((e: MouseEventElement) => void)): void {
|
||||
for (let i = 0, len = this._length; i < len; ++i) {
|
||||
cb(this._events[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class MouseInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private _preMousePos: Vec2 = new Vec2();
|
||||
private _isPressed = false;
|
||||
private _windowManager: any;
|
||||
private _pointLocked = false;
|
||||
private _cache = new MouseEventCache();
|
||||
|
||||
private _handleMouseDown: (mouseEvent: jsb.MouseEvent) => void;
|
||||
private _handleMouseMove: (mouseEvent: jsb.MouseEvent) => void;
|
||||
private _handleMouseUp: (mouseEvent: jsb.MouseEvent) => void;
|
||||
private _handleWindowLeave: () => void;
|
||||
private _handleWindowEnter: () => void;
|
||||
private _handleMouseWheel: (mouseEvent: jsb.MouseWheelEvent) => void;
|
||||
|
||||
constructor () {
|
||||
this._handleMouseDown = this._createEventCacheCallback(InputEventType.MOUSE_DOWN);
|
||||
this._handleMouseMove = this._createEventCacheCallback(InputEventType.MOUSE_MOVE);
|
||||
this._handleMouseUp = this._createEventCacheCallback(InputEventType.MOUSE_UP);
|
||||
this._handleWindowLeave = this._createEventCacheCallback(InputEventType.MOUSE_LEAVE);
|
||||
this._handleWindowEnter = this._createEventCacheCallback(InputEventType.MOUSE_ENTER);
|
||||
this._handleMouseWheel = this._createEventCacheCallback(InputEventType.MOUSE_WHEEL);
|
||||
this._registerEvent();
|
||||
this._windowManager = jsb.ISystemWindowManager.getInstance();
|
||||
}
|
||||
|
||||
public dispatchMouseDownEvent (nativeMouseEvent: any): void { this._handleMouseDown(nativeMouseEvent as jsb.MouseEvent); }
|
||||
public dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._handleMouseMove(nativeMouseEvent as jsb.MouseEvent); }
|
||||
public dispatchMouseUpEvent (nativeMouseEvent: any): void { this._handleMouseUp(nativeMouseEvent as jsb.MouseEvent); }
|
||||
public dispatchScrollEvent (nativeMouseEvent: any): void { this._handleMouseWheel(nativeMouseEvent as jsb.MouseWheelEvent); }
|
||||
|
||||
private _getLocation (event: jsb.MouseEvent): Vec2 {
|
||||
const window = this._windowManager.getWindow(event.windowId);
|
||||
const windowSize = window.getViewSize();
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
const x = event.x * dpr;
|
||||
const y = windowSize.height - event.y * dpr;
|
||||
return new Vec2(x, y);
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onMouseDown = this._handleMouseDown;
|
||||
jsb.onMouseMove = this._handleMouseMove;
|
||||
jsb.onMouseUp = this._handleMouseUp;
|
||||
jsb.onMouseWheel = this._handleMouseWheel;
|
||||
jsb.onPointerlockChange = (value: boolean): void => {
|
||||
this._pointLocked = value;
|
||||
};
|
||||
|
||||
// Treat window leave/enter events as mouse events as web.
|
||||
jsb.onWindowLeave = this._handleWindowLeave;
|
||||
jsb.onWindowEnter = this._handleWindowEnter;
|
||||
}
|
||||
|
||||
private _createEventCacheCallback (eventType: InputEventType) {
|
||||
return (mouseEvent?: jsb.MouseEvent | jsb.MouseWheelEvent): void => {
|
||||
this._cache.push(eventType, mouseEvent);
|
||||
};
|
||||
}
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
const cache = this._cache;
|
||||
|
||||
cache.forEach((e: MouseEventElement) => {
|
||||
switch (e.type) {
|
||||
case InputEventType.MOUSE_LEAVE:
|
||||
this._dispatchWindowLeave();
|
||||
break;
|
||||
case InputEventType.MOUSE_ENTER:
|
||||
this._dispatchWindowEnter();
|
||||
break;
|
||||
case InputEventType.MOUSE_WHEEL:
|
||||
this._dispatchMouseWheel(e.mouseEvent as jsb.MouseWheelEvent);
|
||||
break;
|
||||
default:
|
||||
this._dispatchEvent(e.type!, e.mouseEvent);
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
private _dispatchEvent (eventType: InputEventType, mouseEvent: jsb.MouseEvent): void {
|
||||
const location = this._getLocation(mouseEvent);
|
||||
let button = mouseEvent.button;
|
||||
switch (eventType) {
|
||||
case InputEventType.MOUSE_DOWN:
|
||||
this._isPressed = true;
|
||||
break;
|
||||
case InputEventType.MOUSE_UP:
|
||||
this._isPressed = false;
|
||||
break;
|
||||
case InputEventType.MOUSE_MOVE:
|
||||
if (!this._isPressed) {
|
||||
button = EventMouse.BUTTON_MISSING;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const eventMouse = new EventMouse(eventType, false, this._preMousePos, mouseEvent.windowId);
|
||||
eventMouse.setLocation(location.x, location.y);
|
||||
eventMouse.setButton(button);
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
eventMouse.movementX = typeof mouseEvent.xDelta === 'undefined' ? 0 : mouseEvent.xDelta * dpr;
|
||||
eventMouse.movementY = typeof mouseEvent.yDelta === 'undefined' ? 0 : mouseEvent.yDelta * dpr;
|
||||
// update previous mouse position.
|
||||
this._preMousePos.set(location.x, location.y);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
|
||||
private _dispatchMouseWheel (mouseEvent: jsb.MouseWheelEvent): void {
|
||||
const eventType = InputEventType.MOUSE_WHEEL;
|
||||
const location = this._getLocation(mouseEvent);
|
||||
const button = mouseEvent.button;
|
||||
|
||||
const eventMouse = new EventMouse(eventType, false, this._preMousePos, mouseEvent.windowId);
|
||||
eventMouse.setLocation(location.x, location.y);
|
||||
eventMouse.setButton(button);
|
||||
eventMouse.movementX = location.x - this._preMousePos.x;
|
||||
eventMouse.movementY = this._preMousePos.y - location.y;
|
||||
|
||||
let matchStandardFactor = 0;
|
||||
if (systemInfo.os === OS.OPENHARMONY) {
|
||||
matchStandardFactor = 5;
|
||||
eventMouse.setScrollData(mouseEvent.wheelDeltaX, mouseEvent.wheelDeltaY * matchStandardFactor);
|
||||
} else {
|
||||
matchStandardFactor = 120;
|
||||
eventMouse.setScrollData(mouseEvent.wheelDeltaX * matchStandardFactor, mouseEvent.wheelDeltaY * matchStandardFactor);
|
||||
}
|
||||
// update previous mouse position.
|
||||
this._preMousePos.set(location.x, location.y);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: MouseCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
// Should include window id if supporting multiple windows.
|
||||
private _dispatchWindowLeave (): void {
|
||||
const eventType = InputEventType.MOUSE_LEAVE;
|
||||
const eventMouse = new EventMouse(eventType, false);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
|
||||
private _dispatchWindowEnter (): void {
|
||||
const eventType = InputEventType.MOUSE_ENTER;
|
||||
const eventMouse = new EventMouse(eventType, false);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { Size, Vec2 } from '../../../cocos/core/math';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { EventTouch, Touch as CCTouch } from '../../../cocos/input/types';
|
||||
import { touchManager } from '../touch-manager';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
|
||||
export type TouchCallback = (res: EventTouch) => void;
|
||||
|
||||
declare const jsb: any;
|
||||
|
||||
class TouchEventElement {
|
||||
type: InputEventType | null = null;
|
||||
changedTouches: Touch[] = [];
|
||||
windowId: number = 0;
|
||||
}
|
||||
|
||||
class TouchEventCache {
|
||||
private _events: TouchEventElement[] = [];
|
||||
private _length = 0;
|
||||
|
||||
push (eventType: InputEventType, changedTouches: Touch[], windowId: number): void {
|
||||
const events = this._events;
|
||||
const index = this._length;
|
||||
if (index >= events.length) {
|
||||
events.push(new TouchEventElement());
|
||||
}
|
||||
const e = events[index];
|
||||
const cachedTouches = e.changedTouches;
|
||||
e.type = eventType;
|
||||
cachedTouches.length = changedTouches.length;
|
||||
e.windowId = windowId;
|
||||
|
||||
for (let i = 0, len = changedTouches.length; i < len; ++i) {
|
||||
const src = changedTouches[i];
|
||||
let dst = cachedTouches[i] as any;
|
||||
if (!dst) {
|
||||
(cachedTouches[i] as any) = dst = {};
|
||||
}
|
||||
Object.assign(dst, src);
|
||||
}
|
||||
|
||||
++this._length;
|
||||
}
|
||||
|
||||
clear (): void {
|
||||
this._length = 0;
|
||||
}
|
||||
|
||||
forEach (cb: ((e: TouchEventElement) => void)): void {
|
||||
for (let i = 0, len = this._length; i < len; ++i) {
|
||||
cb(this._events[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class TouchInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private _windowManager: any;
|
||||
|
||||
private _cache = new TouchEventCache();
|
||||
|
||||
constructor () {
|
||||
this._registerEvent();
|
||||
this._windowManager = jsb.ISystemWindowManager.getInstance();
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onTouchStart = this._createEventCacheCallback(InputEventType.TOUCH_START);
|
||||
jsb.onTouchMove = this._createEventCacheCallback(InputEventType.TOUCH_MOVE);
|
||||
jsb.onTouchEnd = this._createEventCacheCallback(InputEventType.TOUCH_END);
|
||||
jsb.onTouchCancel = this._createEventCacheCallback(InputEventType.TOUCH_CANCEL);
|
||||
}
|
||||
|
||||
private _createEventCacheCallback (eventType: InputEventType) {
|
||||
return (changedTouches: Touch[], windowId: number): void => {
|
||||
this._cache.push(eventType, changedTouches, windowId);
|
||||
};
|
||||
}
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
const cache = this._cache;
|
||||
cache.forEach((e: TouchEventElement) => {
|
||||
this._dispatchEvent(e.type!, e.changedTouches, e.windowId);
|
||||
});
|
||||
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
private _dispatchEvent (eventType: InputEventType, changedTouches: Touch[], windowId: number): void {
|
||||
const handleTouches: CCTouch[] = [];
|
||||
const length = changedTouches.length;
|
||||
const windowSize = this._windowManager.getWindow(windowId).getViewSize() as Size;
|
||||
for (let i = 0; i < length; ++i) {
|
||||
const changedTouch = changedTouches[i];
|
||||
const touchID = changedTouch.identifier;
|
||||
if (touchID === null) {
|
||||
continue;
|
||||
}
|
||||
const location = this._getLocation(changedTouch, windowSize);
|
||||
const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y);
|
||||
if (!touch) {
|
||||
continue;
|
||||
}
|
||||
if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) {
|
||||
touchManager.releaseTouch(touchID);
|
||||
}
|
||||
handleTouches.push(touch);
|
||||
}
|
||||
if (handleTouches.length > 0) {
|
||||
const eventTouch = new EventTouch(
|
||||
handleTouches,
|
||||
false,
|
||||
eventType,
|
||||
touchManager.getAllTouches(),
|
||||
);
|
||||
eventTouch.windowId = windowId;
|
||||
this._eventTarget.emit(eventType, eventTouch);
|
||||
}
|
||||
}
|
||||
|
||||
private _getLocation (touch: globalThis.Touch, windowSize: Size): Vec2 {
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
const x = touch.clientX * dpr;
|
||||
const y = windowSize.height - touch.clientY * dpr;
|
||||
return new Vec2(x, y);
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: TouchCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventAcceleration } from '../../../cocos/input/types';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
|
||||
export type AccelerometerCallback = (res: EventAcceleration) => void;
|
||||
|
||||
export class AccelerometerInputSource {
|
||||
|
||||
constructor () {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public start (): void {
|
||||
|
||||
}
|
||||
public stop (): void {
|
||||
|
||||
}
|
||||
public setInterval (intervalInMileseconds: number): void {
|
||||
|
||||
}
|
||||
public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* eslint-disable brace-style */
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventGamepad } from '../../../cocos/input/types';
|
||||
import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source';
|
||||
|
||||
export type GamepadCallback = (res: EventGamepad) => void;
|
||||
|
||||
export class GamepadInputDevice {
|
||||
public static all: GamepadInputDevice[] = [];
|
||||
public static xr: (GamepadInputDevice | null) = null;
|
||||
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonL1 (): InputSourceButton { return this._buttonL1; }
|
||||
public get buttonL2 (): InputSourceButton { return this._buttonL2; }
|
||||
public get buttonL3 (): InputSourceButton { return this._buttonL3; }
|
||||
public get buttonR1 (): InputSourceButton { return this._buttonR1; }
|
||||
public get buttonR2 (): InputSourceButton { return this._buttonR2; }
|
||||
public get buttonR3 (): InputSourceButton { return this._buttonR3; }
|
||||
// public get buttonTouchPad () { return this._buttonTouchPad; }
|
||||
// public get buttonHome () { return this._buttonHome; }
|
||||
public get buttonShare (): InputSourceButton { return this._buttonShare; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get dpad (): InputSourceDpad { return this._dpad; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
|
||||
public get deviceId (): number {
|
||||
return 0;
|
||||
}
|
||||
public get connected (): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
private static _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonL1: InputSourceButton;
|
||||
private declare _buttonL2: InputSourceButton;
|
||||
private declare _buttonL3: InputSourceButton;
|
||||
private declare _buttonR1: InputSourceButton;
|
||||
private declare _buttonR2: InputSourceButton;
|
||||
private declare _buttonR3: InputSourceButton;
|
||||
// private declare buttonTouchPad: InputSourceButton;
|
||||
// private declare buttonHome: InputSourceButton;
|
||||
private declare _buttonShare: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _dpad: InputSourceDpad;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
|
||||
|
||||
constructor (deviceId: number) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _init (): void {
|
||||
if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) {
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void {
|
||||
GamepadInputDevice._eventTarget.on(eventType, cb, target);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHandheld } from '../../../cocos/input/types';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
export type HandheldCallback = (res: EventHandheld) => void;
|
||||
|
||||
|
||||
export class HandheldInputDevice {
|
||||
public get handheldPosition (): InputSourcePosition { return this._handheldPosition; }
|
||||
public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _handheldPosition: InputSourcePosition;
|
||||
private declare _handheldOrientation: InputSourceOrientation;
|
||||
|
||||
constructor () {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHandle } from '../../../cocos/input/types';
|
||||
import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source';
|
||||
|
||||
export type HandleCallback = (res: EventHandle) => void;
|
||||
|
||||
|
||||
export class HandleInputDevice {
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; }
|
||||
public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; }
|
||||
public get triggerLeft (): InputSourceButton { return this._triggerLeft; }
|
||||
public get triggerRight (): InputSourceButton { return this._triggerRight; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; }
|
||||
public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
public get touchButtonA (): InputSourceTouch { return this._touchButtonA; }
|
||||
public get touchButtonB (): InputSourceTouch { return this._touchButtonB; }
|
||||
public get touchButtonX (): InputSourceTouch { return this._touchButtonX; }
|
||||
public get touchButtonY (): InputSourceTouch { return this._touchButtonY; }
|
||||
public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; }
|
||||
public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; }
|
||||
public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; }
|
||||
public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonTriggerLeft: InputSourceButton;
|
||||
private declare _buttonTriggerRight: InputSourceButton;
|
||||
private declare _triggerLeft: InputSourceButton;
|
||||
private declare _triggerRight: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonLeftStick: InputSourceButton;
|
||||
private declare _buttonRightStick: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
private declare _touchButtonA: InputSourceTouch;
|
||||
private declare _touchButtonB: InputSourceTouch;
|
||||
private declare _touchButtonX: InputSourceTouch;
|
||||
private declare _touchButtonY: InputSourceTouch;
|
||||
private declare _touchButtonTriggerLeft: InputSourceTouch;
|
||||
private declare _touchButtonTriggerRight: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickLeft: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickRight: InputSourceTouch;
|
||||
|
||||
constructor () {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHMD } from '../../../cocos/input/types';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export type HMDCallback = (res: EventHMD) => void;
|
||||
|
||||
enum Pose {
|
||||
VIEW_LEFT,
|
||||
VIEW_RIGHT,
|
||||
HEAD_MIDDLE,
|
||||
}
|
||||
|
||||
interface IPoseValue {
|
||||
position: Vec3;
|
||||
orientation: Quat;
|
||||
}
|
||||
|
||||
export class HMDInputDevice {
|
||||
public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; }
|
||||
public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; }
|
||||
public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; }
|
||||
public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; }
|
||||
public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; }
|
||||
public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _viewLeftPosition: InputSourcePosition;
|
||||
private declare _viewLeftOrientation: InputSourceOrientation;
|
||||
private declare _viewRightPosition: InputSourcePosition;
|
||||
private declare _viewRightOrientation: InputSourceOrientation;
|
||||
private declare _headMiddlePosition: InputSourcePosition;
|
||||
private declare _headMiddleOrientation: InputSourceOrientation;
|
||||
|
||||
constructor () {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
export * from './accelerometer-input';
|
||||
export * from './gamepad-input';
|
||||
export * from './handle-input';
|
||||
export * from './hmd-input';
|
||||
export * from './handheld-input';
|
||||
export * from './keyboard-input';
|
||||
export * from './mouse-input';
|
||||
export * from './touch-input';
|
||||
|
||||
checkPalIntegrity<typeof import('pal/input')>(withImpl<typeof import('./index')>());
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventKeyboard } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
|
||||
|
||||
export type KeyboardCallback = (res: EventKeyboard) => void;
|
||||
|
||||
|
||||
export class KeyboardInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
constructor () {
|
||||
|
||||
}
|
||||
|
||||
public dispatchKeyboardDownEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { }
|
||||
public dispatchKeyboardUpEvent (nativeKeyboardEvent: jsb.KeyboardEvent): void { }
|
||||
|
||||
|
||||
public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventMouse } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
|
||||
export type MouseCallback = (res: EventMouse) => void;
|
||||
|
||||
export class MouseInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
constructor () {
|
||||
|
||||
}
|
||||
|
||||
public dispatchMouseDownEvent (nativeMouseEvent: any): void { }
|
||||
public dispatchMouseMoveEvent (nativeMouseEvent: any): void { }
|
||||
public dispatchMouseUpEvent (nativeMouseEvent: any): void { }
|
||||
public dispatchScrollEvent (nativeMouseEvent: any): void { }
|
||||
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public on (eventType: InputEventType, callback: MouseCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { EventTouch, Touch as CCTouch } from '../../../cocos/input/types';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
|
||||
export type TouchCallback = (res: EventTouch) => void;
|
||||
|
||||
export class TouchInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
constructor () {
|
||||
}
|
||||
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: TouchCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { Vec2 } from '../../cocos/core/math/vec2';
|
||||
import { logID } from '../../cocos/core/platform/debug';
|
||||
import { macro } from '../../cocos/core/platform/macro';
|
||||
import { Touch } from '../../cocos/input/types';
|
||||
|
||||
const tempVec2 = new Vec2();
|
||||
|
||||
class TouchManager {
|
||||
/**
|
||||
* A map from touch ID to touch object.
|
||||
*/
|
||||
private _touchMap: Map<number, Touch> = new Map();
|
||||
private readonly _maxTouches = 8;
|
||||
|
||||
constructor () {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the touch object at the touch start event callback.
|
||||
* we have some policy to create the touch object:
|
||||
* - If the number of touches doesn't exceed the max count, we create a touch object.
|
||||
* - If the number of touches exceeds the max count, we discard the timeout touch to create a new one.
|
||||
* - If the number of touches exceeds the max count and there is no timeout touch, we can't create any touch object.
|
||||
* @param touchID The touch identifier
|
||||
* @param x The x-axis coordinate of the current touch point.
|
||||
* @param y The y-axis coordinate of the current touch point.
|
||||
* @return The Touch instance or undefined.
|
||||
*/
|
||||
private _createTouch (touchID: number, x: number, y: number): Touch | undefined {
|
||||
if (this._touchMap.has(touchID)) {
|
||||
logID(2301);
|
||||
return undefined;
|
||||
}
|
||||
const checkResult = this._checkTouchMapSizeMoreThanMax(touchID);
|
||||
if (checkResult) {
|
||||
logID(2300);
|
||||
return undefined;
|
||||
}
|
||||
const touch = new Touch(x, y, touchID);
|
||||
this._touchMap.set(touchID, touch);
|
||||
this._updateTouch(touch, x, y);
|
||||
return touch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the touch object at the touch end or touch cancel event callback.
|
||||
* @param touchID
|
||||
* @returns
|
||||
*/
|
||||
public releaseTouch (touchID: number): void {
|
||||
if (!this._touchMap.has(touchID)) {
|
||||
return;
|
||||
}
|
||||
this._touchMap.delete(touchID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get touch object by touch ID.
|
||||
* @param touchID
|
||||
* @returns
|
||||
*/
|
||||
public getTouch (touchID: number): Touch | undefined {
|
||||
return this._touchMap.get(touchID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create touch object by touch ID.
|
||||
* @param touchID
|
||||
* @returns
|
||||
*/
|
||||
public getOrCreateTouch (touchID: number, x: number, y: number): Touch | undefined {
|
||||
let touch = this.getTouch(touchID);
|
||||
if (!touch) {
|
||||
touch = this._createTouch(touchID, x, y);
|
||||
} else {
|
||||
this._updateTouch(touch, x, y);
|
||||
}
|
||||
return touch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the current touches objects.
|
||||
* @returns
|
||||
*/
|
||||
public getAllTouches (): Touch[] {
|
||||
const touches: Touch[] = [];
|
||||
this._touchMap.forEach((touch) => {
|
||||
if (touch) {
|
||||
touches.push(touch);
|
||||
}
|
||||
});
|
||||
return touches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of touches.
|
||||
*/
|
||||
public getTouchCount (): number {
|
||||
return this._touchMap.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the location and previous location of current touch ID.
|
||||
* @param touchID
|
||||
* @param x The current location X
|
||||
* @param y The current location Y
|
||||
*/
|
||||
private _updateTouch (touch: Touch, x: number, y: number): void {
|
||||
touch.getLocation(tempVec2);
|
||||
touch.setPrevPoint(tempVec2);
|
||||
touch.setPoint(x, y);
|
||||
}
|
||||
|
||||
private _checkTouchMapSizeMoreThanMax (touchID: number): boolean {
|
||||
if (this._touchMap.has(touchID)) {
|
||||
return false;
|
||||
}
|
||||
const maxSize = macro.ENABLE_MULTI_TOUCH ? this._maxTouches : 1;
|
||||
if (this._touchMap.size < maxSize) {
|
||||
return false;
|
||||
}
|
||||
// Handle when exceed the max number of touches
|
||||
const now = performance.now();
|
||||
this._touchMap.forEach((touch) => {
|
||||
if (now - touch.lastModified > macro.TOUCH_TIMEOUT) {
|
||||
logID(2302, touch.getID());
|
||||
// TODO: need to handle touch cancel event when exceed the max number of touches ?
|
||||
this.releaseTouch(touch.getID());
|
||||
}
|
||||
});
|
||||
return maxSize >= this._touchMap.size;
|
||||
}
|
||||
}
|
||||
|
||||
export const touchManager = new TouchManager();
|
||||
@@ -1,145 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { AccelerometerCallback } from 'pal/input';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { BrowserType, OS } from '../../system-info/enum-type';
|
||||
import { EventAcceleration, Acceleration } from '../../../cocos/input/types';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { warn } from '../../../cocos/core/platform/debug';
|
||||
|
||||
export class AccelerometerInputSource {
|
||||
private _intervalInMileSeconds = 200;
|
||||
private _accelTimer = 0;
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private declare _deviceEventName: 'devicemotion' |'deviceorientation';
|
||||
private declare _globalEventClass: typeof window.DeviceMotionEvent | typeof window.DeviceOrientationEvent;
|
||||
private declare _didAccelerateFunc: (event: DeviceMotionEvent | DeviceOrientationEvent) => void;
|
||||
|
||||
constructor () {
|
||||
// init event name
|
||||
this._globalEventClass = window.DeviceMotionEvent || window.DeviceOrientationEvent;
|
||||
// TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below.
|
||||
if (systemInfo.browserType === BrowserType.MOBILE_QQ) {
|
||||
this._globalEventClass = window.DeviceOrientationEvent;
|
||||
}
|
||||
this._deviceEventName = this._globalEventClass === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation';
|
||||
this._didAccelerateFunc = this._didAccelerate.bind(this);
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
this._accelTimer = performance.now();
|
||||
window.addEventListener(this._deviceEventName, this._didAccelerateFunc, false);
|
||||
}
|
||||
|
||||
private _unregisterEvent (): void {
|
||||
this._accelTimer = 0;
|
||||
window.removeEventListener(this._deviceEventName, this._didAccelerateFunc, false);
|
||||
}
|
||||
|
||||
private _didAccelerate (event: DeviceMotionEvent | DeviceOrientationEvent): void {
|
||||
const now = performance.now();
|
||||
if (now - this._accelTimer < this._intervalInMileSeconds) {
|
||||
return;
|
||||
}
|
||||
this._accelTimer = now;
|
||||
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
let z = 0;
|
||||
if (this._globalEventClass === window.DeviceMotionEvent) {
|
||||
const deviceMotionEvent = event as DeviceMotionEvent;
|
||||
const eventAcceleration = deviceMotionEvent.accelerationIncludingGravity;
|
||||
x = (eventAcceleration?.x || 0) * 0.1;
|
||||
y = (eventAcceleration?.y || 0) * 0.1;
|
||||
z = (eventAcceleration?.z || 0) * 0.1;
|
||||
} else {
|
||||
const deviceOrientationEvent = event as DeviceOrientationEvent;
|
||||
x = ((deviceOrientationEvent.gamma || 0) / 90) * 0.981;
|
||||
y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981;
|
||||
z = ((deviceOrientationEvent.alpha || 0) / 90) * 0.981;
|
||||
}
|
||||
|
||||
if (screenAdapter.isFrameRotated) {
|
||||
const tmp = x;
|
||||
x = -y;
|
||||
y = tmp;
|
||||
}
|
||||
|
||||
// TODO: window.orientation is deprecated: https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation
|
||||
// try to use experimental screen.orientation: https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation
|
||||
const PORTRAIT = 0;
|
||||
const LANDSCAPE_LEFT = -90;
|
||||
const PORTRAIT_UPSIDE_DOWN = 180;
|
||||
const LANDSCAPE_RIGHT = 90;
|
||||
const tmpX = x;
|
||||
if (window.orientation === LANDSCAPE_RIGHT) {
|
||||
x = -y;
|
||||
y = tmpX;
|
||||
} else if (window.orientation === LANDSCAPE_LEFT) {
|
||||
x = y;
|
||||
y = -tmpX;
|
||||
} else if (window.orientation === PORTRAIT_UPSIDE_DOWN) {
|
||||
x = -x;
|
||||
y = -y;
|
||||
}
|
||||
|
||||
// fix android acc values are opposite
|
||||
if (systemInfo.os === OS.ANDROID
|
||||
&& systemInfo.browserType !== BrowserType.MOBILE_QQ) {
|
||||
x = -x;
|
||||
y = -y;
|
||||
}
|
||||
const timestamp = performance.now();
|
||||
const acceleration = new Acceleration(x, y, z, timestamp);
|
||||
const eventAcceleration = new EventAcceleration(acceleration);
|
||||
this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration);
|
||||
}
|
||||
|
||||
public start (): void {
|
||||
// for iOS 13+, safari
|
||||
// NOTE: since TS 4.4, `requestPermission` is not defined in class DeviceMotionEvent in `lib.dom.d.ts`, this should be a breaking change in TS.
|
||||
// Accessing the `requestPermission` would emit a type error, so we assert `DeviceMotionEvent` as any type to skip the TS type checking.
|
||||
if (window.DeviceMotionEvent && typeof (DeviceMotionEvent as any).requestPermission === 'function') {
|
||||
(DeviceMotionEvent as any).requestPermission().then((response) => {
|
||||
if (response === 'granted') {
|
||||
this._registerEvent();
|
||||
}
|
||||
}).catch((e) => { warn(e); });
|
||||
} else {
|
||||
this._registerEvent();
|
||||
}
|
||||
}
|
||||
public stop (): void {
|
||||
this._unregisterEvent();
|
||||
}
|
||||
public setInterval (intervalInMileSeconds: number): void {
|
||||
this._intervalInMileSeconds = intervalInMileSeconds;
|
||||
}
|
||||
public on (eventType: InputEventType, callback: AccelerometerCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
}
|
||||
@@ -1,899 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { GamepadCallback } from 'pal/input';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { USE_XR } from 'internal:constants';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import legacyCC from '../../../predefine';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
import { InputSourceButton, InputSourceDpad, InputSourceOrientation, InputSourcePosition, InputSourceStick } from '../input-source';
|
||||
import { Quat, Vec3, js } from '../../../cocos/core';
|
||||
import { EventGamepad } from '../../../cocos/input/types';
|
||||
|
||||
//#region button index alias
|
||||
const BUTTON_SOUTH = 0;
|
||||
const BUTTON_EAST = 1;
|
||||
const BUTTON_WEST = 2;
|
||||
const BUTTON_NORTH = 3;
|
||||
const BUTTON_L1 = 4;
|
||||
const BUTTON_R1 = 5;
|
||||
const BUTTON_L2 = 6;
|
||||
const BUTTON_R2 = 7;
|
||||
const BUTTON_SHARE = 8;
|
||||
const BUTTON_OPTIONS = 9;
|
||||
const BUTTON_L3 = 10;
|
||||
const BUTTON_R3 = 11;
|
||||
const BUTTON_DPAD_UP = 12;
|
||||
const BUTTON_DPAD_DOWN = 13;
|
||||
const BUTTON_DPAD_LEFT = 14;
|
||||
const BUTTON_DPAD_RIGHT = 15;
|
||||
const BUTTON_HOME = 16;
|
||||
const BUTTON_TOUCH_PAD = 17;
|
||||
const AXIS_LEFT_STICK_X = 0;
|
||||
const AXIS_LEFT_STICK_Y = 1;
|
||||
const AXIS_RIGHT_STICK_X = 2;
|
||||
const AXIS_RIGHT_STICK_Y = 3;
|
||||
const XR_TRIGGER = 0;
|
||||
const XR_GRIP = 1;
|
||||
const XR_TOUCHPAD = 2;
|
||||
const XR_STICK = 3;
|
||||
const XR_BUTTON_1 = 4;
|
||||
const XR_BUTTON_2 = 5;
|
||||
const XR_AXIS_TOUCHPAD_X = 0;
|
||||
const XR_AXIS_TOUCHPAD_Y = 1;
|
||||
const XR_AXIS_STICK_X = 2;
|
||||
const XR_AXIS_STICK_Y = 3;
|
||||
//#endregion button index alias
|
||||
|
||||
const EPSILON = 0.01;
|
||||
type WebGamepad = Gamepad;
|
||||
const XRLeftHandedness = 'left';
|
||||
const XRRightHandedness = 'right';
|
||||
|
||||
const devicesTmp: GamepadInputDevice[] = [];
|
||||
|
||||
enum Pose {
|
||||
HAND_LEFT = 1,
|
||||
HAND_RIGHT = 4,
|
||||
AIM_LEFT = 2,
|
||||
AIM_RIGHT = 5,
|
||||
}
|
||||
|
||||
interface IPoseValue {
|
||||
position: Vec3;
|
||||
orientation: Quat;
|
||||
}
|
||||
|
||||
interface IPoseInfo {
|
||||
readonly code: Pose;
|
||||
readonly position: DOMPointReadOnly;
|
||||
readonly orientation: DOMPointReadOnly;
|
||||
}
|
||||
|
||||
type WebPoseState = Record<Pose, IPoseValue>
|
||||
|
||||
interface IAxisValue {
|
||||
negative: number;
|
||||
positive: number;
|
||||
}
|
||||
|
||||
interface IGamepadCacheInfo {
|
||||
buttons: Array<number>;
|
||||
axes: Array<number>;
|
||||
}
|
||||
|
||||
export class GamepadInputDevice {
|
||||
public static all: GamepadInputDevice[] = [];
|
||||
public static xr: (GamepadInputDevice | null) = null;
|
||||
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonL1 (): InputSourceButton { return this._buttonL1; }
|
||||
public get buttonL2 (): InputSourceButton { return this._buttonL2; }
|
||||
public get buttonL3 (): InputSourceButton { return this._buttonL3; }
|
||||
public get buttonR1 (): InputSourceButton { return this._buttonR1; }
|
||||
public get buttonR2 (): InputSourceButton { return this._buttonR2; }
|
||||
public get buttonR3 (): InputSourceButton { return this._buttonR3; }
|
||||
// public get buttonTouchPad () { return this._buttonTouchPad; }
|
||||
// public get buttonHome () { return this._buttonHome; }
|
||||
public get buttonShare (): InputSourceButton { return this._buttonShare; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get dpad (): InputSourceDpad { return this._dpad; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
|
||||
public get deviceId (): number {
|
||||
return this._deviceId;
|
||||
}
|
||||
public get connected (): boolean {
|
||||
return this._connected;
|
||||
}
|
||||
|
||||
private static _eventTarget: EventTarget = new EventTarget();
|
||||
private static _cachedWebGamepads: (WebGamepad | null)[] = [];
|
||||
private static _cachedWebXRGamepadMap: (Map<string, IGamepadCacheInfo | undefined> | null) = null;
|
||||
private static _intervalId = -1;
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonL1: InputSourceButton;
|
||||
private declare _buttonL2: InputSourceButton;
|
||||
private declare _buttonL3: InputSourceButton;
|
||||
private declare _buttonR1: InputSourceButton;
|
||||
private declare _buttonR2: InputSourceButton;
|
||||
private declare _buttonR3: InputSourceButton;
|
||||
// private declare buttonTouchPad: InputSourceButton;
|
||||
// private declare buttonHome: InputSourceButton;
|
||||
private declare _buttonShare: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _dpad: InputSourceDpad;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
|
||||
private _deviceId = -1;
|
||||
private _connected = false;
|
||||
|
||||
private _webPoseState: WebPoseState = {
|
||||
[Pose.HAND_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.HAND_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.AIM_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.AIM_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
};
|
||||
|
||||
constructor (deviceId: number) {
|
||||
this._deviceId = deviceId;
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _init (): void {
|
||||
if (!systemInfo.hasFeature(Feature.EVENT_GAMEPAD)) {
|
||||
return;
|
||||
}
|
||||
GamepadInputDevice._registerEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public static _on (eventType: InputEventType, cb: GamepadCallback, target?: any): void {
|
||||
GamepadInputDevice._eventTarget.on(eventType, cb, target);
|
||||
}
|
||||
|
||||
private static _removeInputDevice (id: number): void {
|
||||
const removeIndex = GamepadInputDevice.all.findIndex((device) => device.deviceId === id);
|
||||
if (removeIndex === -1) {
|
||||
return;
|
||||
}
|
||||
js.array.fastRemoveAt(GamepadInputDevice.all, removeIndex);
|
||||
}
|
||||
private static _getOrCreateInputDevice (id: number, connected: boolean): GamepadInputDevice {
|
||||
let device = GamepadInputDevice.all.find((device) => device.deviceId === id);
|
||||
if (!device) {
|
||||
device = new GamepadInputDevice(id);
|
||||
GamepadInputDevice.all.push(device);
|
||||
}
|
||||
device._connected = connected;
|
||||
return device;
|
||||
}
|
||||
|
||||
private static _ensureDirectorDefined (callback: () => void): void {
|
||||
GamepadInputDevice._intervalId = setInterval(() => {
|
||||
if (legacyCC.director && legacyCC.Director) {
|
||||
clearInterval(GamepadInputDevice._intervalId);
|
||||
GamepadInputDevice._intervalId = -1;
|
||||
callback();
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
|
||||
private static _totalGamepadCnt = 0;
|
||||
private static _updateGamepadCnt (): void {
|
||||
let cnt = 0;
|
||||
for (let i = 0, l = GamepadInputDevice._cachedWebGamepads.length; i < l; i++) {
|
||||
if (GamepadInputDevice._cachedWebGamepads[i]) cnt++;
|
||||
}
|
||||
GamepadInputDevice._totalGamepadCnt = cnt;
|
||||
}
|
||||
|
||||
private static _registerEvent (): void {
|
||||
GamepadInputDevice._ensureDirectorDefined(() => {
|
||||
GamepadInputDevice._cachedWebGamepads = GamepadInputDevice._getWebGamePads();
|
||||
GamepadInputDevice._updateGamepadCnt();
|
||||
legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads);
|
||||
});
|
||||
window.addEventListener('gamepadconnected', (e) => {
|
||||
GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = e.gamepad;
|
||||
GamepadInputDevice._updateGamepadCnt();
|
||||
const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, true);
|
||||
GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
|
||||
});
|
||||
window.addEventListener('gamepaddisconnected', (e) => {
|
||||
GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = null;
|
||||
GamepadInputDevice._updateGamepadCnt();
|
||||
const device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, false);
|
||||
GamepadInputDevice._removeInputDevice(e.gamepad.index);
|
||||
GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
|
||||
});
|
||||
}
|
||||
|
||||
private static _scanWebGamepads (devices: GamepadInputDevice[]): void {
|
||||
const allDisconnected = GamepadInputDevice._totalGamepadCnt === 0;
|
||||
if (allDisconnected) return;
|
||||
|
||||
const webGamepads = GamepadInputDevice._getWebGamePads();
|
||||
if (!webGamepads) {
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < webGamepads.length; ++i) {
|
||||
const webGamepad = webGamepads[i];
|
||||
if (!webGamepad) {
|
||||
continue;
|
||||
}
|
||||
const cachedWebGamepad = GamepadInputDevice._cachedWebGamepads[webGamepad.index];
|
||||
// TODO: what if cachedWebGamepad is null
|
||||
if (cachedWebGamepad) {
|
||||
let device: GamepadInputDevice | undefined;
|
||||
const cachedButtons = cachedWebGamepad.buttons;
|
||||
for (let j = 0; j < cachedButtons.length; ++j) {
|
||||
const cachedButton = cachedButtons[j];
|
||||
const button = webGamepad.buttons[j];
|
||||
if (Math.abs(cachedButton.value - button.value) > EPSILON) {
|
||||
device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (device) {
|
||||
devices.push(device);
|
||||
continue;
|
||||
}
|
||||
|
||||
const cachedAxes = cachedWebGamepad.axes;
|
||||
for (let j = 0; j < cachedAxes.length; ++j) {
|
||||
const cachedAxisValue = cachedAxes[j];
|
||||
const axisValue = webGamepad.axes[j];
|
||||
if (Math.abs(cachedAxisValue - axisValue) > EPSILON) {
|
||||
device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (device) {
|
||||
devices.push(device);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// update cache
|
||||
GamepadInputDevice._cachedWebGamepads = webGamepads;
|
||||
}
|
||||
|
||||
private static _scanGamepads (): void {
|
||||
devicesTmp.length = 0;
|
||||
GamepadInputDevice._scanWebGamepads(devicesTmp);
|
||||
GamepadInputDevice._scanWebXRGamepads(devicesTmp);
|
||||
// emit event
|
||||
for (let i = 0; i < devicesTmp.length; ++i) {
|
||||
const device = devicesTmp[i];
|
||||
GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device));
|
||||
}
|
||||
GamepadInputDevice._scanWebXRGamepadsPose();
|
||||
}
|
||||
|
||||
private static _scanWebXRGamepads (devices: GamepadInputDevice[]): void {
|
||||
if (!USE_XR) return;
|
||||
const webxrGamepadMap = GamepadInputDevice._getWebXRGamepadMap();
|
||||
if (!webxrGamepadMap) {
|
||||
// update cache
|
||||
GamepadInputDevice._cachedWebXRGamepadMap = null;
|
||||
if (GamepadInputDevice.xr && GamepadInputDevice.xr._connected) {
|
||||
GamepadInputDevice.xr._connected = false;
|
||||
GamepadInputDevice._eventTarget.emit(
|
||||
InputEventType.GAMEPAD_CHANGE,
|
||||
new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr),
|
||||
);
|
||||
devices.push(GamepadInputDevice.xr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!GamepadInputDevice.xr) {
|
||||
// webxr gamepads index is -1 https://www.w3.org/TR/webxr-gamepads-module-1/#navigator-differences
|
||||
GamepadInputDevice.xr = new GamepadInputDevice(-1);
|
||||
}
|
||||
|
||||
const left = webxrGamepadMap.get(XRLeftHandedness);
|
||||
const right = webxrGamepadMap.get(XRRightHandedness);
|
||||
if (!left && !right) {
|
||||
if (GamepadInputDevice.xr._connected) {
|
||||
GamepadInputDevice.xr._connected = false;
|
||||
GamepadInputDevice._eventTarget.emit(
|
||||
InputEventType.GAMEPAD_CHANGE,
|
||||
new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr),
|
||||
);
|
||||
}
|
||||
} else if (!GamepadInputDevice.xr._connected) {
|
||||
GamepadInputDevice.xr._connected = true;
|
||||
GamepadInputDevice._eventTarget.emit(
|
||||
InputEventType.GAMEPAD_CHANGE,
|
||||
new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr),
|
||||
);
|
||||
}
|
||||
|
||||
if (GamepadInputDevice.checkGamepadChanged(
|
||||
left,
|
||||
GamepadInputDevice._cachedWebXRGamepadMap?.get(XRLeftHandedness),
|
||||
)) {
|
||||
devices.push(GamepadInputDevice.xr);
|
||||
} else if (GamepadInputDevice.checkGamepadChanged(
|
||||
right,
|
||||
GamepadInputDevice._cachedWebXRGamepadMap?.get(XRRightHandedness),
|
||||
)) {
|
||||
devices.push(GamepadInputDevice.xr);
|
||||
}
|
||||
|
||||
// update cache
|
||||
if (!GamepadInputDevice._cachedWebXRGamepadMap) {
|
||||
GamepadInputDevice._cachedWebXRGamepadMap = new Map<string, IGamepadCacheInfo | undefined>();
|
||||
}
|
||||
|
||||
GamepadInputDevice._cachedWebXRGamepadMap.set(XRLeftHandedness, GamepadInputDevice._copyCacheGamepadValue(left));
|
||||
GamepadInputDevice._cachedWebXRGamepadMap.set(XRRightHandedness, GamepadInputDevice._copyCacheGamepadValue(right));
|
||||
}
|
||||
|
||||
private static checkGamepadChanged (currGamepad: (Gamepad | undefined), cachedGamepad: (IGamepadCacheInfo | undefined)): boolean {
|
||||
if (!currGamepad && !cachedGamepad) {
|
||||
return false;
|
||||
} else if (!currGamepad || !cachedGamepad) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const cachedButtons = cachedGamepad.buttons;
|
||||
for (let j = 0; j < cachedButtons.length; ++j) {
|
||||
const cachedButton = cachedButtons[j];
|
||||
const button = currGamepad.buttons[j];
|
||||
if (button.value !== 0 || cachedButton !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const cachedAxes = cachedGamepad.axes;
|
||||
for (let j = 0; j < cachedAxes.length; ++j) {
|
||||
const cachedAxisValue = cachedAxes[j];
|
||||
const axisValue = currGamepad.axes[j];
|
||||
if (axisValue !== 0 || cachedAxisValue !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static _copyCacheGamepadValue (gamepad: Gamepad | undefined): IGamepadCacheInfo | undefined {
|
||||
if (!gamepad) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const cacheGamepad: IGamepadCacheInfo = { buttons: new Array(gamepad.buttons.length), axes: new Array(gamepad.axes.length) };
|
||||
for (let j = 0; j < gamepad.buttons.length; ++j) {
|
||||
cacheGamepad.buttons[j] = gamepad.buttons[j].value;
|
||||
}
|
||||
for (let j = 0; j < gamepad.axes.length; ++j) {
|
||||
cacheGamepad.axes[j] = gamepad.axes[j];
|
||||
}
|
||||
|
||||
return cacheGamepad;
|
||||
}
|
||||
|
||||
private static _scanWebXRGamepadsPose (): void {
|
||||
if (!USE_XR) return;
|
||||
const infoList = globalThis.__globalXR?.webxrHandlePoseInfos as IPoseInfo[];
|
||||
if (!infoList || !GamepadInputDevice.xr) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
GamepadInputDevice.xr._updateWebPoseState(info);
|
||||
}
|
||||
GamepadInputDevice._eventTarget.emit(
|
||||
InputEventType.HANDLE_POSE_INPUT,
|
||||
new EventGamepad(InputEventType.HANDLE_POSE_INPUT, GamepadInputDevice.xr),
|
||||
);
|
||||
}
|
||||
|
||||
private static _getWebXRGamepadMap (): (Map<string, Gamepad> | undefined) {
|
||||
return globalThis.__globalXR?.webxrGamepadMap as Map<string, Gamepad>;
|
||||
}
|
||||
|
||||
private static _getWebGamePads (): (WebGamepad | null)[] {
|
||||
if (typeof navigator.getGamepads === 'function') {
|
||||
return navigator.getGamepads();
|
||||
} else if (typeof (navigator as any).webkitGetGamepads === 'function') {
|
||||
// NOTE: 'webkitGetGamepads' is not a standard web interface
|
||||
return (navigator as any).webkitGetGamepads() as (Gamepad | null)[];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private static _getWebGamepad (deviceId: number): WebGamepad | undefined {
|
||||
const webGamepads = GamepadInputDevice._getWebGamePads();
|
||||
for (let i = 0; i < webGamepads.length; ++i) {
|
||||
const webGamepad = webGamepads[i];
|
||||
if (webGamepad && webGamepad.index === deviceId) {
|
||||
return webGamepad;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private _axisToButtons (axisValue: number): IAxisValue {
|
||||
const value = Math.abs(axisValue);
|
||||
if (axisValue > 0) {
|
||||
return { negative: 0, positive: value };
|
||||
} else if (axisValue < 0) {
|
||||
return { negative: value, positive: 0 };
|
||||
} else {
|
||||
return { negative: 0, positive: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
private _updateWebPoseState (info: IPoseInfo): void {
|
||||
if (info.code !== Pose.HAND_LEFT && info.code !== Pose.AIM_LEFT
|
||||
&& info.code !== Pose.HAND_RIGHT && info.code !== Pose.AIM_RIGHT) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._webPoseState[info.code] = {
|
||||
position: new Vec3(info.position.x, info.position.y, info.position.z),
|
||||
orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w),
|
||||
};
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._buttonNorth = new InputSourceButton();
|
||||
this._buttonNorth.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) {
|
||||
return webxrGamepad.buttons[XR_BUTTON_2].value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_NORTH].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonEast = new InputSourceButton();
|
||||
this._buttonEast.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) {
|
||||
return webxrGamepad.buttons[XR_BUTTON_2].value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_EAST].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonWest = new InputSourceButton();
|
||||
this._buttonWest.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) {
|
||||
return webxrGamepad.buttons[XR_BUTTON_1].value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_WEST].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonSouth = new InputSourceButton();
|
||||
this._buttonSouth.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) {
|
||||
return webxrGamepad.buttons[XR_BUTTON_1].value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_SOUTH].value; }
|
||||
return 0;
|
||||
};
|
||||
|
||||
this._buttonL1 = new InputSourceButton();
|
||||
this._buttonL1.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_L1].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonL2 = new InputSourceButton();
|
||||
this._buttonL2.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) {
|
||||
return webxrGamepad.buttons[XR_TRIGGER].value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_L2].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonL3 = new InputSourceButton();
|
||||
this._buttonL3.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) {
|
||||
return webxrGamepad.buttons[XR_STICK].value;
|
||||
} else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) {
|
||||
return webxrGamepad.buttons[XR_TOUCHPAD].value;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_L3].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonR1 = new InputSourceButton();
|
||||
this._buttonR1.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_R1].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonR2 = new InputSourceButton();
|
||||
this._buttonR2.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) {
|
||||
return webxrGamepad.buttons[XR_TRIGGER].value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_R2].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonR3 = new InputSourceButton();
|
||||
this._buttonR3.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) {
|
||||
return webxrGamepad.buttons[XR_STICK].value;
|
||||
} else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) {
|
||||
return webxrGamepad.buttons[XR_TOUCHPAD].value;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_R3].value; }
|
||||
return 0;
|
||||
};
|
||||
|
||||
// this._buttonTouchPad = new InputSourceButton();
|
||||
// this._buttonTouchPad.getValue = () => {
|
||||
// const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
// if (webGamepad) { return webGamepad.buttons[BUTTON_TOUCH_PAD].value; }
|
||||
// return 0;
|
||||
// };
|
||||
// this._buttonHome = new InputSourceButton();
|
||||
// this._buttonHome.getValue = () => {
|
||||
// const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
// if (webGamepad) { return webGamepad.buttons[BUTTON_HOME].value; }
|
||||
// return 0;
|
||||
// };
|
||||
this._buttonShare = new InputSourceButton();
|
||||
this._buttonShare.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_SHARE].value; }
|
||||
return 0;
|
||||
};
|
||||
this._buttonOptions = new InputSourceButton();
|
||||
this._buttonOptions.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_OPTIONS].value; }
|
||||
return 0;
|
||||
};
|
||||
|
||||
const dpadUp = new InputSourceButton();
|
||||
dpadUp.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_UP].value; }
|
||||
return 0;
|
||||
};
|
||||
const dpadDown = new InputSourceButton();
|
||||
dpadDown.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_DOWN].value; }
|
||||
return 0;
|
||||
};
|
||||
const dpadLeft = new InputSourceButton();
|
||||
dpadLeft.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_LEFT].value; }
|
||||
return 0;
|
||||
};
|
||||
const dpadRight = new InputSourceButton();
|
||||
dpadRight.getValue = (): number => {
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) { return webGamepad.buttons[BUTTON_DPAD_RIGHT].value; }
|
||||
return 0;
|
||||
};
|
||||
this._dpad = new InputSourceDpad({ up: dpadUp, down: dpadDown, left: dpadLeft, right: dpadRight });
|
||||
|
||||
const leftStickUp = new InputSourceButton();
|
||||
leftStickUp.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).negative;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
const leftStickDown = new InputSourceButton();
|
||||
leftStickDown.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).positive;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
const leftStickLeft = new InputSourceButton();
|
||||
leftStickLeft.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).negative;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
const leftStickRight = new InputSourceButton();
|
||||
leftStickRight.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).positive;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
this._leftStick = new InputSourceStick({ up: leftStickUp, down: leftStickDown, left: leftStickLeft, right: leftStickRight });
|
||||
|
||||
const rightStickUp = new InputSourceButton();
|
||||
rightStickUp.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).negative;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
const rightStickDown = new InputSourceButton();
|
||||
rightStickDown.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).positive;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
const rightStickLeft = new InputSourceButton();
|
||||
rightStickLeft.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).negative;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
const rightStickRight = new InputSourceButton();
|
||||
rightStickRight.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad) {
|
||||
if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive;
|
||||
} else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
|
||||
return this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
const webGamepad = GamepadInputDevice._getWebGamepad(this.deviceId);
|
||||
if (webGamepad) {
|
||||
return this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).positive;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
this._rightStick = new InputSourceStick({ up: rightStickUp, down: rightStickDown, left: rightStickLeft, right: rightStickRight });
|
||||
|
||||
this._buttonStart = new InputSourceButton();
|
||||
this._buttonStart.getValue = (): number => 0;
|
||||
|
||||
this._gripLeft = new InputSourceButton();
|
||||
this._gripLeft.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
if (USE_XR) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRLeftHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) {
|
||||
return webxrGamepad.buttons[XR_GRIP].value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
this._gripRight = new InputSourceButton();
|
||||
this._gripRight.getValue = (): number => {
|
||||
if (this.deviceId === -1) {
|
||||
const webxrGamepad = GamepadInputDevice._getWebXRGamepadMap()?.get(XRRightHandedness);
|
||||
if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) {
|
||||
return webxrGamepad.buttons[XR_GRIP].value;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
this._handLeftPosition = new InputSourcePosition();
|
||||
this._handLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.HAND_LEFT].position;
|
||||
this._handLeftOrientation = new InputSourceOrientation();
|
||||
this._handLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.HAND_LEFT].orientation;
|
||||
|
||||
this._handRightPosition = new InputSourcePosition();
|
||||
this._handRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.HAND_RIGHT].position;
|
||||
this._handRightOrientation = new InputSourceOrientation();
|
||||
this._handRightOrientation.getValue = (): Quat => this._webPoseState[Pose.HAND_RIGHT].orientation;
|
||||
|
||||
this._aimLeftPosition = new InputSourcePosition();
|
||||
this._aimLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.AIM_LEFT].position;
|
||||
this._aimLeftOrientation = new InputSourceOrientation();
|
||||
this._aimLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.AIM_LEFT].orientation;
|
||||
|
||||
this._aimRightPosition = new InputSourcePosition();
|
||||
this._aimRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.AIM_RIGHT].position;
|
||||
this._aimRightOrientation = new InputSourceOrientation();
|
||||
this._aimRightOrientation.getValue = (): Quat => this._webPoseState[Pose.AIM_RIGHT].orientation;
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HandheldCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
export class HandheldInputDevice {
|
||||
public get handheldPosition (): InputSourcePosition { return this._handheldPosition; }
|
||||
public get handheldOrientation (): InputSourceOrientation { return this._handheldOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _handheldPosition: InputSourcePosition;
|
||||
private declare _handheldOrientation: InputSourceOrientation;
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandheldCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._handheldPosition = new InputSourcePosition();
|
||||
this._handheldPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._handheldOrientation = new InputSourceOrientation();
|
||||
this._handheldOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
}
|
||||
}
|
||||
@@ -1,433 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HandleCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { EventHandle } from '../../../cocos/input/types';
|
||||
import { InputSourceButton, InputSourceStick, InputSourcePosition, InputSourceOrientation, InputSourceTouch } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
|
||||
enum Button {
|
||||
BUTTON_EAST,
|
||||
BUTTON_SOUTH,
|
||||
BUTTON_WEST,
|
||||
BUTTON_NORTH,
|
||||
BUTTON_TRIGGER_LEFT,
|
||||
BUTTON_TRIGGER_RIGHT,
|
||||
TRIGGER_LEFT,
|
||||
TRIGGER_RIGHT,
|
||||
GRIP_LEFT,
|
||||
GRIP_RIGHT,
|
||||
BUTTON_LEFT_STICK,
|
||||
LEFT_STICK_UP,
|
||||
LEFT_STICK_DOWN,
|
||||
LEFT_STICK_LEFT,
|
||||
LEFT_STICK_RIGHT,
|
||||
BUTTON_RIGHT_STICK,
|
||||
RIGHT_STICK_UP,
|
||||
RIGHT_STICK_DOWN,
|
||||
RIGHT_STICK_LEFT,
|
||||
RIGHT_STICK_RIGHT,
|
||||
ROKID_MENU,
|
||||
ROKID_START,
|
||||
}
|
||||
|
||||
export enum KeyEventType {
|
||||
KET_CLICK,
|
||||
KET_STICK,
|
||||
KET_GRAB,
|
||||
KET_TOUCH,
|
||||
}
|
||||
|
||||
enum StickKeyCode {
|
||||
UNDEFINE = 0,
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
L1,
|
||||
R1,
|
||||
MINUS,
|
||||
PLUS,
|
||||
L3,
|
||||
R3,
|
||||
MENU,
|
||||
START,
|
||||
TRIGGER_LEFT,
|
||||
TRIGGER_RIGHT,
|
||||
}
|
||||
|
||||
enum StickAxisCode {
|
||||
UNDEFINE = 0,
|
||||
X,
|
||||
Y,
|
||||
LEFT_STICK_X,
|
||||
LEFT_STICK_Y,
|
||||
RIGHT_STICK_X,
|
||||
RIGHT_STICK_Y,
|
||||
L2,
|
||||
R2,
|
||||
LEFT_GRIP,
|
||||
RIGHT_GRIP,
|
||||
}
|
||||
|
||||
enum StickTouchCode {
|
||||
UNDEFINE = 0,
|
||||
A,
|
||||
B,
|
||||
X,
|
||||
Y,
|
||||
LEFT_TRIGGER,
|
||||
RIGHT_TRIGGER,
|
||||
LEFT_THUMBSTICK,
|
||||
RIGHT_THUMBSTICK,
|
||||
}
|
||||
|
||||
const _nativeButtonMap = {
|
||||
1: Button.BUTTON_EAST,
|
||||
2: Button.BUTTON_SOUTH,
|
||||
3: Button.BUTTON_NORTH,
|
||||
4: Button.BUTTON_WEST,
|
||||
9: Button.BUTTON_LEFT_STICK,
|
||||
10: Button.BUTTON_RIGHT_STICK,
|
||||
11: Button.ROKID_MENU,
|
||||
12: Button.ROKID_START,
|
||||
13: Button.BUTTON_TRIGGER_LEFT,
|
||||
14: Button.BUTTON_TRIGGER_RIGHT,
|
||||
};
|
||||
|
||||
interface IAxisValue {
|
||||
negative: number;
|
||||
positive: number;
|
||||
}
|
||||
|
||||
type NativeButtonState = Record<Button, number>
|
||||
type NativeTouchState = Record<StickTouchCode, number>
|
||||
|
||||
export class HandleInputDevice {
|
||||
public get buttonNorth (): InputSourceButton { return this._buttonNorth; }
|
||||
public get buttonEast (): InputSourceButton { return this._buttonEast; }
|
||||
public get buttonWest (): InputSourceButton { return this._buttonWest; }
|
||||
public get buttonSouth (): InputSourceButton { return this._buttonSouth; }
|
||||
public get buttonTriggerLeft (): InputSourceButton { return this._buttonTriggerLeft; }
|
||||
public get buttonTriggerRight (): InputSourceButton { return this._buttonTriggerRight; }
|
||||
public get triggerLeft (): InputSourceButton { return this._triggerLeft; }
|
||||
public get triggerRight (): InputSourceButton { return this._triggerRight; }
|
||||
public get gripLeft (): InputSourceButton { return this._gripLeft; }
|
||||
public get gripRight (): InputSourceButton { return this._gripRight; }
|
||||
public get leftStick (): InputSourceStick { return this._leftStick; }
|
||||
public get rightStick (): InputSourceStick { return this._rightStick; }
|
||||
public get buttonLeftStick (): InputSourceButton { return this._buttonLeftStick; }
|
||||
public get buttonRightStick (): InputSourceButton { return this._buttonRightStick; }
|
||||
public get buttonOptions (): InputSourceButton { return this._buttonOptions; }
|
||||
public get buttonStart (): InputSourceButton { return this._buttonStart; }
|
||||
public get handLeftPosition (): InputSourcePosition { return this._handLeftPosition; }
|
||||
public get handLeftOrientation (): InputSourceOrientation { return this._handLeftOrientation; }
|
||||
public get handRightPosition (): InputSourcePosition { return this._handRightPosition; }
|
||||
public get handRightOrientation (): InputSourceOrientation { return this._handRightOrientation; }
|
||||
public get aimLeftPosition (): InputSourcePosition { return this._aimLeftPosition; }
|
||||
public get aimLeftOrientation (): InputSourceOrientation { return this._aimLeftOrientation; }
|
||||
public get aimRightPosition (): InputSourcePosition { return this._aimRightPosition; }
|
||||
public get aimRightOrientation (): InputSourceOrientation { return this._aimRightOrientation; }
|
||||
public get touchButtonA (): InputSourceTouch { return this._touchButtonA; }
|
||||
public get touchButtonB (): InputSourceTouch { return this._touchButtonB; }
|
||||
public get touchButtonX (): InputSourceTouch { return this._touchButtonX; }
|
||||
public get touchButtonY (): InputSourceTouch { return this._touchButtonY; }
|
||||
public get touchButtonTriggerLeft (): InputSourceTouch { return this._touchButtonTriggerLeft; }
|
||||
public get touchButtonTriggerRight (): InputSourceTouch { return this._touchButtonTriggerRight; }
|
||||
public get touchButtonThumbStickLeft (): InputSourceTouch { return this._touchButtonThumbStickLeft; }
|
||||
public get touchButtonThumbStickRight (): InputSourceTouch { return this._touchButtonThumbStickRight; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
private declare _buttonNorth: InputSourceButton;
|
||||
private declare _buttonEast: InputSourceButton;
|
||||
private declare _buttonWest: InputSourceButton;
|
||||
private declare _buttonSouth: InputSourceButton;
|
||||
private declare _buttonTriggerLeft: InputSourceButton;
|
||||
private declare _buttonTriggerRight: InputSourceButton;
|
||||
private declare _triggerLeft: InputSourceButton;
|
||||
private declare _triggerRight: InputSourceButton;
|
||||
private declare _gripLeft: InputSourceButton;
|
||||
private declare _gripRight: InputSourceButton;
|
||||
private declare _leftStick: InputSourceStick;
|
||||
private declare _rightStick: InputSourceStick;
|
||||
private declare _buttonLeftStick: InputSourceButton;
|
||||
private declare _buttonRightStick: InputSourceButton;
|
||||
private declare _buttonOptions: InputSourceButton;
|
||||
private declare _buttonStart: InputSourceButton;
|
||||
private declare _handLeftPosition: InputSourcePosition;
|
||||
private declare _handLeftOrientation: InputSourceOrientation;
|
||||
private declare _handRightPosition: InputSourcePosition;
|
||||
private declare _handRightOrientation: InputSourceOrientation;
|
||||
private declare _aimLeftPosition: InputSourcePosition;
|
||||
private declare _aimLeftOrientation: InputSourceOrientation;
|
||||
private declare _aimRightPosition: InputSourcePosition;
|
||||
private declare _aimRightOrientation: InputSourceOrientation;
|
||||
private declare _touchButtonA: InputSourceTouch;
|
||||
private declare _touchButtonB: InputSourceTouch;
|
||||
private declare _touchButtonX: InputSourceTouch;
|
||||
private declare _touchButtonY: InputSourceTouch;
|
||||
private declare _touchButtonTriggerLeft: InputSourceTouch;
|
||||
private declare _touchButtonTriggerRight: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickLeft: InputSourceTouch;
|
||||
private declare _touchButtonThumbStickRight: InputSourceTouch;
|
||||
|
||||
private _nativeButtonState: NativeButtonState = {
|
||||
[Button.BUTTON_SOUTH]: 0,
|
||||
[Button.BUTTON_EAST]: 0,
|
||||
[Button.BUTTON_WEST]: 0,
|
||||
[Button.BUTTON_NORTH]: 0,
|
||||
[Button.BUTTON_TRIGGER_LEFT]: 0,
|
||||
[Button.BUTTON_TRIGGER_RIGHT]: 0,
|
||||
[Button.TRIGGER_LEFT]: 0,
|
||||
[Button.TRIGGER_RIGHT]: 0,
|
||||
[Button.GRIP_LEFT]: 0,
|
||||
[Button.GRIP_RIGHT]: 0,
|
||||
[Button.LEFT_STICK_UP]: 0,
|
||||
[Button.LEFT_STICK_DOWN]: 0,
|
||||
[Button.LEFT_STICK_LEFT]: 0,
|
||||
[Button.LEFT_STICK_RIGHT]: 0,
|
||||
[Button.RIGHT_STICK_UP]: 0,
|
||||
[Button.RIGHT_STICK_DOWN]: 0,
|
||||
[Button.RIGHT_STICK_LEFT]: 0,
|
||||
[Button.RIGHT_STICK_RIGHT]: 0,
|
||||
[Button.BUTTON_LEFT_STICK]: 0,
|
||||
[Button.BUTTON_RIGHT_STICK]: 0,
|
||||
[Button.ROKID_MENU]: 0,
|
||||
[Button.ROKID_START]: 0,
|
||||
};
|
||||
|
||||
private _nativeTouchState: NativeTouchState = {
|
||||
[StickTouchCode.UNDEFINE]: 0,
|
||||
[StickTouchCode.A]: 0,
|
||||
[StickTouchCode.B]: 0,
|
||||
[StickTouchCode.X]: 0,
|
||||
[StickTouchCode.Y]: 0,
|
||||
[StickTouchCode.LEFT_TRIGGER]: 0,
|
||||
[StickTouchCode.RIGHT_TRIGGER]: 0,
|
||||
[StickTouchCode.LEFT_THUMBSTICK]: 0,
|
||||
[StickTouchCode.RIGHT_THUMBSTICK]: 0,
|
||||
};
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
window.addEventListener('xr-remote-input', (evt: Event): void => {
|
||||
const remoteInputEvent: CustomEvent = evt as CustomEvent;
|
||||
const keyEventType: KeyEventType = remoteInputEvent.detail.keyEventType;
|
||||
const stickAxisCode = remoteInputEvent.detail.stickAxisCode as StickAxisCode;
|
||||
const stickAxisValue = remoteInputEvent.detail.stickAxisValue as number;
|
||||
const stickKeyCode = remoteInputEvent.detail.stickKeyCode;
|
||||
const isButtonPressed = remoteInputEvent.detail.isButtonPressed;
|
||||
const touchCode = remoteInputEvent.detail.touchCode as StickTouchCode;
|
||||
const touchValue = remoteInputEvent.detail.touchValue as number;
|
||||
|
||||
if (keyEventType === KeyEventType.KET_CLICK) {
|
||||
const button = _nativeButtonMap[stickKeyCode];
|
||||
this._nativeButtonState[button] = isButtonPressed ? 1 : 0;
|
||||
} else if (keyEventType === KeyEventType.KET_STICK || keyEventType === KeyEventType.KET_GRAB) {
|
||||
//
|
||||
let negativeButton: Button|undefined;
|
||||
let positiveButton: Button|undefined;
|
||||
let axisValue: IAxisValue|undefined;
|
||||
switch (stickAxisCode) {
|
||||
case StickAxisCode.LEFT_STICK_X:
|
||||
negativeButton = Button.LEFT_STICK_LEFT;
|
||||
positiveButton = Button.LEFT_STICK_RIGHT;
|
||||
axisValue = this._axisToButtons(stickAxisValue);
|
||||
break;
|
||||
case StickAxisCode.LEFT_STICK_Y:
|
||||
negativeButton = Button.LEFT_STICK_DOWN;
|
||||
positiveButton = Button.LEFT_STICK_UP;
|
||||
axisValue = this._axisToButtons(stickAxisValue);
|
||||
break;
|
||||
case StickAxisCode.RIGHT_STICK_X:
|
||||
negativeButton = Button.RIGHT_STICK_LEFT;
|
||||
positiveButton = Button.RIGHT_STICK_RIGHT;
|
||||
axisValue = this._axisToButtons(stickAxisValue);
|
||||
break;
|
||||
case StickAxisCode.RIGHT_STICK_Y:
|
||||
negativeButton = Button.RIGHT_STICK_DOWN;
|
||||
positiveButton = Button.RIGHT_STICK_UP;
|
||||
axisValue = this._axisToButtons(stickAxisValue);
|
||||
break;
|
||||
case StickAxisCode.L2:
|
||||
this._nativeButtonState[Button.TRIGGER_LEFT] = stickAxisValue;
|
||||
break;
|
||||
case StickAxisCode.R2:
|
||||
this._nativeButtonState[Button.TRIGGER_RIGHT] = stickAxisValue;
|
||||
break;
|
||||
case StickAxisCode.LEFT_GRIP:
|
||||
this._nativeButtonState[Button.GRIP_LEFT] = stickAxisValue;
|
||||
break;
|
||||
case StickAxisCode.RIGHT_GRIP:
|
||||
this._nativeButtonState[Button.GRIP_RIGHT] = stickAxisValue;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (negativeButton && positiveButton && axisValue) {
|
||||
this._nativeButtonState[negativeButton] = axisValue.negative;
|
||||
this._nativeButtonState[positiveButton] = axisValue.positive;
|
||||
}
|
||||
} else if (keyEventType === KeyEventType.KET_TOUCH) {
|
||||
switch (touchCode) {
|
||||
case StickTouchCode.A:
|
||||
case StickTouchCode.B:
|
||||
case StickTouchCode.X:
|
||||
case StickTouchCode.Y:
|
||||
case StickTouchCode.LEFT_TRIGGER:
|
||||
case StickTouchCode.RIGHT_TRIGGER:
|
||||
case StickTouchCode.LEFT_THUMBSTICK:
|
||||
case StickTouchCode.RIGHT_THUMBSTICK:
|
||||
this._nativeTouchState[touchCode] = touchValue;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, this));
|
||||
});
|
||||
}
|
||||
|
||||
private _axisToButtons (axisValue: number): IAxisValue {
|
||||
const value = Math.abs(axisValue);
|
||||
if (axisValue > 0) {
|
||||
return { negative: 0, positive: value };
|
||||
} else if (axisValue < 0) {
|
||||
return { negative: value, positive: 0 };
|
||||
} else {
|
||||
return { negative: 0, positive: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HandleCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._buttonNorth = new InputSourceButton();
|
||||
this._buttonNorth.getValue = (): number => this._nativeButtonState[Button.BUTTON_NORTH];
|
||||
this._buttonEast = new InputSourceButton();
|
||||
this._buttonEast.getValue = (): number => this._nativeButtonState[Button.BUTTON_EAST];
|
||||
this._buttonWest = new InputSourceButton();
|
||||
this._buttonWest.getValue = (): number => this._nativeButtonState[Button.BUTTON_WEST];
|
||||
this._buttonSouth = new InputSourceButton();
|
||||
this._buttonSouth.getValue = (): number => this._nativeButtonState[Button.BUTTON_SOUTH];
|
||||
|
||||
this._buttonTriggerLeft = new InputSourceButton();
|
||||
this._buttonTriggerLeft.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_LEFT];
|
||||
this._buttonTriggerRight = new InputSourceButton();
|
||||
this._buttonTriggerRight.getValue = (): number => this._nativeButtonState[Button.BUTTON_TRIGGER_RIGHT];
|
||||
this._triggerLeft = new InputSourceButton();
|
||||
this._triggerLeft.getValue = (): number => this._nativeButtonState[Button.TRIGGER_LEFT];
|
||||
this._triggerRight = new InputSourceButton();
|
||||
this._triggerRight.getValue = (): number => this._nativeButtonState[Button.TRIGGER_RIGHT];
|
||||
this._gripLeft = new InputSourceButton();
|
||||
this._gripLeft.getValue = (): number => this._nativeButtonState[Button.GRIP_LEFT];
|
||||
this._gripRight = new InputSourceButton();
|
||||
this._gripRight.getValue = (): number => this._nativeButtonState[Button.GRIP_RIGHT];
|
||||
|
||||
this._buttonLeftStick = new InputSourceButton();
|
||||
this._buttonLeftStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_LEFT_STICK];
|
||||
const leftStickUp = new InputSourceButton();
|
||||
leftStickUp.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_UP];
|
||||
const leftStickDown = new InputSourceButton();
|
||||
leftStickDown.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_DOWN];
|
||||
const leftStickLeft = new InputSourceButton();
|
||||
leftStickLeft.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_LEFT];
|
||||
const leftStickRight = new InputSourceButton();
|
||||
leftStickRight.getValue = (): number => this._nativeButtonState[Button.LEFT_STICK_RIGHT];
|
||||
this._leftStick = new InputSourceStick({
|
||||
up: leftStickUp,
|
||||
down: leftStickDown,
|
||||
left: leftStickLeft,
|
||||
right: leftStickRight,
|
||||
});
|
||||
|
||||
this._buttonRightStick = new InputSourceButton();
|
||||
this._buttonRightStick.getValue = (): number => this._nativeButtonState[Button.BUTTON_RIGHT_STICK];
|
||||
const rightStickUp = new InputSourceButton();
|
||||
rightStickUp.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_UP];
|
||||
const rightStickDown = new InputSourceButton();
|
||||
rightStickDown.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_DOWN];
|
||||
const rightStickLeft = new InputSourceButton();
|
||||
rightStickLeft.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_LEFT];
|
||||
const rightStickRight = new InputSourceButton();
|
||||
rightStickRight.getValue = (): number => this._nativeButtonState[Button.RIGHT_STICK_RIGHT];
|
||||
this._rightStick = new InputSourceStick({
|
||||
up: rightStickUp,
|
||||
down: rightStickDown,
|
||||
left: rightStickLeft,
|
||||
right: rightStickRight,
|
||||
});
|
||||
|
||||
this._buttonOptions = new InputSourceButton();
|
||||
this._buttonOptions.getValue = (): number => this._nativeButtonState[Button.ROKID_MENU];
|
||||
this._buttonStart = new InputSourceButton();
|
||||
this._buttonStart.getValue = (): number => this._nativeButtonState[Button.ROKID_START];
|
||||
|
||||
this._handLeftPosition = new InputSourcePosition();
|
||||
this._handLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._handLeftOrientation = new InputSourceOrientation();
|
||||
this._handLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
this._handRightPosition = new InputSourcePosition();
|
||||
this._handRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._handRightOrientation = new InputSourceOrientation();
|
||||
this._handRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
this._aimLeftPosition = new InputSourcePosition();
|
||||
this._aimLeftPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._aimLeftOrientation = new InputSourceOrientation();
|
||||
this._aimLeftOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
|
||||
this._aimRightPosition = new InputSourcePosition();
|
||||
this._aimRightPosition.getValue = (): Readonly<Vec3> => Vec3.ZERO;
|
||||
this._aimRightOrientation = new InputSourceOrientation();
|
||||
this._aimRightOrientation.getValue = (): Readonly<Quat> => Quat.IDENTITY;
|
||||
this._touchButtonA = new InputSourceTouch();
|
||||
this._touchButtonA.getValue = (): number => this._nativeTouchState[StickTouchCode.A];
|
||||
this._touchButtonB = new InputSourceTouch();
|
||||
this._touchButtonB.getValue = (): number => this._nativeTouchState[StickTouchCode.B];
|
||||
this._touchButtonX = new InputSourceTouch();
|
||||
this._touchButtonX.getValue = (): number => this._nativeTouchState[StickTouchCode.X];
|
||||
this._touchButtonY = new InputSourceTouch();
|
||||
this._touchButtonY.getValue = (): number => this._nativeTouchState[StickTouchCode.Y];
|
||||
this._touchButtonTriggerLeft = new InputSourceTouch();
|
||||
this._touchButtonTriggerLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_TRIGGER];
|
||||
this._touchButtonTriggerRight = new InputSourceTouch();
|
||||
this._touchButtonTriggerRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_TRIGGER];
|
||||
this._touchButtonThumbStickLeft = new InputSourceTouch();
|
||||
this._touchButtonThumbStickLeft.getValue = (): number => this._nativeTouchState[StickTouchCode.LEFT_THUMBSTICK];
|
||||
this._touchButtonThumbStickRight = new InputSourceTouch();
|
||||
this._touchButtonThumbStickRight.getValue = (): number => this._nativeTouchState[StickTouchCode.RIGHT_THUMBSTICK];
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HMDCallback } from 'pal/input';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { EventHMD } from '../../../cocos/input/types';
|
||||
import { InputSourcePosition, InputSourceOrientation } from '../input-source';
|
||||
import { Vec3, Quat } from '../../../cocos/core/math';
|
||||
import legacyCC from '../../../predefine';
|
||||
|
||||
enum Pose {
|
||||
VIEW_LEFT = 0,
|
||||
VIEW_RIGHT = 3,
|
||||
HEAD_MIDDLE = 6,
|
||||
}
|
||||
|
||||
interface IPoseValue {
|
||||
position: Vec3;
|
||||
orientation: Quat;
|
||||
}
|
||||
|
||||
interface IPoseInfo {
|
||||
readonly code: number;
|
||||
readonly position: DOMPointReadOnly;
|
||||
readonly orientation: DOMPointReadOnly;
|
||||
}
|
||||
|
||||
type WebPoseState = Record<Pose, IPoseValue>
|
||||
|
||||
export class HMDInputDevice {
|
||||
public get viewLeftPosition (): InputSourcePosition { return this._viewLeftPosition; }
|
||||
public get viewLeftOrientation (): InputSourceOrientation { return this._viewLeftOrientation; }
|
||||
public get viewRightPosition (): InputSourcePosition { return this._viewRightPosition; }
|
||||
public get viewRightOrientation (): InputSourceOrientation { return this._viewRightOrientation; }
|
||||
public get headMiddlePosition (): InputSourcePosition { return this._headMiddlePosition; }
|
||||
public get headMiddleOrientation (): InputSourceOrientation { return this._headMiddleOrientation; }
|
||||
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private _intervalId = -1;
|
||||
|
||||
private declare _viewLeftPosition: InputSourcePosition;
|
||||
private declare _viewLeftOrientation: InputSourceOrientation;
|
||||
private declare _viewRightPosition: InputSourcePosition;
|
||||
private declare _viewRightOrientation: InputSourceOrientation;
|
||||
private declare _headMiddlePosition: InputSourcePosition;
|
||||
private declare _headMiddleOrientation: InputSourceOrientation;
|
||||
|
||||
private _webPoseState: WebPoseState = {
|
||||
[Pose.VIEW_LEFT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.VIEW_RIGHT]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
[Pose.HEAD_MIDDLE]: { position: Vec3.ZERO, orientation: Quat.IDENTITY },
|
||||
};
|
||||
|
||||
constructor () {
|
||||
this._initInputSource();
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _ensureDirectorDefined (): Promise<void> {
|
||||
return new Promise<void>((resolve) => {
|
||||
this._intervalId = setInterval(() => {
|
||||
if (legacyCC.director && legacyCC.Director) {
|
||||
clearInterval(this._intervalId);
|
||||
this._intervalId = -1;
|
||||
resolve();
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
this._ensureDirectorDefined().then(() => {
|
||||
legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, this._scanHmd, this);
|
||||
}).catch((e) => {});
|
||||
}
|
||||
|
||||
private _scanHmd (): void {
|
||||
const infoList = globalThis.__globalXR?.webxrHmdPoseInfos as IPoseInfo[];
|
||||
if (!infoList) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < infoList.length; ++i) {
|
||||
const info = infoList[i];
|
||||
this._updateWebPoseState(info);
|
||||
}
|
||||
this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this));
|
||||
}
|
||||
|
||||
/**
|
||||
* @engineInternal
|
||||
*/
|
||||
public _on (eventType: InputEventType, callback: HMDCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _updateWebPoseState (info: IPoseInfo): void {
|
||||
if (info.code !== Pose.VIEW_LEFT && info.code !== Pose.VIEW_RIGHT && info.code !== Pose.HEAD_MIDDLE) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._webPoseState[info.code] = {
|
||||
position: new Vec3(info.position.x, info.position.y, info.position.z),
|
||||
orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w),
|
||||
};
|
||||
}
|
||||
|
||||
private _initInputSource (): void {
|
||||
this._viewLeftPosition = new InputSourcePosition();
|
||||
this._viewLeftPosition.getValue = (): Vec3 => this._webPoseState[Pose.VIEW_LEFT].position;
|
||||
this._viewLeftOrientation = new InputSourceOrientation();
|
||||
this._viewLeftOrientation.getValue = (): Quat => this._webPoseState[Pose.VIEW_LEFT].orientation;
|
||||
|
||||
this._viewRightPosition = new InputSourcePosition();
|
||||
this._viewRightPosition.getValue = (): Vec3 => this._webPoseState[Pose.VIEW_RIGHT].position;
|
||||
this._viewRightOrientation = new InputSourceOrientation();
|
||||
this._viewRightOrientation.getValue = (): Quat => this._webPoseState[Pose.VIEW_RIGHT].orientation;
|
||||
|
||||
this._headMiddlePosition = new InputSourcePosition();
|
||||
this._headMiddlePosition.getValue = (): Vec3 => this._webPoseState[Pose.HEAD_MIDDLE].position;
|
||||
this._headMiddleOrientation = new InputSourceOrientation();
|
||||
this._headMiddleOrientation.getValue = (): Quat => this._webPoseState[Pose.HEAD_MIDDLE].orientation;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
export * from './accelerometer-input';
|
||||
export * from './gamepad-input';
|
||||
export * from './handle-input';
|
||||
export * from './hmd-input';
|
||||
export * from './handheld-input';
|
||||
export * from './keyboard-input';
|
||||
export * from './mouse-input';
|
||||
export * from './touch-input';
|
||||
|
||||
checkPalIntegrity<typeof import('pal/input')>(withImpl<typeof import('./index')>());
|
||||
@@ -1,79 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { KeyboardCallback } from 'pal/input';
|
||||
import { KeyCode, EventKeyboard } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { code2KeyCode } from '../keycodes';
|
||||
|
||||
function getKeyCode (code: string): KeyCode {
|
||||
return code2KeyCode[code] || KeyCode.NONE;
|
||||
}
|
||||
|
||||
export class KeyboardInputSource {
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
constructor () {
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
public dispatchKeyboardDownEvent (nativeKeyboardEvent: KeyboardEvent): void { this._handleKeyboardDown(nativeKeyboardEvent); }
|
||||
public dispatchKeyboardUpEvent (nativeKeyboardEvent: KeyboardEvent): void { this._handleKeyboardUp(nativeKeyboardEvent); }
|
||||
|
||||
public on (eventType: InputEventType, callback: KeyboardCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
const canvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
|
||||
canvas?.addEventListener('keydown', this._handleKeyboardDown.bind(this));
|
||||
canvas?.addEventListener('keyup', this._handleKeyboardUp.bind(this));
|
||||
}
|
||||
|
||||
private _getInputEvent (event: any, eventType: InputEventType): EventKeyboard {
|
||||
const keyCode = getKeyCode(event.code);
|
||||
const eventKeyboard = new EventKeyboard(keyCode, eventType);
|
||||
return eventKeyboard;
|
||||
}
|
||||
|
||||
private _handleKeyboardDown (event: KeyboardEvent): void {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
if (!event.repeat) {
|
||||
const keyDownInputEvent = this._getInputEvent(event, InputEventType.KEY_DOWN);
|
||||
this._eventTarget.emit(InputEventType.KEY_DOWN, keyDownInputEvent);
|
||||
} else {
|
||||
const keyPressingInputEvent = this._getInputEvent(event, InputEventType.KEY_PRESSING);
|
||||
this._eventTarget.emit(InputEventType.KEY_PRESSING, keyPressingInputEvent);
|
||||
}
|
||||
}
|
||||
|
||||
private _handleKeyboardUp (event: KeyboardEvent): void {
|
||||
const inputEvent = this._getInputEvent(event, InputEventType.KEY_UP);
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
this._eventTarget.emit(InputEventType.KEY_UP, inputEvent);
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR, TEST } from 'internal:constants';
|
||||
import { MouseCallback } from 'pal/input';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { EventMouse } from '../../../cocos/input/types';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { Rect, Vec2 } from '../../../cocos/core/math';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
import { warn } from '../../../cocos/core/platform/debug';
|
||||
|
||||
export class MouseInputSource {
|
||||
private _canvas?: HTMLCanvasElement;
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
private _pointLocked = false;
|
||||
private _isPressed = false;
|
||||
private _preMousePos: Vec2 = new Vec2();
|
||||
|
||||
private _handleMouseDown!: (event: MouseEvent) => void;
|
||||
private _handleMouseMove!: (event: MouseEvent) => void;
|
||||
private _handleMouseUp!: (event: MouseEvent) => void;
|
||||
|
||||
constructor () {
|
||||
if (systemInfo.hasFeature(Feature.EVENT_MOUSE)) {
|
||||
this._canvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
|
||||
if (!this._canvas && !TEST && !EDITOR) {
|
||||
warn('failed to access canvas');
|
||||
}
|
||||
|
||||
this._handleMouseDown = this._createCallback(InputEventType.MOUSE_DOWN);
|
||||
this._handleMouseMove = this._createCallback(InputEventType.MOUSE_MOVE);
|
||||
this._handleMouseUp = this._createCallback(InputEventType.MOUSE_UP);
|
||||
// In Editor, we receive mouse event from manually event dispatching.
|
||||
if (!EDITOR) {
|
||||
this._registerEvent();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public dispatchMouseDownEvent (nativeMouseEvent: any): void { this._handleMouseDown(nativeMouseEvent as MouseEvent); }
|
||||
public dispatchMouseMoveEvent (nativeMouseEvent: any): void { this._handleMouseMove(nativeMouseEvent as MouseEvent); }
|
||||
public dispatchMouseUpEvent (nativeMouseEvent: any): void { this._handleMouseUp(nativeMouseEvent as MouseEvent); }
|
||||
public dispatchScrollEvent (nativeMouseEvent: WheelEvent): void { this._handleMouseWheel(nativeMouseEvent); }
|
||||
|
||||
public on (eventType: InputEventType, callback: MouseCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
private _getCanvasRect (): Rect {
|
||||
const canvas = this._canvas;
|
||||
const box = canvas?.getBoundingClientRect();
|
||||
if (box) {
|
||||
return new Rect(box.x, box.y, box.width, box.height);
|
||||
}
|
||||
return new Rect(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
private _getLocation (mouseEvent: MouseEvent): Vec2 {
|
||||
const canvasRect = this._getCanvasRect();
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
let x = this._pointLocked ? (this._preMousePos.x / dpr + mouseEvent.movementX) : (mouseEvent.clientX - canvasRect.x);
|
||||
let y = this._pointLocked ? (this._preMousePos.y / dpr - mouseEvent.movementY) : (canvasRect.y + canvasRect.height - mouseEvent.clientY);
|
||||
x *= dpr;
|
||||
y *= dpr;
|
||||
return new Vec2(x, y);
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
// register mouse down event
|
||||
window.addEventListener('mousedown', () => {
|
||||
this._isPressed = true;
|
||||
});
|
||||
this._canvas?.addEventListener('mousedown', this._handleMouseDown);
|
||||
|
||||
// register mouse move event
|
||||
this._canvas?.addEventListener('mousemove', this._handleMouseMove);
|
||||
|
||||
// register mouse up event
|
||||
window.addEventListener('mouseup', this._handleMouseUp);
|
||||
this._canvas?.addEventListener('mouseup', this._handleMouseUp);
|
||||
|
||||
// register wheel event
|
||||
this._canvas?.addEventListener('wheel', this._handleMouseWheel.bind(this));
|
||||
this._registerPointerLockEvent();
|
||||
|
||||
this._canvas?.addEventListener('mouseleave', this._handleMouseLeave.bind(this));
|
||||
this._canvas?.addEventListener('mouseenter', this._handleMouseEnter.bind(this));
|
||||
}
|
||||
|
||||
// To be removed in the future.
|
||||
private _registerPointerLockEvent (): void {
|
||||
const lockChangeAlert = (): void => {
|
||||
const canvas = this._canvas;
|
||||
// NOTE: mozPointerLockElement is not a standard web interface
|
||||
if (document.pointerLockElement === canvas || (document as any).mozPointerLockElement === canvas) {
|
||||
this._pointLocked = true;
|
||||
} else {
|
||||
this._pointLocked = false;
|
||||
}
|
||||
};
|
||||
if ('onpointerlockchange' in document) {
|
||||
document.addEventListener('pointerlockchange', lockChangeAlert, false);
|
||||
} else if ('onmozpointerlockchange' in document) {
|
||||
// NOTE: handle event compatibility
|
||||
(document as any).addEventListener('mozpointerlockchange', lockChangeAlert, false);
|
||||
}
|
||||
}
|
||||
|
||||
private _createCallback (eventType: InputEventType) {
|
||||
return (mouseEvent: MouseEvent): void => {
|
||||
const location = this._getLocation(mouseEvent);
|
||||
const { button, buttons } = mouseEvent;
|
||||
let targetButton = button;
|
||||
switch (eventType) {
|
||||
case InputEventType.MOUSE_DOWN:
|
||||
this._canvas?.focus();
|
||||
this._isPressed = true;
|
||||
break;
|
||||
case InputEventType.MOUSE_UP:
|
||||
this._isPressed = false;
|
||||
break;
|
||||
case InputEventType.MOUSE_MOVE:
|
||||
// mouseEvent.button doesn't work well in mouse move event
|
||||
// now we don't support multiple buttons in one mouse event
|
||||
if (1 & buttons) {
|
||||
targetButton = EventMouse.BUTTON_LEFT;
|
||||
} else if (2 & buttons) {
|
||||
targetButton = EventMouse.BUTTON_RIGHT;
|
||||
} else if (4 & buttons) {
|
||||
targetButton = EventMouse.BUTTON_MIDDLE;
|
||||
} else {
|
||||
targetButton = EventMouse.BUTTON_MISSING;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const eventMouse = new EventMouse(eventType, false, this._preMousePos);
|
||||
eventMouse.setLocation(location.x, location.y);
|
||||
eventMouse.setButton(targetButton);
|
||||
eventMouse.movementX = mouseEvent.movementX;
|
||||
eventMouse.movementY = mouseEvent.movementY;
|
||||
|
||||
// update previous mouse position.
|
||||
this._preMousePos.set(location.x, location.y);
|
||||
mouseEvent.stopPropagation();
|
||||
if (mouseEvent.target === this._canvas) {
|
||||
mouseEvent.preventDefault();
|
||||
}
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
};
|
||||
}
|
||||
|
||||
private _handleMouseWheel (mouseEvent: WheelEvent): void {
|
||||
const eventType = InputEventType.MOUSE_WHEEL;
|
||||
const location = this._getLocation(mouseEvent);
|
||||
const button = mouseEvent.button;
|
||||
|
||||
const eventMouse = new EventMouse(eventType, false, this._preMousePos);
|
||||
eventMouse.setLocation(location.x, location.y);
|
||||
eventMouse.setButton(button);
|
||||
eventMouse.movementX = mouseEvent.movementX;
|
||||
eventMouse.movementY = mouseEvent.movementY;
|
||||
|
||||
const wheelSensitivityFactor = 5;
|
||||
eventMouse.setScrollData(mouseEvent.deltaX * wheelSensitivityFactor, -mouseEvent.deltaY * wheelSensitivityFactor);
|
||||
// update previous mouse position.
|
||||
this._preMousePos.set(location.x, location.y);
|
||||
mouseEvent.stopPropagation();
|
||||
if (mouseEvent.target === this._canvas) {
|
||||
mouseEvent.preventDefault();
|
||||
}
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
|
||||
private _handleMouseLeave (mouseEvent: MouseEvent): void {
|
||||
const eventType = InputEventType.MOUSE_LEAVE;
|
||||
const eventMouse = new EventMouse(eventType, false);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
|
||||
private _handleMouseEnter (mouseEvent: MouseEvent): void {
|
||||
const eventType = InputEventType.MOUSE_ENTER;
|
||||
const eventMouse = new EventMouse(eventType, false);
|
||||
this._eventTarget.emit(eventType, eventMouse);
|
||||
}
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { TouchCallback } from 'pal/input';
|
||||
import { EDITOR, TEST, USE_XR } from 'internal:constants';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { Rect, Vec2 } from '../../../cocos/core/math';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { Touch, EventTouch } from '../../../cocos/input/types';
|
||||
import { touchManager } from '../touch-manager';
|
||||
import { macro } from '../../../cocos/core/platform/macro';
|
||||
import { InputEventType } from '../../../cocos/input/types/event-enum';
|
||||
import { Feature } from '../../system-info/enum-type';
|
||||
import { warn } from '../../../cocos/core/platform/debug';
|
||||
|
||||
export class TouchInputSource {
|
||||
private _canvas?: HTMLCanvasElement;
|
||||
private _eventTarget: EventTarget = new EventTarget();
|
||||
|
||||
constructor () {
|
||||
if (systemInfo.hasFeature(Feature.INPUT_TOUCH)) {
|
||||
this._canvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
|
||||
if (!this._canvas && !TEST && !EDITOR) {
|
||||
warn('failed to access canvas');
|
||||
}
|
||||
// In Editor, we don't receive touch event but maybe receive simulated touch event.
|
||||
if (!EDITOR) {
|
||||
this._registerEvent();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
// IDEA: need to register on window ?
|
||||
this._canvas?.addEventListener('touchstart', this._createCallback(InputEventType.TOUCH_START));
|
||||
this._canvas?.addEventListener('touchmove', this._createCallback(InputEventType.TOUCH_MOVE));
|
||||
this._canvas?.addEventListener('touchend', this._createCallback(InputEventType.TOUCH_END));
|
||||
this._canvas?.addEventListener('touchcancel', this._createCallback(InputEventType.TOUCH_CANCEL));
|
||||
}
|
||||
|
||||
private _createCallback (eventType: InputEventType) {
|
||||
return (event: TouchEvent): void => {
|
||||
const canvasRect = this._getCanvasRect();
|
||||
const handleTouches: Touch[] = [];
|
||||
const length = event.changedTouches.length;
|
||||
for (let i = 0; i < length; ++i) {
|
||||
const changedTouch = event.changedTouches[i];
|
||||
const touchID = changedTouch.identifier;
|
||||
if (touchID === null) {
|
||||
continue;
|
||||
}
|
||||
const location = this._getLocation(changedTouch, canvasRect);
|
||||
const touch = touchManager.getOrCreateTouch(touchID, location.x, location.y);
|
||||
if (!touch) {
|
||||
continue;
|
||||
}
|
||||
if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) {
|
||||
touchManager.releaseTouch(touchID);
|
||||
}
|
||||
handleTouches.push(touch);
|
||||
}
|
||||
event.stopPropagation();
|
||||
if (event.target === this._canvas) {
|
||||
event.preventDefault();
|
||||
}
|
||||
if (eventType === InputEventType.TOUCH_START) {
|
||||
this._canvas?.focus();
|
||||
}
|
||||
if (handleTouches.length > 0) {
|
||||
const eventTouch = new EventTouch(
|
||||
handleTouches,
|
||||
false,
|
||||
eventType,
|
||||
touchManager.getAllTouches(),
|
||||
);
|
||||
this._eventTarget.emit(eventType, eventTouch);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private _getCanvasRect (): Rect {
|
||||
const canvas = this._canvas;
|
||||
const box = canvas?.getBoundingClientRect();
|
||||
if (box) {
|
||||
return new Rect(box.x, box.y, box.width, box.height);
|
||||
}
|
||||
return new Rect(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
private _getLocation (touch: globalThis.Touch, canvasRect: Rect): Vec2 {
|
||||
// webxr has been converted to screen coordinates via camera
|
||||
if (USE_XR && globalThis.__globalXR && globalThis.__globalXR.ar && globalThis.__globalXR.ar.isWebXR()) {
|
||||
return new Vec2(touch.clientX, touch.clientY);
|
||||
}
|
||||
|
||||
let x = touch.clientX - canvasRect.x;
|
||||
let y = canvasRect.y + canvasRect.height - touch.clientY;
|
||||
if (screenAdapter.isFrameRotated) {
|
||||
const tmp = x;
|
||||
x = canvasRect.height - y;
|
||||
y = tmp;
|
||||
}
|
||||
const dpr = screenAdapter.devicePixelRatio;
|
||||
x *= dpr;
|
||||
y *= dpr;
|
||||
return new Vec2(x, y);
|
||||
}
|
||||
|
||||
public on (eventType: InputEventType, callback: TouchCallback, target?: any): void {
|
||||
this._eventTarget.on(eventType, callback, target);
|
||||
}
|
||||
|
||||
public dispatchEventsInCache (): void {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
declare const guard: unique symbol;
|
||||
|
||||
type Guard = typeof guard;
|
||||
|
||||
/**
|
||||
* Checks if a PAL implementation module is compatible with its target interface module.
|
||||
*
|
||||
* @example
|
||||
* If you write the following in somewhere:
|
||||
*
|
||||
* ```ts
|
||||
* checkPalIntegrity<typeof import('pal-interface-module')>(
|
||||
* withImpl<typeof import('pal-implementation-module')>());
|
||||
* ```
|
||||
*
|
||||
* you will receive a compilation error
|
||||
* if your implementation module is not fulfil the interface module.
|
||||
*
|
||||
* @note This function should be easily tree-shaken.
|
||||
*/
|
||||
export function checkPalIntegrity<T> (impl: T & Guard): void {
|
||||
/* empty */
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function, see example of `checkPalIntegrity()`.
|
||||
*
|
||||
*/
|
||||
export function withImpl<T> (): T & Guard {
|
||||
return 0 as unknown as T & Guard;
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill } from '../utils';
|
||||
|
||||
declare let my: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, my);
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
minigame.isDevTool = window.navigator && (/AlipayIDE/.test(window.navigator.userAgent));
|
||||
|
||||
minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight;
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
const landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// NOTE: onDeviceOrientationChange is not supported on this platform
|
||||
// my.onDeviceOrientationChange((res) => {
|
||||
// if (res.value === 'landscape') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// } else if (res.value === 'landscapeReverse') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
// }
|
||||
// });
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region TouchEvent
|
||||
// my.onTouchStart register touch event listner on body
|
||||
// need to register on canvas
|
||||
minigame.onTouchStart = function (cb): void {
|
||||
window.canvas.addEventListener('touchstart', (res) => {
|
||||
cb && cb(res);
|
||||
});
|
||||
};
|
||||
minigame.onTouchMove = function (cb): void {
|
||||
window.canvas.addEventListener('touchmove', (res) => {
|
||||
cb && cb(res);
|
||||
});
|
||||
};
|
||||
minigame.onTouchEnd = function (cb): void {
|
||||
window.canvas.addEventListener('touchend', (res) => {
|
||||
cb && cb(res);
|
||||
});
|
||||
};
|
||||
minigame.onTouchCancel = function (cb): void {
|
||||
window.canvas.addEventListener('touchcancel', (res) => {
|
||||
cb && cb(res);
|
||||
});
|
||||
};
|
||||
// #endregion TouchEvent
|
||||
|
||||
// #region Audio
|
||||
const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, {
|
||||
onPlay: true, // Fix: onPlay can not be executed at Alipay(Override onPlay method).
|
||||
onPause: true, // Fix: calling pause twice, onPause won't execute twice.(Override onPause method)
|
||||
onStop: false,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.createInnerAudioContext = function (): InnerAudioContext {
|
||||
// NOTE: `onCanPlay` and `offCanPlay` is not standard minigame interface,
|
||||
// so here we mark audio as type of any
|
||||
const audio: any = polyfilledCreateInnerAudio();
|
||||
if (audio.onCanPlay) {
|
||||
audio.onCanplay = audio.onCanPlay.bind(audio);
|
||||
delete audio.onCanPlay;
|
||||
}
|
||||
if (audio.offCanPlay) {
|
||||
audio.offCanplay = audio.offCanPlay.bind(audio);
|
||||
delete audio.offCanPlay;
|
||||
}
|
||||
return audio as InnerAudioContext;
|
||||
};
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any): void => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void {
|
||||
if (_accelerometerCb) {
|
||||
my.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
minigame.startAccelerometer = function (res: any): void {
|
||||
if (_accelerometerCb) {
|
||||
my.onAccelerometerChange(_accelerometerCb);
|
||||
} else {
|
||||
// my.startAccelerometer() is not implemented.
|
||||
console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on alipay platform');
|
||||
}
|
||||
};
|
||||
minigame.stopAccelerometer = function (res: any): void {
|
||||
// my.stopAccelerometer() is not implemented.
|
||||
minigame.offAccelerometerChange();
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
// #region SafeArea
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
if (typeof minigame.getWindowInfo === "function") {
|
||||
const windowInfo = minigame.getWindowInfo();
|
||||
return windowInfo.safeArea;
|
||||
}
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: systemInfo.windowHeight,
|
||||
right: systemInfo.windowWidth,
|
||||
width: systemInfo.windowWidth,
|
||||
height: systemInfo.windowHeight,
|
||||
};
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./alipay')>());
|
||||
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill } from '../utils';
|
||||
|
||||
declare let swan: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, swan);
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
minigame.isDevTool = systemInfo.platform === 'devtools';
|
||||
|
||||
minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight;
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
let landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
swan.onDeviceOrientationChange((res) => {
|
||||
if (res.value === 'landscape') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
} else if (res.value === 'landscapeReverse') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region Accelerometer
|
||||
let _customAccelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
let _innerAccelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void {
|
||||
// swan.offAccelerometerChange() is not supported.
|
||||
// so we can only register AccelerometerChange callback, but can't unregister.
|
||||
if (!_innerAccelerometerCb) {
|
||||
_innerAccelerometerCb = (res: any): void => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
_customAccelerometerCb?.(resClone);
|
||||
};
|
||||
swan.onAccelerometerChange(_innerAccelerometerCb);
|
||||
// onAccelerometerChange would start accelerometer, need to stop it mannually
|
||||
swan.stopAccelerometer({});
|
||||
}
|
||||
_customAccelerometerCb = cb;
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void {
|
||||
// swan.offAccelerometerChange() is not supported.
|
||||
_customAccelerometerCb = undefined;
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(swan, {
|
||||
onPlay: true,
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: false,
|
||||
});
|
||||
|
||||
// #region SafeArea
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: systemInfo.screenHeight,
|
||||
right: systemInfo.screenWidth,
|
||||
width: systemInfo.screenWidth,
|
||||
height: systemInfo.screenHeight,
|
||||
};
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./baidu')>());
|
||||
@@ -1,126 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame, SystemInfo } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill } from '../utils';
|
||||
|
||||
declare let tt: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, tt);
|
||||
|
||||
// #region platform related
|
||||
minigame.tt = {};
|
||||
minigame.tt.getAudioContext = tt.getAudioContext?.bind(tt);
|
||||
// #endregion platform related
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
|
||||
minigame.isDevTool = (systemInfo.platform === 'devtools');
|
||||
|
||||
minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight;
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
let landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
tt.onDeviceOrientationChange((res) => {
|
||||
if (res.value === 'landscape') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
} else if (res.value === 'landscapeReverse') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any): void => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void {
|
||||
if (_accelerometerCb) {
|
||||
tt.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
minigame.startAccelerometer = function (res: any): void {
|
||||
if (_accelerometerCb) {
|
||||
tt.onAccelerometerChange(_accelerometerCb);
|
||||
}
|
||||
tt.startAccelerometer(res);
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(tt, {
|
||||
onPlay: true,
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: true,
|
||||
});
|
||||
|
||||
// #region SafeArea
|
||||
// FIX_ME: wrong safe area when orientation is landscape left
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
const locSystemInfo = tt.getSystemInfoSync() as SystemInfo;
|
||||
let { top, left, right } = locSystemInfo.safeArea;
|
||||
const { bottom, width, height } = locSystemInfo.safeArea;
|
||||
// HACK: on iOS device, the orientation should mannually rotate
|
||||
if (locSystemInfo.platform === 'ios' && !minigame.isDevTool && minigame.isLandscape) {
|
||||
const tmpTop = top; const tmpLeft = left; const tmpBottom = bottom; const tmpRight = right; const tmpWidth = width; const tmpHeight = height;
|
||||
top = tmpLeft;
|
||||
left = tmpTop;
|
||||
right = tmpRight - tmpTop;
|
||||
}
|
||||
return { top, left, bottom, right, width, height };
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./bytedance')>());
|
||||
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
const minigame: any = {};
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./non-minigame')>());
|
||||
@@ -1,136 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { VIVO } from 'internal:constants';
|
||||
import { SystemInfo, IMiniGame } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill } from '../utils';
|
||||
|
||||
declare let ral: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, ral);
|
||||
minigame.ral = ral;
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
minigame.isDevTool = (systemInfo.platform === 'devtools');
|
||||
|
||||
// NOTE: size and orientation info is wrong at the init phase, need to define as a getter
|
||||
Object.defineProperty(minigame, 'isLandscape', {
|
||||
get () {
|
||||
if (VIVO) {
|
||||
return systemInfo.screenWidth > systemInfo.screenHeight;
|
||||
} else {
|
||||
const locSysInfo = minigame.getSystemInfoSync();
|
||||
return locSysInfo.screenWidth > locSysInfo.screenHeight;
|
||||
}
|
||||
},
|
||||
});
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
const landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// NOTE: onDeviceOrientationChange is not supported on this platform
|
||||
// ral.onDeviceOrientationChange((res) => {
|
||||
// if (res.value === 'landscape') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// } else if (res.value === 'landscapeReverse') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
// }
|
||||
// });
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region Accelerometer
|
||||
let _customAccelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
let _innerAccelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
let _needHandleAccelerometerCb = false;
|
||||
minigame.onAccelerometerChange = function (cb): void {
|
||||
if (!_innerAccelerometerCb) {
|
||||
_innerAccelerometerCb = (res): void => {
|
||||
if (!_needHandleAccelerometerCb) {
|
||||
return;
|
||||
}
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1;
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
_customAccelerometerCb?.(resClone);
|
||||
};
|
||||
ral.onAccelerometerChange(_innerAccelerometerCb);
|
||||
}
|
||||
_needHandleAccelerometerCb = true;
|
||||
_customAccelerometerCb = cb;
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb): void {
|
||||
_needHandleAccelerometerCb = false;
|
||||
_customAccelerometerCb = undefined;
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(ral, {
|
||||
onPlay: true, // polyfill for vivo
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: true,
|
||||
});
|
||||
|
||||
// #region SafeArea
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
const locSystemInfo = ral.getSystemInfoSync() as SystemInfo;
|
||||
if (locSystemInfo.safeArea) {
|
||||
return locSystemInfo.safeArea;
|
||||
} else {
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: systemInfo.screenHeight,
|
||||
right: systemInfo.screenWidth,
|
||||
width: systemInfo.screenWidth,
|
||||
height: systemInfo.screenHeight,
|
||||
};
|
||||
}
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./runtime')>());
|
||||
@@ -1,219 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame, SystemInfo } from 'pal/minigame';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils';
|
||||
import { Language } from '../system-info/enum-type';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
//taobao IDE language ("Chinese")
|
||||
//taobao phone language (Andrond: "cn", iPad: 'zh_CN')
|
||||
const languageMap: Record<string, Language> = {
|
||||
Chinese: Language.CHINESE,
|
||||
cn: Language.CHINESE,
|
||||
zh_CN: Language.CHINESE,
|
||||
};
|
||||
|
||||
declare let my: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, my);
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
systemInfo.language = languageMap[systemInfo.language] || systemInfo.language;
|
||||
|
||||
minigame.isDevTool = my.isIDE;
|
||||
|
||||
Object.defineProperty(minigame, 'isLandscape', {
|
||||
get () {
|
||||
const locSystemInfo = minigame.getSystemInfoSync();
|
||||
if (typeof locSystemInfo.deviceOrientation === 'string') {
|
||||
return locSystemInfo.deviceOrientation.startsWith('landscape');
|
||||
} else {
|
||||
return locSystemInfo.screenWidth > locSystemInfo.screenHeight;
|
||||
}
|
||||
},
|
||||
});
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
const landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// NOTE: onDeviceOrientationChange is not supported on this platform
|
||||
// my.onDeviceOrientationChange((res) => {
|
||||
// if (res.value === 'landscape') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// } else if (res.value === 'landscapeReverse') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
// }
|
||||
// });
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
function detectLandscapeSupport (): void {
|
||||
const locSysInfo = minigame.getSystemInfoSync();
|
||||
if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) {
|
||||
if (versionCompare(locSysInfo.version, '10.15.10') < 0) {
|
||||
console.warn('The current Taobao client version does not support Landscape, the minimum requirement is 10.15.10');
|
||||
}
|
||||
}
|
||||
}
|
||||
detectLandscapeSupport();
|
||||
|
||||
// #region Audio
|
||||
const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, {
|
||||
onPlay: true, // Fix: onPlay won't execute.
|
||||
onPause: true, // NOTE: calling pause() twice onPause won't execute twice.
|
||||
onStop: false,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
minigame.createInnerAudioContext = function (): InnerAudioContext {
|
||||
// NOTE: `onCanPlay` is not standard minigame interface,
|
||||
// so here we mark audio as type of any
|
||||
const audio: any = polyfilledCreateInnerAudio();
|
||||
return audio as InnerAudioContext;
|
||||
};
|
||||
// #region Audio
|
||||
|
||||
// #region Font
|
||||
minigame.loadFont = function (url): string {
|
||||
// my.loadFont crash when url is not in user data path
|
||||
return 'Arial';
|
||||
};
|
||||
// #endregion Font
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any): void => {
|
||||
let x: number = res.x;
|
||||
let y: number = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor: number = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
x = -res.y * orientationFactor;
|
||||
y = res.x * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void {
|
||||
if (_accelerometerCb) {
|
||||
my.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
minigame.startAccelerometer = function (res: any): void {
|
||||
if (_accelerometerCb) {
|
||||
my.onAccelerometerChange(_accelerometerCb);
|
||||
} else {
|
||||
// my.startAccelerometer() is not implemented.
|
||||
console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on taobao platform');
|
||||
}
|
||||
};
|
||||
minigame.stopAccelerometer = function (res: any): void {
|
||||
// my.stopAccelerometer() is not implemented.
|
||||
minigame.offAccelerometerChange();
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
// #region SafeArea
|
||||
// It should be a value that is not multiplied by dpr
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
if (typeof systemInfo.safeArea !== 'undefined') {
|
||||
return systemInfo.safeArea;
|
||||
}
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: systemInfo.windowHeight,
|
||||
right: systemInfo.windowWidth,
|
||||
width: systemInfo.windowWidth,
|
||||
height: systemInfo.windowHeight,
|
||||
};
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
declare const $global: any; // global variable on Taobao platform.
|
||||
|
||||
// TODO: A filpY operation will be performed after ReadPixels on Taobao.
|
||||
if (!my.isIDE) {
|
||||
const locCanvas = $global.screencanvas;
|
||||
if (locCanvas) {
|
||||
const originalGetContext = locCanvas.getContext.bind(locCanvas);
|
||||
locCanvas.getContext = function (name, param): any {
|
||||
if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) {
|
||||
Object.assign(param, { enable_flip_y_after_read_pixels: false });
|
||||
const gl = originalGetContext(name, param);
|
||||
adapterGL(gl);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return gl;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return originalGetContext(name, param);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let hasAdapter = false;
|
||||
function adapterGL (gl): void {
|
||||
if (hasAdapter) { return; }
|
||||
hasAdapter = true;
|
||||
|
||||
if (!my.isIDE) {
|
||||
// TODO: Premultiplication is already used on Taobao, do not use premultiplication on the phone.
|
||||
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
|
||||
|
||||
// TODO: adapter gl.getUniformLocation
|
||||
// Android return value: undefined. iOS return value: {ID: -1}.
|
||||
if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') {
|
||||
const originalGetUniformLocation = gl.getUniformLocation.bind(gl);
|
||||
gl.getUniformLocation = function (program, name): any {
|
||||
const glLoc = originalGetUniformLocation(program, name);
|
||||
if (glLoc && glLoc.ID === -1) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return originalGetUniformLocation(program, name);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./taobao')>());
|
||||
@@ -1,227 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame, SystemInfo } from 'pal/minigame';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils';
|
||||
import { Language } from '../system-info/enum-type';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
//taobao IDE language ("Chinese")
|
||||
//taobao phone language (Andrond: "cn", iPad: 'zh_CN')
|
||||
const languageMap: Record<string, Language> = {
|
||||
Chinese: Language.CHINESE,
|
||||
cn: Language.CHINESE,
|
||||
zh_CN: Language.CHINESE,
|
||||
};
|
||||
|
||||
declare let my: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, my);
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
systemInfo.language = languageMap[systemInfo.language] || systemInfo.language;
|
||||
|
||||
minigame.isDevTool = my.isIDE;
|
||||
|
||||
Object.defineProperty(minigame, 'isLandscape', {
|
||||
get () {
|
||||
const windowInfo = my.getWindowInfoSync();
|
||||
return windowInfo.windowWidth > windowInfo.windowHeight;
|
||||
},
|
||||
});
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
const landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// NOTE: onDeviceOrientationChange is not supported on this platform
|
||||
// my.onDeviceOrientationChange((res) => {
|
||||
// if (res.value === 'landscape') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// } else if (res.value === 'landscapeReverse') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
// }
|
||||
// });
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// eslint-disable-next-line func-names
|
||||
function detectLandscapeSupport (): void {
|
||||
const locSysInfo = minigame.getSystemInfoSync();
|
||||
if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) {
|
||||
if (versionCompare(locSysInfo.version, '10.15.10') < 0) {
|
||||
console.warn('The current Taobao client version does not support Landscape, the minimum requirement is 10.15.10');
|
||||
}
|
||||
}
|
||||
}
|
||||
detectLandscapeSupport();
|
||||
|
||||
// #region Audio
|
||||
const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, {
|
||||
onPlay: true, // Fix: onPlay won't execute.
|
||||
onPause: true, // NOTE: calling pause() twice onPause won't execute twice.
|
||||
onStop: false,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.createInnerAudioContext = function (): InnerAudioContext {
|
||||
// NOTE: `onCanPlay` is not standard minigame interface,
|
||||
// so here we mark audio as type of any
|
||||
const audio: any = polyfilledCreateInnerAudio();
|
||||
return audio as InnerAudioContext;
|
||||
};
|
||||
// #region Audio
|
||||
|
||||
// #region Font
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.loadFont = function (url): string {
|
||||
// my.loadFont crash when url is not in user data path
|
||||
return 'Arial';
|
||||
};
|
||||
// #endregion Font
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any): void => {
|
||||
let x: number = res.x;
|
||||
let y: number = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor: number = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
x = -res.y * orientationFactor;
|
||||
y = res.x * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void {
|
||||
if (_accelerometerCb) {
|
||||
my.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.startAccelerometer = function (res: any): void {
|
||||
if (_accelerometerCb) {
|
||||
my.onAccelerometerChange(_accelerometerCb);
|
||||
} else {
|
||||
// my.startAccelerometer() is not implemented.
|
||||
console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on taobao platform');
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.stopAccelerometer = function (res: any): void {
|
||||
// my.stopAccelerometer() is not implemented.
|
||||
minigame.offAccelerometerChange();
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
// #region SafeArea
|
||||
// It should be a value that is not multiplied by dpr
|
||||
minigame.getSafeArea = function (): any {
|
||||
const systemInfo = my.getWindowInfoSync();
|
||||
if (typeof systemInfo.safeArea !== 'undefined') {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return systemInfo.safeArea;
|
||||
}
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: systemInfo.windowHeight,
|
||||
right: systemInfo.windowWidth,
|
||||
width: systemInfo.windowWidth,
|
||||
height: systemInfo.windowHeight,
|
||||
};
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
declare const $global: any; // global variable on Taobao platform.
|
||||
|
||||
// TODO: A filpY operation will be performed after ReadPixels on Taobao.
|
||||
if (!my.isIDE) {
|
||||
const locCanvas = $global.screencanvas;
|
||||
if (locCanvas) {
|
||||
const originalGetContext = locCanvas.getContext.bind(locCanvas);
|
||||
// eslint-disable-next-line func-names
|
||||
locCanvas.getContext = function (name, param): any {
|
||||
if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) {
|
||||
Object.assign(param, { enable_flip_y_after_read_pixels: false });
|
||||
const gl = originalGetContext(name, param);
|
||||
adapterGL(gl);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return gl;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return originalGetContext(name, param);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let hasAdapter = false;
|
||||
function adapterGL (gl): void {
|
||||
if (hasAdapter) { return; }
|
||||
hasAdapter = true;
|
||||
|
||||
if (!my.isIDE) {
|
||||
// TODO: Premultiplication is already used on Taobao, do not use premultiplication on the phone.
|
||||
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
|
||||
|
||||
// TODO: adapter gl.getUniformLocation
|
||||
// Android return value: undefined. iOS return value: {ID: -1}.
|
||||
if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') {
|
||||
const originalGetUniformLocation = gl.getUniformLocation.bind(gl);
|
||||
// eslint-disable-next-line func-names
|
||||
gl.getUniformLocation = function (program, name): any {
|
||||
const glLoc = originalGetUniformLocation(program, name);
|
||||
if (glLoc && glLoc.ID === -1) {
|
||||
return undefined;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return originalGetUniformLocation(program, name);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
minigame.loadSubpackage = my.loadSubPackage.bind(my);
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./taobao_minigame')>());
|
||||
@@ -1,254 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame, SystemInfo, DeviceInfo, WindowInfo, AppBaseInfo, SystemSetting, AppAuthorizeSetting } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils';
|
||||
import { sys, systemEvent } from '../../typedoc-index';
|
||||
|
||||
declare let wx: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, wx);
|
||||
|
||||
// #region platform related
|
||||
minigame.wx = {};
|
||||
minigame.wx.onKeyDown = wx.onKeyDown?.bind(wx);
|
||||
minigame.wx.onKeyUp = wx.onKeyUp?.bind(wx);
|
||||
minigame.wx.onMouseDown = wx.onMouseDown?.bind(wx);
|
||||
minigame.wx.onMouseMove = wx.onMouseMove?.bind(wx);
|
||||
minigame.wx.onMouseUp = wx.onMouseUp?.bind(wx);
|
||||
minigame.wx.onWheel = wx.onWheel?.bind(wx);
|
||||
// #endregion platform related
|
||||
|
||||
// This interface is not supported in versions below 2.25.3.
|
||||
if (minigame.getSystemSetting === undefined) {
|
||||
minigame.getSystemSetting = function (): SystemSetting {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
bluetoothEnabled: systemInfo.bluetoothEnabled,
|
||||
locationEnabled: systemInfo.locationEnabled,
|
||||
wifiEnabled: systemInfo.wifiEnabled,
|
||||
deviceOrientation: systemInfo.deviceOrientation,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
if (minigame.getAppAuthorizeSetting === undefined) {
|
||||
minigame.getAppAuthorizeSetting = function (): AppAuthorizeSetting {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
albumAuthorized: systemInfo.albumAuthorized === undefined ? undefined : ((systemInfo.albumAuthorized) ? 'authorized' : 'denied'),
|
||||
bluetoothAuthorized: systemInfo.bluetoothAuthorized === undefined ? undefined
|
||||
: ((systemInfo.bluetoothAuthorized) ? 'authorized' : 'denied'),
|
||||
cameraAuthorized: systemInfo.cameraAuthorized === undefined ? undefined
|
||||
: ((systemInfo.cameraAuthorized) ? 'authorized' : 'denied'),
|
||||
locationAuthorized: systemInfo.locationAuthorized === undefined ? undefined
|
||||
: ((systemInfo.locationAuthorized) ? 'authorized' : 'denied'),
|
||||
locationReducedAccuracy: systemInfo.locationReducedAccuracy === undefined ? undefined : (systemInfo.locationReducedAccuracy),
|
||||
microphoneAuthorized: systemInfo.microphoneAuthorized === undefined ? undefined
|
||||
: ((systemInfo.microphoneAuthorized) ? 'authorized' : 'denied'),
|
||||
notificationAuthorized: systemInfo.notificationAuthorized === undefined ? undefined
|
||||
: ((systemInfo.notificationAuthorized) ? 'authorized' : 'denied'),
|
||||
notificationAlertAuthorized: systemInfo.notificationAlertAuthorized === undefined ? undefined
|
||||
: ((systemInfo.notificationAlertAuthorized) ? 'authorized' : 'denied'),
|
||||
notificationBadgeAuthorized: systemInfo.notificationBadgeAuthorized === undefined ? undefined
|
||||
: ((systemInfo.notificationBadgeAuthorized) ? 'authorized' : 'denied'),
|
||||
notificationSoundAuthorized: systemInfo.notificationSoundAuthorized === undefined ? undefined
|
||||
: ((systemInfo.notificationSoundAuthorized) ? 'authorized' : 'denied'),
|
||||
phoneCalendarAuthorized: systemInfo.phoneCalendarAuthorized === undefined ? undefined
|
||||
: ((systemInfo.phoneCalendarAuthorized) ? 'authorized' : 'denied'),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
if (minigame.getDeviceInfo === undefined) {
|
||||
minigame.getDeviceInfo = function (): DeviceInfo {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
abi: systemInfo.abi,
|
||||
deviceAbi: systemInfo.deviceAbi,
|
||||
benchmarkLevel: systemInfo.benchmarkLevel,
|
||||
brand: systemInfo.brand,
|
||||
model: systemInfo.model,
|
||||
system: systemInfo.system,
|
||||
platform: systemInfo.platform,
|
||||
cpuType: systemInfo.cpuType,
|
||||
memorySize: systemInfo.memorySize,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
if (minigame.getWindowInfo === undefined) {
|
||||
minigame.getWindowInfo = function (): WindowInfo {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
pixelRatio: systemInfo.pixelRatio,
|
||||
screenWidth: systemInfo.screenWidth,
|
||||
screenHeight: systemInfo.screenHeight,
|
||||
windowWidth: systemInfo.windowWidth,
|
||||
windowHeight: systemInfo.windowHeight,
|
||||
statusBarHeight: systemInfo.statusBarHeight,
|
||||
safeArea: systemInfo.safeArea,
|
||||
screenTop: systemInfo.screenTop,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
if (minigame.getAppBaseInfo === undefined) {
|
||||
minigame.getAppBaseInfo = function (): AppBaseInfo {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
SDKVersion: systemInfo.SDKVersion,
|
||||
enableDebug: systemInfo.enableDebug,
|
||||
host: systemInfo.host, // not
|
||||
language: systemInfo.language,
|
||||
version: systemInfo.version,
|
||||
theme: systemInfo.theme,
|
||||
mode: systemInfo.mode,
|
||||
fontSizeScaleFactor: systemInfo.fontSizeScaleFactor,
|
||||
fontSizeSetting: systemInfo.fontSizeSetting,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const devideInfo = minigame.getDeviceInfo();
|
||||
|
||||
minigame.isDevTool = (devideInfo.platform === 'devtools');
|
||||
// NOTE: size and orientation info is wrong at the init phase, especially on iOS device
|
||||
Object.defineProperty(minigame, 'isLandscape', {
|
||||
get () {
|
||||
const locSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
if (typeof locSystemInfo.deviceOrientation === 'string') {
|
||||
return locSystemInfo.deviceOrientation.startsWith('landscape');
|
||||
} else {
|
||||
return locSystemInfo.screenWidth > locSystemInfo.screenHeight;
|
||||
}
|
||||
},
|
||||
});
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
let landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
if (devideInfo.platform.toLocaleLowerCase() !== 'android') {
|
||||
// onDeviceOrientationChange doesn't work well on Android.
|
||||
// see this issue: https://developers.weixin.qq.com/community/minigame/doc/000482138dc460e56cfaa5cb15bc00
|
||||
wx.onDeviceOrientationChange((res) => {
|
||||
if (res.value === 'landscape') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
} else if (res.value === 'landscapeReverse') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
}
|
||||
});
|
||||
}
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback): void {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any): void => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback): void {
|
||||
if (_accelerometerCb) {
|
||||
wx.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
minigame.startAccelerometer = function (res: any): void {
|
||||
if (_accelerometerCb) {
|
||||
wx.onAccelerometerChange(_accelerometerCb);
|
||||
}
|
||||
wx.startAccelerometer(res);
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, {
|
||||
onPlay: true,
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
|
||||
// #region SafeArea
|
||||
// FIX_ME: wrong safe area when orientation is landscape left
|
||||
minigame.getSafeArea = function (): SafeArea {
|
||||
const windowInfo: WindowInfo = minigame.getWindowInfo();
|
||||
let safeArea = windowInfo.safeArea;
|
||||
if (!safeArea) {
|
||||
safeArea = {
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: windowInfo.screenHeight,
|
||||
right: windowInfo.screenWidth,
|
||||
width: windowInfo.screenWidth,
|
||||
height: windowInfo.screenHeight,
|
||||
};
|
||||
}
|
||||
return safeArea;
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
declare const canvas: any; // defined in global
|
||||
|
||||
// HACK: adapt GL.useProgram: use program not supported to unbind program on pc end
|
||||
const appBaseInfo = minigame.getAppBaseInfo();
|
||||
if (devideInfo.platform === 'windows' && versionCompare(appBaseInfo.SDKVersion, '2.16.0') < 0) {
|
||||
const locCanvas = canvas;
|
||||
if (locCanvas) {
|
||||
const webglRC = locCanvas.getContext('webgl');
|
||||
const originalUseProgram = webglRC.useProgram.bind(webglRC);
|
||||
webglRC.useProgram = function (program): void {
|
||||
if (program) {
|
||||
originalUseProgram(program);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./wechat')>());
|
||||
@@ -1,195 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame, SystemInfo } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils';
|
||||
|
||||
declare let wx: any;
|
||||
// NOTE: getApp is defined on wechat miniprogram platform
|
||||
declare const getApp: any;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error can't init minigame when it's declared
|
||||
const minigame: IMiniGame = {};
|
||||
cloneObject(minigame, wx);
|
||||
|
||||
// #region platform related
|
||||
minigame.wx = {};
|
||||
minigame.wx.onKeyDown = wx.onKeyDown?.bind(wx);
|
||||
minigame.wx.onKeyUp = wx.onKeyUp?.bind(wx);
|
||||
minigame.wx.onMouseDown = wx.onMouseDown?.bind(wx);
|
||||
minigame.wx.onMouseMove = wx.onMouseMove?.bind(wx);
|
||||
minigame.wx.onMouseUp = wx.onMouseUp?.bind(wx);
|
||||
minigame.wx.onWheel = wx.onWheel?.bind(wx);
|
||||
// #endregion platform related
|
||||
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
minigame.isDevTool = (systemInfo.platform === 'devtools');
|
||||
// NOTE: size and orientation info is wrong at the init phase, especially on iOS device
|
||||
Object.defineProperty(minigame, 'isLandscape', {
|
||||
get () {
|
||||
const locSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
if (typeof locSystemInfo.deviceOrientation === 'string') {
|
||||
return locSystemInfo.deviceOrientation.startsWith('landscape');
|
||||
} else {
|
||||
return locSystemInfo.screenWidth > locSystemInfo.screenHeight;
|
||||
}
|
||||
},
|
||||
});
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
let landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
if (systemInfo.platform.toLocaleLowerCase() !== 'android') {
|
||||
// onDeviceOrientationChange doesn't work well on Android.
|
||||
// see this issue: https://developers.weixin.qq.com/community/minigame/doc/000482138dc460e56cfaa5cb15bc00
|
||||
wx.onDeviceOrientationChange((res) => {
|
||||
if (res.value === 'landscape') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
} else if (res.value === 'landscapeReverse') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
}
|
||||
});
|
||||
}
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = (cb: AccelerometerChangeCallback): void => {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any): void => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
minigame.offAccelerometerChange = (cb?: AccelerometerChangeCallback): void => {
|
||||
if (_accelerometerCb) {
|
||||
wx.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
minigame.startAccelerometer = (res: any): void => {
|
||||
if (_accelerometerCb) {
|
||||
wx.onAccelerometerChange(_accelerometerCb);
|
||||
}
|
||||
wx.startAccelerometer(res);
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, {
|
||||
onPlay: true,
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
|
||||
// #region SafeArea
|
||||
// FIX_ME: wrong safe area when orientation is landscape left
|
||||
minigame.getSafeArea = (): SafeArea => {
|
||||
const locSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
let safeArea = locSystemInfo.safeArea;
|
||||
if (!safeArea) {
|
||||
safeArea = {
|
||||
left: 0,
|
||||
top: 0,
|
||||
bottom: systemInfo.screenHeight,
|
||||
right: systemInfo.screenWidth,
|
||||
width: systemInfo.screenWidth,
|
||||
height: systemInfo.screenHeight,
|
||||
};
|
||||
}
|
||||
return safeArea;
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
// HACK: adapt GL.useProgram: use program not supported to unbind program on pc end
|
||||
if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, '2.16.0') < 0) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error canvas defined in global
|
||||
const locCanvas = canvas;
|
||||
if (locCanvas) {
|
||||
const webglRC = locCanvas.getContext('webgl');
|
||||
const originalUseProgram = webglRC.useProgram.bind(webglRC);
|
||||
webglRC.useProgram = (program): void => {
|
||||
if (program) {
|
||||
originalUseProgram(program);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// HACK: adapt gl.texSubImage2D: gl.texSubImage2D do not support 2d canvas in wechat miniprogram
|
||||
const gl = getApp().GameGlobal.canvas.getContext('webgl');
|
||||
const oldTexSubImage2D = gl.texSubImage2D;
|
||||
gl.texSubImage2D = (...args: any[]): void => {
|
||||
if (args.length === 7) {
|
||||
const canvas = args[6];
|
||||
if (typeof canvas.type !== 'undefined' && canvas.type === 'canvas') {
|
||||
const ctx = canvas.getContext('2d');
|
||||
const texOffsetX = args[2];
|
||||
const texOffsetY = args[3];
|
||||
const imgData = ctx.getImageData(texOffsetX, texOffsetY, canvas.width, canvas.height);
|
||||
oldTexSubImage2D.call(
|
||||
gl,
|
||||
args[0],
|
||||
args[1],
|
||||
texOffsetX,
|
||||
texOffsetY,
|
||||
canvas.width,
|
||||
canvas.height,
|
||||
args[4],
|
||||
args[5],
|
||||
new Uint8Array(imgData.data as ArrayBuffer),
|
||||
);
|
||||
} else {
|
||||
oldTexSubImage2D.apply(gl, args);
|
||||
}
|
||||
} else {
|
||||
oldTexSubImage2D.apply(gl, args);
|
||||
}
|
||||
};
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./wechat_mini_program')>());
|
||||
@@ -1,156 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { IMiniGame } from 'pal/minigame';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill } from '../utils';
|
||||
import { warn } from '../../cocos/core/platform/debug';
|
||||
|
||||
declare let qg: any;
|
||||
|
||||
const minigame: IMiniGame = {} as IMiniGame;
|
||||
cloneObject(minigame, qg);
|
||||
|
||||
// #region SystemInfo
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
minigame.isDevTool = false;
|
||||
|
||||
minigame.isLandscape = systemInfo.screenWidth > systemInfo.screenHeight;
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
const landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// NOTE: onDeviceOrientationChange is not supported on this platform
|
||||
// qg.onDeviceOrientationChange((res) => {
|
||||
// if (res.value === 'landscape') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
// } else if (res.value === 'landscapeReverse') {
|
||||
// landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
// }
|
||||
// });
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region TouchEvent
|
||||
minigame.onTouchStart = (cb): void => {
|
||||
window.canvas.ontouchstart = cb;
|
||||
};
|
||||
minigame.onTouchMove = (cb): void => {
|
||||
window.canvas.ontouchmove = cb;
|
||||
};
|
||||
minigame.onTouchEnd = (cb): void => {
|
||||
window.canvas.ontouchend = cb;
|
||||
};
|
||||
minigame.onTouchCancel = (cb): void => {
|
||||
window.canvas.ontouchcancel = cb;
|
||||
};
|
||||
// #endregion TouchEvent
|
||||
|
||||
// // Keyboard
|
||||
// globalAdapter.showKeyboard = function (res) {
|
||||
// res.confirmHold = true; // HACK: confirmHold not working on Xiaomi platform
|
||||
// qg.showKeyboard(res);
|
||||
// };
|
||||
|
||||
// #region Accelerometer
|
||||
let _customAccelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
let _innerAccelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = (cb: AccelerometerChangeCallback): void => {
|
||||
// qg.offAccelerometerChange() is not supported.
|
||||
// so we can only register AccelerometerChange callback, but can't unregister.
|
||||
if (!_innerAccelerometerCb) {
|
||||
_innerAccelerometerCb = (res: any): void => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const standardFactor = -0.1;
|
||||
x *= standardFactor;
|
||||
y *= standardFactor;
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
_customAccelerometerCb?.(resClone);
|
||||
};
|
||||
qg.onAccelerometerChange(_innerAccelerometerCb);
|
||||
}
|
||||
_customAccelerometerCb = cb;
|
||||
};
|
||||
minigame.offAccelerometerChange = (cb?: AccelerometerChangeCallback): void => {
|
||||
// qg.offAccelerometerChange() is not supported.
|
||||
_customAccelerometerCb = undefined;
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
// #region InnerAudioContext
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(qg, {
|
||||
onPlay: true,
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: false,
|
||||
});
|
||||
const originalCreateInnerAudioContext = minigame.createInnerAudioContext;
|
||||
minigame.createInnerAudioContext = (): InnerAudioContext => {
|
||||
const audioContext = originalCreateInnerAudioContext.call(minigame);
|
||||
const originalStop = audioContext.stop;
|
||||
Object.defineProperty(audioContext, 'stop', {
|
||||
configurable: true,
|
||||
value (): void {
|
||||
// NOTE: stop won't seek to 0 when audio is paused on Xiaomi platform.
|
||||
audioContext.seek(0);
|
||||
originalStop.call(audioContext);
|
||||
},
|
||||
});
|
||||
return audioContext;
|
||||
};
|
||||
// #endregion InnerAudioContext
|
||||
|
||||
// #region SafeArea
|
||||
minigame.getSafeArea = (): SafeArea => {
|
||||
warn('getSafeArea is not supported on this platform');
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
return {
|
||||
top: 0,
|
||||
left: 0,
|
||||
bottom: systemInfo.screenHeight,
|
||||
right: systemInfo.screenWidth,
|
||||
width: systemInfo.screenWidth,
|
||||
height: systemInfo.screenHeight,
|
||||
};
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
export { minigame };
|
||||
|
||||
checkPalIntegrity<typeof import('pal/minigame')>(withImpl<typeof import('./xiaomi')>());
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { assertIsTrue } from '../../cocos/core/data/utils/asserts';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
export class Pacer {
|
||||
private _rafHandle = 0;
|
||||
private _onTick: (() => void) | null = null;
|
||||
private declare _updateCallback: () => void;
|
||||
private _targetFrameRate = 60;
|
||||
private _isPlaying = false;
|
||||
constructor () {
|
||||
this._updateCallback = (): void => {
|
||||
if (this._isPlaying) {
|
||||
this._rafHandle = requestAnimationFrame(this._updateCallback);
|
||||
}
|
||||
if (this._onTick) {
|
||||
this._onTick();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get targetFrameRate (): number {
|
||||
return this._targetFrameRate;
|
||||
}
|
||||
|
||||
set targetFrameRate (val: number) {
|
||||
if (this._targetFrameRate !== val) {
|
||||
assertIsTrue(val > 0);
|
||||
this._targetFrameRate = val;
|
||||
minigame.setPreferredFramesPerSecond(this._targetFrameRate);
|
||||
if (this._isPlaying) {
|
||||
this.stop();
|
||||
this.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set onTick (val: (() => void) | null) {
|
||||
this._onTick = val;
|
||||
}
|
||||
|
||||
get onTick (): (() => void) | null {
|
||||
return this._onTick;
|
||||
}
|
||||
|
||||
start (): void {
|
||||
if (this._isPlaying) return;
|
||||
this._rafHandle = requestAnimationFrame(this._updateCallback);
|
||||
this._isPlaying = true;
|
||||
}
|
||||
|
||||
stop (): void {
|
||||
if (!this._isPlaying) return;
|
||||
cancelAnimationFrame(this._rafHandle);
|
||||
this._rafHandle = 0;
|
||||
this._isPlaying = false;
|
||||
}
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/pacer')>(withImpl<typeof import('./pacer-minigame')>());
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { assertIsTrue } from '../../cocos/core/data/utils/asserts';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
declare const jsb: any;
|
||||
export class Pacer {
|
||||
private _rafHandle = 0;
|
||||
private _onTick: (() => void) | null = null;
|
||||
private _targetFrameRate = 60;
|
||||
private _isPlaying = false;
|
||||
private declare _updateCallback: () => void;
|
||||
constructor () {
|
||||
this._updateCallback = (): void => {
|
||||
if (this._isPlaying) {
|
||||
this._rafHandle = requestAnimationFrame(this._updateCallback);
|
||||
}
|
||||
if (this._onTick) {
|
||||
this._onTick();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
get targetFrameRate (): number {
|
||||
return this._targetFrameRate;
|
||||
}
|
||||
|
||||
set targetFrameRate (val: number) {
|
||||
if (this._targetFrameRate !== val) {
|
||||
assertIsTrue(val > 0);
|
||||
this._targetFrameRate = val;
|
||||
jsb.setPreferredFramesPerSecond(this._targetFrameRate);
|
||||
if (this._isPlaying) {
|
||||
this.stop();
|
||||
this.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set onTick (val: (() => void) | null) {
|
||||
this._onTick = val;
|
||||
}
|
||||
|
||||
get onTick (): (() => void) | null {
|
||||
return this._onTick;
|
||||
}
|
||||
|
||||
start (): void {
|
||||
if (this._isPlaying) return;
|
||||
this._rafHandle = requestAnimationFrame(this._updateCallback);
|
||||
this._isPlaying = true;
|
||||
}
|
||||
|
||||
stop (): void {
|
||||
if (!this._isPlaying) return;
|
||||
cancelAnimationFrame(this._rafHandle);
|
||||
this._rafHandle = 0;
|
||||
this._isPlaying = false;
|
||||
}
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/pacer')>(withImpl<typeof import('./pacer-native')>());
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
const FRAME_RESET_TIME = 2000;
|
||||
|
||||
export class Pacer {
|
||||
private _stHandle = 0;
|
||||
private _onTick: (() => void) | null = null;
|
||||
private _targetFrameRate = 60;
|
||||
private _frameTime = 0;
|
||||
private _startTime = 0;
|
||||
private _isPlaying = false;
|
||||
|
||||
constructor () {
|
||||
this._isPlaying = false;
|
||||
}
|
||||
|
||||
get targetFrameRate (): number {
|
||||
return this._targetFrameRate;
|
||||
}
|
||||
|
||||
set targetFrameRate (val: number) {
|
||||
if (this._targetFrameRate !== val) {
|
||||
this._targetFrameRate = val;
|
||||
this._frameTime = 1000 / this._targetFrameRate;
|
||||
if (this._isPlaying) {
|
||||
this.stop();
|
||||
this.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set onTick (val: (() => void) | null) {
|
||||
this._onTick = val;
|
||||
}
|
||||
|
||||
get onTick (): (() => void) | null {
|
||||
return this._onTick;
|
||||
}
|
||||
|
||||
start (): void {
|
||||
if (this._isPlaying) return;
|
||||
const updateCallback = (): void => {
|
||||
if (this._isPlaying) {
|
||||
this._stHandle = this._stTime(updateCallback);
|
||||
}
|
||||
if (this._onTick) {
|
||||
this._onTick();
|
||||
}
|
||||
};
|
||||
this._startTime = performance.now();
|
||||
this._stHandle = this._stTime(updateCallback);
|
||||
|
||||
this._isPlaying = true;
|
||||
}
|
||||
|
||||
stop (): void {
|
||||
if (!this._isPlaying) return;
|
||||
this._ctTime(this._stHandle);
|
||||
this._stHandle = 0;
|
||||
this._isPlaying = false;
|
||||
}
|
||||
|
||||
private _stTime (callback: () => void): number {
|
||||
const currTime = performance.now();
|
||||
const elapseTime = Math.max(0, currTime - this._startTime);
|
||||
const timeToCall = Math.max(0, this._frameTime - elapseTime);
|
||||
return setTimeout(callback, timeToCall);
|
||||
}
|
||||
|
||||
private _ctTime (id: number | undefined): void {
|
||||
clearTimeout(id);
|
||||
}
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/pacer')>(withImpl<typeof import('./pacer-web')>());
|
||||
@@ -1,151 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR, USE_XR } from 'internal:constants';
|
||||
import { assertIsTrue } from '../../cocos/core/data/utils/asserts';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
const FRAME_RESET_TIME = 2000;
|
||||
|
||||
export class Pacer {
|
||||
private _stHandle = 0;
|
||||
private _onTick: (() => void) | null = null;
|
||||
private _targetFrameRate = 60;
|
||||
private _frameTime = 0;
|
||||
private _startTime = 0;
|
||||
private _isPlaying = false;
|
||||
private _frameCount = 0;
|
||||
private _callback: (() => void) | null = null;
|
||||
private _rAF: typeof requestAnimationFrame;
|
||||
private _cAF: typeof cancelAnimationFrame;
|
||||
|
||||
constructor () {
|
||||
this._frameTime = 1000 / this._targetFrameRate;
|
||||
this._rAF = window.requestAnimationFrame
|
||||
|| window.webkitRequestAnimationFrame
|
||||
|| window.mozRequestAnimationFrame
|
||||
|| window.oRequestAnimationFrame
|
||||
|| window.msRequestAnimationFrame;
|
||||
this._cAF = window.cancelAnimationFrame
|
||||
|| window.cancelRequestAnimationFrame
|
||||
|| window.msCancelRequestAnimationFrame
|
||||
|| window.mozCancelRequestAnimationFrame
|
||||
|| window.oCancelRequestAnimationFrame
|
||||
|| window.webkitCancelRequestAnimationFrame
|
||||
|| window.msCancelAnimationFrame
|
||||
|| window.mozCancelAnimationFrame
|
||||
|| window.webkitCancelAnimationFrame
|
||||
|| window.ocancelAnimationFrame;
|
||||
}
|
||||
|
||||
get targetFrameRate (): number {
|
||||
return this._targetFrameRate;
|
||||
}
|
||||
|
||||
set targetFrameRate (val: number) {
|
||||
if (this._targetFrameRate !== val) {
|
||||
assertIsTrue(val > 0);
|
||||
this._targetFrameRate = val;
|
||||
this._frameTime = 1000 / this._targetFrameRate;
|
||||
if (this._isPlaying) {
|
||||
this.stop();
|
||||
this.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
set onTick (val: (() => void) | null) {
|
||||
this._onTick = val;
|
||||
}
|
||||
|
||||
get onTick (): (() => void) | null {
|
||||
return this._onTick;
|
||||
}
|
||||
|
||||
start (): void {
|
||||
if (this._isPlaying) return;
|
||||
const recordStartTime = EDITOR || this._rAF === undefined || (USE_XR && globalThis.__globalXR?.isWebXR);
|
||||
const updateCallback = (): void => {
|
||||
if (recordStartTime) this._startTime = performance.now();
|
||||
if (this._isPlaying) {
|
||||
this._stHandle = this._stTime(updateCallback);
|
||||
}
|
||||
if (this._onTick) {
|
||||
this._onTick();
|
||||
}
|
||||
};
|
||||
this._startTime = performance.now();
|
||||
this._stHandle = this._stTime(updateCallback);
|
||||
|
||||
this._isPlaying = true;
|
||||
this._frameCount = 0;
|
||||
}
|
||||
|
||||
stop (): void {
|
||||
if (!this._isPlaying) return;
|
||||
this._ctTime(this._stHandle);
|
||||
this._stHandle = 0;
|
||||
this._isPlaying = false;
|
||||
this._frameCount = 0;
|
||||
}
|
||||
|
||||
_handleRAF = (stamp: number): void => {
|
||||
const currTime = performance.now();
|
||||
const elapseTime = currTime - this._startTime;
|
||||
const elapseFrame = Math.floor(elapseTime / this._frameTime);
|
||||
if (elapseFrame < 0) {
|
||||
this._startTime = currTime;
|
||||
this._frameCount = 0;
|
||||
}
|
||||
if (elapseFrame < this._frameCount) {
|
||||
this._stHandle = this._rAF.call(window, this._handleRAF);
|
||||
} else {
|
||||
this._frameCount = elapseFrame + 1;
|
||||
if (this._callback) {
|
||||
this._callback();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private _stTime (callback: () => void): number {
|
||||
if (EDITOR || this._rAF === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) {
|
||||
const currTime = performance.now();
|
||||
const elapseTime = Math.max(0, currTime - this._startTime);
|
||||
const timeToCall = Math.max(0, this._frameTime - elapseTime);
|
||||
return setTimeout(callback, timeToCall);
|
||||
}
|
||||
this._callback = callback;
|
||||
return this._rAF.call(window, this._handleRAF);
|
||||
}
|
||||
|
||||
private _ctTime (id: number | undefined): void {
|
||||
if (EDITOR || this._cAF === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) {
|
||||
clearTimeout(id);
|
||||
} else if (id) {
|
||||
this._cAF.call(window, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/pacer')>(withImpl<typeof import('./pacer-web')>());
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export * from './orientation';
|
||||
export * from './screen-event';
|
||||
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum Orientation {
|
||||
PORTRAIT = 1,
|
||||
PORTRAIT_UPSIDE_DOWN = PORTRAIT << 1,
|
||||
LANDSCAPE_LEFT = PORTRAIT << 2,
|
||||
LANDSCAPE_RIGHT = PORTRAIT << 3,
|
||||
LANDSCAPE = LANDSCAPE_LEFT | LANDSCAPE_RIGHT,
|
||||
AUTO = PORTRAIT | LANDSCAPE,
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export type PalScreenEvent = 'window-resize' | 'orientation-change' | 'fullscreen-change';
|
||||
@@ -1,183 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ALIPAY, BYTEDANCE, TAOBAO_MINIGAME, VIVO, WECHAT } from 'internal:constants';
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { IScreenOptions, SafeAreaEdge } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { getError, warnID } from '../../../cocos/core/platform/debug';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { Size } from '../../../cocos/core/math';
|
||||
import { OS } from '../../system-info/enum-type';
|
||||
import { Orientation } from '../enum-type';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
|
||||
declare const my: any;
|
||||
|
||||
// HACK: In some platform like CocosPlay or Alipay iOS end
|
||||
// the windowSize need to rotate when init screenAdapter if it's landscape
|
||||
let rotateLandscape = false;
|
||||
try {
|
||||
if (ALIPAY) {
|
||||
if (systemInfo.os === OS.IOS && !minigame.isDevTool) {
|
||||
// TODO: use pal/fs
|
||||
// issue: https://github.com/cocos/cocos-engine/issues/14647
|
||||
const fs = my.getFileSystemManager();
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
const screenOrientation = JSON.parse(fs.readFileSync({
|
||||
filePath: 'game.json',
|
||||
encoding: 'utf8',
|
||||
}).data).screenOrientation;
|
||||
rotateLandscape = (screenOrientation === 'landscape');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
class ScreenAdapter extends EventTarget {
|
||||
public isFrameRotated = false;
|
||||
public handleResizeEvent = true;
|
||||
|
||||
public get supportFullScreen (): boolean {
|
||||
return false;
|
||||
}
|
||||
public get isFullScreen (): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
public get devicePixelRatio (): number {
|
||||
if (WECHAT) {
|
||||
const sysInfo = minigame.getWindowInfo();
|
||||
return sysInfo.pixelRatio;
|
||||
}
|
||||
const sysInfo = minigame.getSystemInfoSync();
|
||||
return sysInfo.pixelRatio;
|
||||
}
|
||||
|
||||
public get windowSize (): Size {
|
||||
let sysInfo;
|
||||
if (WECHAT) {
|
||||
sysInfo = minigame.getWindowInfo();
|
||||
} else {
|
||||
sysInfo = minigame.getSystemInfoSync();
|
||||
}
|
||||
|
||||
const dpr = this.devicePixelRatio;
|
||||
let screenWidth = sysInfo.windowWidth;
|
||||
let screenHeight = sysInfo.windowHeight;
|
||||
if (BYTEDANCE) {
|
||||
screenWidth = sysInfo.screenWidth;
|
||||
screenHeight = sysInfo.screenHeight;
|
||||
} else if (ALIPAY && rotateLandscape && screenWidth < screenHeight) {
|
||||
const temp = screenWidth;
|
||||
screenWidth = screenHeight;
|
||||
screenHeight = temp;
|
||||
} else if (TAOBAO_MINIGAME) {
|
||||
const windowInfo = my.getWindowInfoSync();
|
||||
if (windowInfo) {
|
||||
screenWidth = windowInfo.windowWidth;
|
||||
screenHeight = windowInfo.windowHeight;
|
||||
}
|
||||
}
|
||||
return new Size(screenWidth * dpr, screenHeight * dpr);
|
||||
}
|
||||
public set windowSize (size: Size) {
|
||||
warnID(1221);
|
||||
}
|
||||
|
||||
public get resolution (): Size {
|
||||
const windowSize = this.windowSize;
|
||||
const resolutionScale = this.resolutionScale;
|
||||
return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
|
||||
}
|
||||
public get resolutionScale (): number {
|
||||
return this._resolutionScale;
|
||||
}
|
||||
public set resolutionScale (value: number) {
|
||||
if (value === this._resolutionScale) {
|
||||
return;
|
||||
}
|
||||
this._resolutionScale = value;
|
||||
this._cbToUpdateFrameBuffer?.();
|
||||
}
|
||||
|
||||
public get orientation (): Orientation {
|
||||
return minigame.orientation;
|
||||
}
|
||||
public set orientation (value: Orientation) {
|
||||
warnID(1221);
|
||||
}
|
||||
|
||||
public get safeAreaEdge (): SafeAreaEdge {
|
||||
const minigameSafeArea = minigame.getSafeArea();
|
||||
const windowSize = this.windowSize;
|
||||
// NOTE: safe area info on vivo platform is in physical pixel.
|
||||
// No need to multiply with DPR.
|
||||
const dpr = VIVO ? 1 : this.devicePixelRatio;
|
||||
const topEdge = minigameSafeArea.top * dpr;
|
||||
const bottomEdge = windowSize.height - minigameSafeArea.bottom * dpr;
|
||||
const leftEdge = minigameSafeArea.left * dpr;
|
||||
const rightEdge = windowSize.width - minigameSafeArea.right * dpr;
|
||||
return {
|
||||
top: topEdge,
|
||||
bottom: bottomEdge,
|
||||
left: leftEdge,
|
||||
right: rightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
public get isProportionalToFrame (): boolean {
|
||||
return this._isProportionalToFrame;
|
||||
}
|
||||
public set isProportionalToFrame (v: boolean) { }
|
||||
|
||||
private _cbToUpdateFrameBuffer?: () => void;
|
||||
private _resolutionScale = 1;
|
||||
private _isProportionalToFrame = false;
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
minigame.onWindowResize?.(() => {
|
||||
this.emit('window-resize', this.windowSize.width, this.windowSize.height);
|
||||
});
|
||||
}
|
||||
|
||||
public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void {
|
||||
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
|
||||
this._cbToUpdateFrameBuffer();
|
||||
}
|
||||
|
||||
public requestFullScreen (): Promise<void> {
|
||||
return Promise.reject(new Error(getError(9008)));
|
||||
}
|
||||
public exitFullScreen (): Promise<void> {
|
||||
return Promise.reject(new Error(getError(9009)));
|
||||
}
|
||||
}
|
||||
|
||||
export const screenAdapter = new ScreenAdapter();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/screen-adapter')>(withImpl<typeof import('./screen-adapter')>());
|
||||
@@ -1,174 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR } from 'internal:constants';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { Size } from '../../../cocos/core/math';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { Orientation } from '../enum-type';
|
||||
import { warn, warnID } from '../../../cocos/core/platform/debug';
|
||||
|
||||
export interface SafeAreaEdge {
|
||||
top: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
right: number;
|
||||
}
|
||||
|
||||
export type ConfigOrientation = 'auto' | 'landscape' | 'portrait';
|
||||
|
||||
export interface IScreenOptions {
|
||||
/**
|
||||
* Orientation options from editor builder.
|
||||
*/
|
||||
configOrientation: ConfigOrientation;
|
||||
/**
|
||||
* Determine whether the game frame exact fits the screen.
|
||||
* Now it only works on Web platform.
|
||||
*/
|
||||
exactFitScreen: boolean,
|
||||
/**
|
||||
* Determine whether use headless renderer, which means do not support some screen operations.
|
||||
*/
|
||||
isHeadlessMode: boolean;
|
||||
}
|
||||
|
||||
// these value is defined in the native layer
|
||||
const orientationMap: Record<string, Orientation> = {
|
||||
0: Orientation.PORTRAIT,
|
||||
'-90': Orientation.LANDSCAPE_LEFT,
|
||||
90: Orientation.LANDSCAPE_RIGHT,
|
||||
180: Orientation.PORTRAIT_UPSIDE_DOWN,
|
||||
};
|
||||
|
||||
class ScreenAdapter extends EventTarget {
|
||||
public isFrameRotated = false;
|
||||
public handleResizeEvent = true;
|
||||
|
||||
public get supportFullScreen (): boolean {
|
||||
return false;
|
||||
}
|
||||
public get isFullScreen (): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
public get devicePixelRatio (): number {
|
||||
return jsb.device.getDevicePixelRatio() || 1;
|
||||
}
|
||||
|
||||
public get windowSize (): Size {
|
||||
const dpr = this.devicePixelRatio;
|
||||
// NOTE: fix precision issue on Metal render end.
|
||||
const width = jsb.window.innerWidth as number;
|
||||
const height = jsb.window.innerHeight as number;
|
||||
// NOTE: fix precision issue on Metal render end.
|
||||
const roundWidth = Math.round(width);
|
||||
const roundHeight = Math.round(height);
|
||||
return new Size(roundWidth * dpr, roundHeight * dpr);
|
||||
}
|
||||
public set windowSize (size: Size) {
|
||||
warn('Setting window size is not supported yet.');
|
||||
}
|
||||
|
||||
public get resolution (): Size {
|
||||
const windowSize = this.windowSize;
|
||||
const resolutionScale = this.resolutionScale;
|
||||
return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
|
||||
}
|
||||
public get resolutionScale (): number {
|
||||
return this._resolutionScale;
|
||||
}
|
||||
public set resolutionScale (v: number) {
|
||||
if (v === this._resolutionScale) {
|
||||
return;
|
||||
}
|
||||
this._resolutionScale = v;
|
||||
this._cbToUpdateFrameBuffer?.();
|
||||
}
|
||||
|
||||
public get orientation (): Orientation {
|
||||
return orientationMap[jsb.device.getDeviceOrientation()];
|
||||
}
|
||||
public set orientation (value: Orientation) {
|
||||
warnID(1221);
|
||||
}
|
||||
|
||||
public get safeAreaEdge (): SafeAreaEdge {
|
||||
const nativeSafeArea = jsb.device.getSafeAreaEdge();
|
||||
const dpr = this.devicePixelRatio;
|
||||
const topEdge = nativeSafeArea.x * dpr;
|
||||
const bottomEdge = nativeSafeArea.z * dpr;
|
||||
const leftEdge = nativeSafeArea.y * dpr;
|
||||
const rightEdge = nativeSafeArea.w * dpr;
|
||||
return {
|
||||
top: topEdge,
|
||||
bottom: bottomEdge,
|
||||
left: leftEdge,
|
||||
right: rightEdge,
|
||||
};
|
||||
}
|
||||
public get isProportionalToFrame (): boolean {
|
||||
return this._isProportionalToFrame;
|
||||
}
|
||||
public set isProportionalToFrame (v: boolean) { }
|
||||
|
||||
private _cbToUpdateFrameBuffer?: () => void;
|
||||
private _resolutionScale = 1;
|
||||
private _isProportionalToFrame = false;
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void {
|
||||
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
|
||||
if (!EDITOR) {
|
||||
this._cbToUpdateFrameBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
public requestFullScreen (): Promise<void> {
|
||||
return Promise.reject(new Error('request fullscreen has not been supported yet on this platform.'));
|
||||
}
|
||||
public exitFullScreen (): Promise<void> {
|
||||
return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.'));
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onResize = (event: jsb.WindowEvent): void => {
|
||||
if (event.width === 0 || event.height === 0) return;
|
||||
// TODO: remove this function calling
|
||||
window.resize(event.width / this.devicePixelRatio, event.height / this.devicePixelRatio);
|
||||
this.emit('window-resize', event.width, event.height, event.windowId);
|
||||
};
|
||||
jsb.onOrientationChanged = (event): void => {
|
||||
this.emit('orientation-change', this.orientation);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const screenAdapter = new ScreenAdapter();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/screen-adapter')>(withImpl<typeof import('./screen-adapter')>());
|
||||
@@ -1,139 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2025 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { Size } from '../../../cocos/core/math';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { Orientation } from '../enum-type';
|
||||
import { warn, warnID } from '../../../cocos/core/platform/debug';
|
||||
|
||||
export interface SafeAreaEdge {
|
||||
top: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
right: number;
|
||||
}
|
||||
|
||||
export type ConfigOrientation = 'auto' | 'landscape' | 'portrait';
|
||||
|
||||
export interface IScreenOptions {
|
||||
/**
|
||||
* Orientation options from editor builder.
|
||||
*/
|
||||
configOrientation: ConfigOrientation;
|
||||
/**
|
||||
* Determine whether the game frame exact fits the screen.
|
||||
* Now it only works on Web platform.
|
||||
*/
|
||||
exactFitScreen: boolean,
|
||||
/**
|
||||
* Determine whether use headless renderer, which means do not support some screen operations.
|
||||
*/
|
||||
isHeadlessMode: boolean;
|
||||
}
|
||||
|
||||
class ScreenAdapter extends EventTarget {
|
||||
public isFrameRotated = false;
|
||||
public handleResizeEvent = false;
|
||||
|
||||
public get supportFullScreen (): boolean {
|
||||
return false;
|
||||
}
|
||||
public get isFullScreen (): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
public get devicePixelRatio (): number {
|
||||
return 1;
|
||||
}
|
||||
|
||||
public get windowSize (): Size {
|
||||
// Simulate fake window size
|
||||
return new Size(960, 640);
|
||||
}
|
||||
|
||||
public set windowSize (size: Size) {
|
||||
warn('Setting window size is not supported yet.');
|
||||
}
|
||||
|
||||
public get resolution (): Size {
|
||||
const windowSize = this.windowSize;
|
||||
const resolutionScale = this.resolutionScale;
|
||||
return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
|
||||
}
|
||||
|
||||
public get resolutionScale (): number {
|
||||
return this._resolutionScale;
|
||||
}
|
||||
|
||||
public set resolutionScale (v: number) {
|
||||
if (v === this._resolutionScale) {
|
||||
return;
|
||||
}
|
||||
this._resolutionScale = v;
|
||||
}
|
||||
|
||||
public get orientation (): Orientation {
|
||||
return Orientation.PORTRAIT;
|
||||
}
|
||||
public set orientation (value: Orientation) {
|
||||
warnID(1221);
|
||||
}
|
||||
|
||||
public get safeAreaEdge (): SafeAreaEdge {
|
||||
return {
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
};
|
||||
}
|
||||
public get isProportionalToFrame (): boolean {
|
||||
return this._isProportionalToFrame;
|
||||
}
|
||||
public set isProportionalToFrame (v: boolean) { }
|
||||
|
||||
private _resolutionScale = 1;
|
||||
private _isProportionalToFrame = false;
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
}
|
||||
|
||||
public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void {
|
||||
|
||||
}
|
||||
|
||||
public requestFullScreen (): Promise<void> {
|
||||
return Promise.reject(new Error('request fullscreen has not been supported yet on this platform.'));
|
||||
}
|
||||
public exitFullScreen (): Promise<void> {
|
||||
return Promise.reject(new Error('exit fullscreen has not been supported yet on this platform.'));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const screenAdapter = new ScreenAdapter();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/screen-adapter')>(withImpl<typeof import('./screen-adapter')>());
|
||||
@@ -1,663 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR, TEST } from 'internal:constants';
|
||||
import { ConfigOrientation, IScreenOptions, SafeAreaEdge } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { warnID } from '../../../cocos/core/platform/debug';
|
||||
import { EventTarget } from '../../../cocos/core/event/event-target';
|
||||
import { Size } from '../../../cocos/core/math';
|
||||
import { Orientation } from '../enum-type';
|
||||
import legacyCC from '../../../predefine';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { OS } from '../../system-info/enum-type';
|
||||
|
||||
interface ICachedStyle {
|
||||
width: string;
|
||||
height: string;
|
||||
}
|
||||
|
||||
const EVENT_TIMEOUT = EDITOR ? 5 : 200;
|
||||
const orientationMap: Record<ConfigOrientation, Orientation> = {
|
||||
auto: Orientation.AUTO,
|
||||
landscape: Orientation.LANDSCAPE,
|
||||
portrait: Orientation.PORTRAIT,
|
||||
};
|
||||
|
||||
/**
|
||||
* On Web platform, the game window may points to different type of window.
|
||||
*/
|
||||
enum WindowType {
|
||||
/**
|
||||
* Unknown window type.
|
||||
*/
|
||||
Unknown,
|
||||
/**
|
||||
* A SubFrame in BrowserWindow.
|
||||
* Need to set the frame size from an external editor option.
|
||||
* Should only dispatch 'resize' event when the frame size changed.
|
||||
* Setting window size is supported.
|
||||
*/
|
||||
SubFrame,
|
||||
/**
|
||||
* The window size is determined by the size of BrowserWindow.
|
||||
* Should dispatch 'resize' event when the BrowserWindow size changed.
|
||||
* Setting window size is NOT supported.
|
||||
*/
|
||||
BrowserWindow,
|
||||
/**
|
||||
* The window size is equal to the size of screen.
|
||||
* Should dispatch 'resize' event when enter / exit fullscreen or screen resize.
|
||||
* Setting window size is NOT supported.
|
||||
*/
|
||||
Fullscreen,
|
||||
}
|
||||
|
||||
interface IScreenFunctionName {
|
||||
requestFullscreen: string,
|
||||
exitFullscreen: string,
|
||||
fullscreenchange: string,
|
||||
fullscreenEnabled: string,
|
||||
fullscreenElement: string,
|
||||
fullscreenerror: string,
|
||||
}
|
||||
|
||||
class ScreenAdapter extends EventTarget {
|
||||
public isFrameRotated = false;
|
||||
public handleResizeEvent = true;
|
||||
|
||||
public get supportFullScreen (): boolean {
|
||||
return this._supportFullScreen;
|
||||
}
|
||||
public get isFullScreen (): boolean {
|
||||
if (!this._supportFullScreen) {
|
||||
return false;
|
||||
}
|
||||
return !!document[this._fn.fullscreenElement];
|
||||
}
|
||||
|
||||
public get devicePixelRatio (): number {
|
||||
// TODO: remove the down sampling operation in DPR after supporting resolutionScale
|
||||
return Math.min(window.devicePixelRatio ?? 1, 2);
|
||||
}
|
||||
|
||||
public get windowSize (): Size {
|
||||
const result = this._windowSizeInCssPixels;
|
||||
const dpr = this.devicePixelRatio;
|
||||
result.width *= dpr;
|
||||
result.height *= dpr;
|
||||
return result;
|
||||
}
|
||||
public set windowSize (size: Size) {
|
||||
if (this._windowType !== WindowType.SubFrame) {
|
||||
warnID(9202);
|
||||
return;
|
||||
}
|
||||
this._resizeFrame(this._convertToSizeInCssPixels(size));
|
||||
}
|
||||
|
||||
public get resolution (): Size {
|
||||
const windowSize = this.windowSize;
|
||||
const resolutionScale = this.resolutionScale;
|
||||
return new Size(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
|
||||
}
|
||||
public get resolutionScale (): number {
|
||||
return this._resolutionScale;
|
||||
}
|
||||
public set resolutionScale (v: number) {
|
||||
if (v === this._resolutionScale) {
|
||||
return;
|
||||
}
|
||||
this._resolutionScale = v;
|
||||
this._cbToUpdateFrameBuffer?.();
|
||||
}
|
||||
|
||||
public get orientation (): Orientation {
|
||||
return this._orientation;
|
||||
}
|
||||
public set orientation (value: Orientation) {
|
||||
if (this._orientation === value) {
|
||||
return;
|
||||
}
|
||||
this._orientation = value;
|
||||
this._updateFrame();
|
||||
}
|
||||
|
||||
private _updateFrame (): void {
|
||||
this._updateFrameState();
|
||||
this._resizeFrame();
|
||||
}
|
||||
|
||||
public get safeAreaEdge (): SafeAreaEdge {
|
||||
const dpr = this.devicePixelRatio;
|
||||
const _top = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-top') || '0') * dpr;
|
||||
const _bottom = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-bottom') || '0') * dpr;
|
||||
const _left = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-left') || '0') * dpr;
|
||||
const _right = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-right') || '0') * dpr;
|
||||
|
||||
return {
|
||||
top: _top,
|
||||
bottom: _bottom,
|
||||
left: _left,
|
||||
right: _right,
|
||||
};
|
||||
}
|
||||
public get isProportionalToFrame (): boolean {
|
||||
return this._isProportionalToFrame;
|
||||
}
|
||||
public set isProportionalToFrame (v: boolean) {
|
||||
if (this._isProportionalToFrame === v) {
|
||||
return;
|
||||
}
|
||||
this._isProportionalToFrame = v;
|
||||
this._updateContainer();
|
||||
}
|
||||
|
||||
private _gameFrame?: HTMLDivElement;
|
||||
private _gameContainer?: HTMLDivElement;
|
||||
private _gameCanvas?: HTMLCanvasElement;
|
||||
private _isProportionalToFrame = false;
|
||||
private _cachedFrameStyle: ICachedStyle = { width: '0px', height: '0px' };
|
||||
private _cachedContainerStyle: ICachedStyle = { width: '0px', height: '0px' };
|
||||
private _cbToUpdateFrameBuffer?: () => void;
|
||||
private _supportFullScreen = false;
|
||||
private _touchEventName: string;
|
||||
private _onFullscreenChange?: () => void;
|
||||
private _onFullscreenError?: () => void;
|
||||
// We need to set timeout to handle screen event.
|
||||
private _orientationChangeTimeoutId = -1;
|
||||
private _cachedFrameSize = new Size(0, 0); // cache before enter fullscreen.
|
||||
private _exactFitScreen = false;
|
||||
private _isHeadlessMode = false;
|
||||
private _fn = {} as IScreenFunctionName;
|
||||
// Function mapping for cross browser support
|
||||
private _fnGroup = [
|
||||
[
|
||||
'requestFullscreen',
|
||||
'exitFullscreen',
|
||||
'fullscreenchange',
|
||||
'fullscreenEnabled',
|
||||
'fullscreenElement',
|
||||
'fullscreenerror',
|
||||
],
|
||||
[
|
||||
'requestFullScreen',
|
||||
'exitFullScreen',
|
||||
'fullScreenchange',
|
||||
'fullScreenEnabled',
|
||||
'fullScreenElement',
|
||||
'fullscreenerror',
|
||||
],
|
||||
[
|
||||
'webkitRequestFullScreen',
|
||||
'webkitCancelFullScreen',
|
||||
'webkitfullscreenchange',
|
||||
'webkitIsFullScreen',
|
||||
'webkitCurrentFullScreenElement',
|
||||
'webkitfullscreenerror',
|
||||
],
|
||||
[
|
||||
'mozRequestFullScreen',
|
||||
'mozCancelFullScreen',
|
||||
'mozfullscreenchange',
|
||||
'mozFullScreen',
|
||||
'mozFullScreenElement',
|
||||
'mozfullscreenerror',
|
||||
],
|
||||
[
|
||||
'msRequestFullscreen',
|
||||
'msExitFullscreen',
|
||||
'MSFullscreenChange',
|
||||
'msFullscreenEnabled',
|
||||
'msFullscreenElement',
|
||||
'msfullscreenerror',
|
||||
],
|
||||
];
|
||||
private get _windowSizeInCssPixels (): Size {
|
||||
if (TEST) {
|
||||
return new Size(window.innerWidth, window.innerHeight);
|
||||
}
|
||||
if (this.isProportionalToFrame) {
|
||||
if (!this._gameContainer) {
|
||||
warnID(9201);
|
||||
return new Size(0, 0);
|
||||
}
|
||||
return new Size(this._gameContainer.clientWidth, this._gameContainer.clientHeight);
|
||||
}
|
||||
let fullscreenTarget;
|
||||
let width: number;
|
||||
let height: number;
|
||||
switch (this._windowType) {
|
||||
case WindowType.SubFrame:
|
||||
if (!this._gameFrame) {
|
||||
warnID(9201);
|
||||
return new Size(0, 0);
|
||||
}
|
||||
return new Size(this._gameFrame.clientWidth, this._gameFrame.clientHeight);
|
||||
case WindowType.Fullscreen:
|
||||
fullscreenTarget = this._getFullscreenTarget()!;
|
||||
width = this.isFrameRotated ? fullscreenTarget.clientHeight : fullscreenTarget.clientWidth;
|
||||
height = this.isFrameRotated ? fullscreenTarget.clientWidth : fullscreenTarget.clientHeight;
|
||||
return new Size(width, height);
|
||||
case WindowType.BrowserWindow:
|
||||
width = this.isFrameRotated ? window.innerHeight : window.innerWidth;
|
||||
height = this.isFrameRotated ? window.innerWidth : window.innerHeight;
|
||||
return new Size(width, height);
|
||||
case WindowType.Unknown:
|
||||
default:
|
||||
return new Size(1, 1);
|
||||
}
|
||||
}
|
||||
private get _windowType (): WindowType {
|
||||
if (this._isHeadlessMode) {
|
||||
return WindowType.Unknown;
|
||||
}
|
||||
if (this.isFullScreen) {
|
||||
return WindowType.Fullscreen;
|
||||
}
|
||||
if (!this._gameFrame) {
|
||||
warnID(9201);
|
||||
return WindowType.Unknown;
|
||||
}
|
||||
if (this._exactFitScreen) {
|
||||
// Note: It doesn't work well to determine whether the frame exact fits the screen.
|
||||
// Need to specify the attribute from Editor.
|
||||
return WindowType.BrowserWindow;
|
||||
}
|
||||
return WindowType.SubFrame;
|
||||
}
|
||||
private _resolutionScale = 1;
|
||||
private _orientation = Orientation.AUTO;//The orientation set by user.
|
||||
private _orientationDevice = Orientation.AUTO;//Store the device's orientation.
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
// TODO: need to access frame from 'pal/launcher' module
|
||||
this._gameFrame = document.getElementById('GameDiv') as HTMLDivElement;
|
||||
this._gameContainer = document.getElementById('Cocos3dGameContainer') as HTMLDivElement;
|
||||
this._gameCanvas = document.getElementById('GameCanvas') as HTMLCanvasElement;
|
||||
// Compability with old preview or build template in Editor.
|
||||
if (!TEST && !EDITOR) {
|
||||
if (!this._gameFrame) {
|
||||
this._gameFrame = document.createElement<'div'>('div');
|
||||
this._gameFrame.setAttribute('id', 'GameDiv');
|
||||
this._gameCanvas?.parentNode?.insertBefore(this._gameFrame, this._gameCanvas);
|
||||
this._gameFrame.appendChild(this._gameCanvas);
|
||||
}
|
||||
if (!this._gameContainer) {
|
||||
this._gameContainer = document.createElement<'div'>('div');
|
||||
this._gameContainer.setAttribute('id', 'Cocos3dGameContainer');
|
||||
this._gameCanvas?.parentNode?.insertBefore(this._gameContainer, this._gameCanvas);
|
||||
this._gameContainer.appendChild(this._gameCanvas);
|
||||
}
|
||||
}
|
||||
|
||||
let fnList: Array<string>;
|
||||
const fnGroup = this._fnGroup;
|
||||
for (let i = 0; i < fnGroup.length; i++) {
|
||||
fnList = fnGroup[i];
|
||||
// detect event support
|
||||
if (typeof document[fnList[1]] !== 'undefined') {
|
||||
for (let i = 0; i < fnList.length; i++) {
|
||||
this._fn[fnGroup[0][i]] = fnList[i];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this._supportFullScreen = (this._fn.requestFullscreen !== undefined);
|
||||
this._touchEventName = ('ontouchstart' in window) ? 'touchend' : 'mousedown';
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
public init (options: IScreenOptions, cbToRebuildFrameBuffer: () => void): void {
|
||||
this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
|
||||
this.orientation = orientationMap[options.configOrientation];
|
||||
this._exactFitScreen = options.exactFitScreen;
|
||||
this._isHeadlessMode = options.isHeadlessMode;
|
||||
this._resizeFrame();
|
||||
}
|
||||
|
||||
public requestFullScreen (): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this.isFullScreen) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
this._cachedFrameSize = this.windowSize;
|
||||
this._doRequestFullScreen().then(() => {
|
||||
resolve();
|
||||
}).catch(() => {
|
||||
const fullscreenTarget = this._getFullscreenTarget();
|
||||
if (!fullscreenTarget) {
|
||||
reject(new Error('Cannot access fullscreen target'));
|
||||
return;
|
||||
}
|
||||
fullscreenTarget.addEventListener(this._touchEventName, () => {
|
||||
this._doRequestFullScreen().then(() => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
}, { once: true, capture: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
public exitFullScreen (): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestPromise = document[this._fn.exitFullscreen]();
|
||||
if (window.Promise && requestPromise instanceof Promise) {
|
||||
requestPromise.then(() => {
|
||||
this.windowSize = this._cachedFrameSize;
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
return;
|
||||
}
|
||||
this.windowSize = this._cachedFrameSize;
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
document.addEventListener(this._fn.fullscreenerror, (): void => {
|
||||
this._onFullscreenError?.();
|
||||
});
|
||||
|
||||
window.addEventListener('resize', (): void => {
|
||||
// if (!this.handleResizeEvent) {
|
||||
// return;
|
||||
// }
|
||||
this._updateFrame();
|
||||
});
|
||||
|
||||
const notifyOrientationChange = (orientation): void => {
|
||||
if (orientation === this._orientationDevice) {
|
||||
return;
|
||||
}
|
||||
this._orientationDevice = orientation;
|
||||
this._updateFrame();
|
||||
this.emit('orientation-change', orientation);
|
||||
};
|
||||
|
||||
const getOrientation = (): Orientation => {
|
||||
let tmpOrientation = Orientation.PORTRAIT;
|
||||
switch (window.orientation) {
|
||||
case 0:
|
||||
tmpOrientation = Orientation.PORTRAIT;
|
||||
break;
|
||||
case 90:
|
||||
// Handle landscape orientation, top side facing to the right
|
||||
tmpOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
break;
|
||||
case -90:
|
||||
// Handle landscape orientation, top side facing to the left
|
||||
tmpOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
break;
|
||||
case 180:
|
||||
tmpOrientation = Orientation.PORTRAIT_UPSIDE_DOWN;
|
||||
break;
|
||||
default:
|
||||
tmpOrientation = this._orientationDevice;
|
||||
break;
|
||||
}
|
||||
return tmpOrientation;
|
||||
};
|
||||
/*After receive orientation-change event, window.innerWidth & innerHeight may not change immediately,
|
||||
so we delay EVENT_TIMEOUT to handle orientation-change.*/
|
||||
let handleOrientationChange;
|
||||
const orientationChangeCallback = (): void => {
|
||||
if (this._orientationChangeTimeoutId !== -1) {
|
||||
clearTimeout(this._orientationChangeTimeoutId);
|
||||
}
|
||||
this._orientationChangeTimeoutId = setTimeout((): void => {
|
||||
handleOrientationChange();
|
||||
}, EVENT_TIMEOUT);
|
||||
};
|
||||
if (typeof window.matchMedia === 'function') {
|
||||
const updateDPRChangeListener = (): void => {
|
||||
const dpr = this.devicePixelRatio;
|
||||
// NOTE: some browsers especially on iPhone doesn't support MediaQueryList
|
||||
const mediaQueryResolution = window.matchMedia(`(resolution: ${dpr}dppx)`);
|
||||
if (mediaQueryResolution.addEventListener) {
|
||||
mediaQueryResolution.addEventListener('change', (): void => {
|
||||
this.emit('window-resize', this.windowSize.width, this.windowSize.height);
|
||||
updateDPRChangeListener();
|
||||
}, { once: true });
|
||||
} else if (mediaQueryResolution.addListener) {
|
||||
mediaQueryResolution.addListener((): void => {
|
||||
this.emit('window-resize', this.windowSize.width, this.windowSize.height);
|
||||
});
|
||||
}
|
||||
};
|
||||
updateDPRChangeListener();
|
||||
|
||||
const mediaQueryPortrait = window.matchMedia('(orientation: portrait)');
|
||||
const mediaQueryLandscape = window.matchMedia('(orientation: landscape)');
|
||||
// eslint-disable-next-line no-restricted-globals
|
||||
const hasScreeOrientation = screen.orientation;
|
||||
handleOrientationChange = (): void => {
|
||||
let tmpOrientation: Orientation = this._orientationDevice;
|
||||
if (mediaQueryPortrait.matches) {
|
||||
tmpOrientation = Orientation.PORTRAIT;
|
||||
if (hasScreeOrientation) {
|
||||
// eslint-disable-next-line no-restricted-globals
|
||||
const orientationType = screen.orientation.type;
|
||||
if (orientationType === 'portrait-primary') {
|
||||
tmpOrientation = Orientation.PORTRAIT;
|
||||
} else {
|
||||
tmpOrientation = Orientation.PORTRAIT_UPSIDE_DOWN;
|
||||
}
|
||||
}
|
||||
} else if (mediaQueryLandscape.matches) {
|
||||
tmpOrientation = Orientation.LANDSCAPE;
|
||||
if (hasScreeOrientation) {
|
||||
// eslint-disable-next-line no-restricted-globals
|
||||
const orientationType = screen.orientation.type;
|
||||
if (orientationType === 'landscape-primary') {
|
||||
tmpOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
} else {
|
||||
tmpOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
}
|
||||
}
|
||||
}
|
||||
notifyOrientationChange(tmpOrientation);
|
||||
};
|
||||
if (mediaQueryPortrait.addEventListener) {
|
||||
mediaQueryPortrait.addEventListener('change', orientationChangeCallback);
|
||||
mediaQueryLandscape.addEventListener('change', orientationChangeCallback);
|
||||
} else if (mediaQueryPortrait.addListener) {
|
||||
mediaQueryPortrait.addListener(orientationChangeCallback);
|
||||
mediaQueryLandscape.addListener(orientationChangeCallback);
|
||||
}
|
||||
} else {
|
||||
handleOrientationChange = (): void => {
|
||||
const tmpOrientation = getOrientation();
|
||||
notifyOrientationChange(tmpOrientation);
|
||||
};
|
||||
window.addEventListener('orientationchange', orientationChangeCallback);
|
||||
}
|
||||
document.addEventListener(this._fn.fullscreenchange, () => {
|
||||
this._onFullscreenChange?.();
|
||||
this.emit('fullscreen-change', this.windowSize.width, this.windowSize.height);
|
||||
});
|
||||
}
|
||||
private _convertToSizeInCssPixels (size: Size): Size {
|
||||
const clonedSize = size.clone();
|
||||
const dpr = this.devicePixelRatio;
|
||||
clonedSize.width /= dpr;
|
||||
clonedSize.height /= dpr;
|
||||
return clonedSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame size may be from screen size or an external editor options by setting screen.windowSize.
|
||||
* @param sizeInCssPixels you need to specify this size when the windowType is SubFrame.
|
||||
*/
|
||||
private _resizeFrame (sizeInCssPixels?: Size): void {
|
||||
if (!this._gameFrame) {
|
||||
return;
|
||||
}
|
||||
// Center align the canvas
|
||||
this._gameFrame.style.display = 'flex';
|
||||
this._gameFrame.style['justify-content'] = 'center';
|
||||
this._gameFrame.style['align-items'] = 'center';
|
||||
if (this._windowType === WindowType.SubFrame) {
|
||||
if (!sizeInCssPixels) {
|
||||
this._updateContainer();
|
||||
return;
|
||||
}
|
||||
this._gameFrame.style.width = `${sizeInCssPixels.width}px`;
|
||||
this._gameFrame.style.height = `${sizeInCssPixels.height}px`;
|
||||
} else {
|
||||
const winWidth = window.innerWidth;
|
||||
let winHeight = window.innerHeight;
|
||||
//On certain android devices, window.innerHeight may not account for the height of the virtual keyboard, so dynamic calculation is necessary.
|
||||
const inputHeight = document.body.scrollHeight - winHeight;
|
||||
if (systemInfo.os === OS.ANDROID && winHeight < inputHeight) {
|
||||
winHeight += inputHeight;
|
||||
}
|
||||
if (this.isFrameRotated) {
|
||||
this._gameFrame.style['-webkit-transform'] = 'rotate(90deg)';
|
||||
this._gameFrame.style.transform = 'rotate(90deg)';
|
||||
this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
|
||||
this._gameFrame.style.transformOrigin = '0px 0px 0px';
|
||||
this._gameFrame.style.margin = `0 0 0 ${winWidth}px`;
|
||||
this._gameFrame.style.width = `${winHeight}px`;
|
||||
this._gameFrame.style.height = `${winWidth}px`;
|
||||
} else {
|
||||
this._gameFrame.style['-webkit-transform'] = 'rotate(0deg)';
|
||||
this._gameFrame.style.transform = 'rotate(0deg)';
|
||||
// TODO
|
||||
// this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
|
||||
// this._gameFrame.style.transformOrigin = '0px 0px 0px';
|
||||
this._gameFrame.style.margin = '0px auto';
|
||||
this._gameFrame.style.width = `${winWidth}px`;
|
||||
this._gameFrame.style.height = `${winHeight}px`;
|
||||
}
|
||||
}
|
||||
|
||||
this._updateContainer();
|
||||
}
|
||||
|
||||
private _getFullscreenTarget (): HTMLElement | undefined {
|
||||
const windowType = this._windowType;
|
||||
if (windowType === WindowType.Fullscreen) {
|
||||
return document[this._fn.fullscreenElement] as HTMLElement;
|
||||
}
|
||||
if (windowType === WindowType.SubFrame) {
|
||||
return this._gameFrame;
|
||||
}
|
||||
// On web mobile, the transform of game frame doesn't work when it's on fullscreen.
|
||||
// So we need to make the body fullscreen.
|
||||
return document.body;
|
||||
}
|
||||
private _doRequestFullScreen (): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this._supportFullScreen) {
|
||||
reject(new Error('fullscreen is not supported'));
|
||||
return;
|
||||
}
|
||||
const fullscreenTarget = this._getFullscreenTarget();
|
||||
if (!fullscreenTarget) {
|
||||
reject(new Error('Cannot access fullscreen target'));
|
||||
return;
|
||||
}
|
||||
this._onFullscreenChange = undefined;
|
||||
this._onFullscreenError = undefined;
|
||||
const requestPromise = fullscreenTarget[this._fn.requestFullscreen]() as Promise<void> | undefined;
|
||||
if (window.Promise && requestPromise instanceof Promise) {
|
||||
requestPromise.then(resolve).catch(reject);
|
||||
} else {
|
||||
this._onFullscreenChange = resolve;
|
||||
this._onFullscreenError = reject;
|
||||
}
|
||||
});
|
||||
}
|
||||
private _updateFrameState (): void {
|
||||
const orientation = this.orientation;
|
||||
const width = window.innerWidth;
|
||||
const height = window.innerHeight;
|
||||
const isBrowserLandscape = width > height;
|
||||
this.isFrameRotated = systemInfo.isMobile
|
||||
&& ((isBrowserLandscape && orientation === Orientation.PORTRAIT)
|
||||
|| (!isBrowserLandscape && orientation === Orientation.LANDSCAPE));
|
||||
}
|
||||
private _updateContainer (): void {
|
||||
if (!this._gameContainer) {
|
||||
warnID(9201);
|
||||
return;
|
||||
}
|
||||
if (this.isProportionalToFrame) {
|
||||
if (!this._gameFrame) {
|
||||
warnID(9201);
|
||||
return;
|
||||
}
|
||||
// TODO: access designedResolution from Launcher module.
|
||||
const designedResolution = legacyCC.view.getDesignResolutionSize() as Size;
|
||||
const frame = this._gameFrame;
|
||||
const frameW = frame.clientWidth;
|
||||
const frameH = frame.clientHeight;
|
||||
const designW = designedResolution.width;
|
||||
const designH = designedResolution.height;
|
||||
const scaleX = frameW / designW;
|
||||
const scaleY = frameH / designH;
|
||||
const containerStyle = this._gameContainer.style;
|
||||
let containerW: number;
|
||||
let containerH: number;
|
||||
|
||||
if (scaleX < scaleY) {
|
||||
containerW = frameW;
|
||||
containerH = designH * scaleX;
|
||||
} else {
|
||||
containerW = designW * scaleY;
|
||||
containerH = frameH;
|
||||
}
|
||||
// Set window size on game container
|
||||
containerStyle.width = `${containerW}px`;
|
||||
containerStyle.height = `${containerH}px`;
|
||||
} else {
|
||||
const containerStyle = this._gameContainer.style;
|
||||
// game container exact fit game frame.
|
||||
containerStyle.width = '100%';
|
||||
containerStyle.height = '100%';
|
||||
}
|
||||
|
||||
// Cache Test
|
||||
if (this._gameFrame
|
||||
&& (this._cachedFrameStyle.width !== this._gameFrame.style.width
|
||||
|| this._cachedFrameStyle.height !== this._gameFrame.style.height
|
||||
|| this._cachedContainerStyle.width !== this._gameContainer.style.width
|
||||
|| this._cachedContainerStyle.height !== this._gameContainer.style.height)) {
|
||||
this.emit('window-resize', this.windowSize.width, this.windowSize.height);
|
||||
|
||||
// Update Cache
|
||||
this._cachedFrameStyle.width = this._gameFrame.style.width;
|
||||
this._cachedFrameStyle.height = this._gameFrame.style.height;
|
||||
this._cachedContainerStyle.width = this._gameContainer.style.width;
|
||||
this._cachedContainerStyle.height = this._gameContainer.style.height;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const screenAdapter = new ScreenAdapter();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/screen-adapter')>(withImpl<typeof import('./screen-adapter')>());
|
||||
@@ -1,141 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum BrowserType {
|
||||
/**
|
||||
* @en Browser Type - Unknown
|
||||
* @zh 浏览器类型 - 未知
|
||||
*/
|
||||
UNKNOWN = 'unknown',
|
||||
/**
|
||||
* @en Browser Type - WeChat inner browser
|
||||
* @zh 浏览器类型 - 微信内置浏览器
|
||||
*/
|
||||
WECHAT = 'wechat',
|
||||
/**
|
||||
* @en Browser Type - Android Browser
|
||||
* @zh 浏览器类型 - 安卓浏览器
|
||||
*/
|
||||
ANDROID = 'androidbrowser',
|
||||
/**
|
||||
* @en Browser Type - Internet Explorer
|
||||
* @zh 浏览器类型 - 微软 IE
|
||||
*/
|
||||
IE = 'ie',
|
||||
/**
|
||||
* @en Browser Type - Microsoft Edge
|
||||
* @zh 浏览器类型 - 微软 Edge
|
||||
*/
|
||||
EDGE = 'edge',
|
||||
/**
|
||||
* @en Browser Type - QQ Browser
|
||||
* @zh 浏览器类型 - QQ 浏览器
|
||||
*/
|
||||
QQ = 'qqbrowser',
|
||||
/**
|
||||
* @en Browser Type - Mobile QQ Browser
|
||||
* @zh 浏览器类型 - 手机 QQ 浏览器
|
||||
*/
|
||||
MOBILE_QQ = 'mqqbrowser',
|
||||
/**
|
||||
* @en Browser Type - UC Browser
|
||||
* @zh 浏览器类型 - UC 浏览器
|
||||
*/
|
||||
UC = 'ucbrowser',
|
||||
/**
|
||||
* @en Browser Type - Third party integrated UC browser
|
||||
* @zh 浏览器类型 - 第三方应用中集成的 UC 浏览器
|
||||
*/
|
||||
UCBS = 'ucbs',
|
||||
/**
|
||||
* @en Browser Type - 360 Browser
|
||||
* @zh 浏览器类型 - 360 浏览器
|
||||
*/
|
||||
BROWSER_360 = '360browser',
|
||||
/**
|
||||
* @en Browser Type - Baidu Box App
|
||||
* @zh 浏览器类型 - Baidu Box App
|
||||
*/
|
||||
BAIDU_APP = 'baiduboxapp',
|
||||
/**
|
||||
* @en Browser Type - Baidu Browser
|
||||
* @zh 浏览器类型 - 百度浏览器
|
||||
*/
|
||||
BAIDU = 'baidubrowser',
|
||||
/**
|
||||
* @en Browser Type - Maxthon Browser
|
||||
* @zh 浏览器类型 - 傲游浏览器
|
||||
*/
|
||||
MAXTHON = 'maxthon',
|
||||
/**
|
||||
* @en Browser Type - Opera Browser
|
||||
* @zh 浏览器类型 - Opera 浏览器
|
||||
*/
|
||||
OPERA = 'opera',
|
||||
/**
|
||||
* @en Browser Type - Oupeng Browser
|
||||
* @zh 浏览器类型 - 欧朋浏览器
|
||||
*/
|
||||
OUPENG = 'oupeng',
|
||||
/**
|
||||
* @en Browser Type - MI UI Browser
|
||||
* @zh 浏览器类型 - MIUI 内置浏览器
|
||||
*/
|
||||
MIUI = 'miuibrowser',
|
||||
/**
|
||||
* @en Browser Type - Firefox Browser
|
||||
* @zh 浏览器类型 - Firefox 浏览器
|
||||
*/
|
||||
FIREFOX = 'firefox',
|
||||
/**
|
||||
* @en Browser Type - Safari Browser
|
||||
* @zh 浏览器类型 - Safari 浏览器
|
||||
*/
|
||||
SAFARI = 'safari',
|
||||
/**
|
||||
* @en Browser Type - Chrome Browser
|
||||
* @zh 浏览器类型 - Chrome 浏览器
|
||||
*/
|
||||
CHROME = 'chrome',
|
||||
/**
|
||||
* @en Browser Type - Cheetah Browser
|
||||
* @zh 浏览器类型 - 猎豹浏览器
|
||||
*/
|
||||
LIEBAO = 'liebao',
|
||||
/**
|
||||
* @en Browser Type - QZone Inner Browser
|
||||
* @zh 浏览器类型 - QZone 内置浏览器
|
||||
*/
|
||||
QZONE = 'qzone',
|
||||
/**
|
||||
* @en Browser Type - Sogou Browser
|
||||
* @zh 浏览器类型 - 搜狗浏览器
|
||||
*/
|
||||
SOUGOU = 'sogou',
|
||||
/**
|
||||
* @en Browser Type - Huawei Browser
|
||||
* @zh 浏览器类型 - 华为浏览器
|
||||
*/
|
||||
HUAWEI = 'huawei',
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export type PalSystemEvent = 'hide' | 'show' | 'close';
|
||||
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum Feature {
|
||||
/**
|
||||
* @en Feature to support Webp.
|
||||
* @zh 是否支持 Webp 特性。
|
||||
*/
|
||||
WEBP = 'WEBP',
|
||||
/**
|
||||
* @en Feature to support Image Bitmap.
|
||||
* @zh 是否支持 Image Bitmap 特性。
|
||||
*/
|
||||
IMAGE_BITMAP = 'IMAGE_BITMAP',
|
||||
/**
|
||||
* @en Feature to support Web View.
|
||||
* @zh 是否支持 Web View 特性。
|
||||
*/
|
||||
WEB_VIEW = 'WEB_VIEW',
|
||||
/**
|
||||
* @en Feature to support Video Player.
|
||||
* @zh 是否支持 Video Player 特性。
|
||||
*/
|
||||
VIDEO_PLAYER = 'VIDEO_PLAYER',
|
||||
/**
|
||||
* @en Feature to support Safe Area.
|
||||
* @zh 是否支持 Safe Area 特性。
|
||||
*/
|
||||
SAFE_AREA = 'SAFE_AREA',
|
||||
|
||||
/**
|
||||
* @en Feature to support HPE (high performance emulator) platforms, such as Google Play Games For PC.
|
||||
* @zh 是否支持 HPE 平台, 比如: Android 的 Google Play Games 在 PC 上的模拟器.
|
||||
*/
|
||||
HPE = 'HPE',
|
||||
|
||||
/**
|
||||
* @en Feature to support Touch Input.
|
||||
* Touch Input is only supported on some devices with touch screen.
|
||||
* This feature tells that whether the device has a touch screen.
|
||||
* @zh 是否支持触摸输入。
|
||||
* 触摸输入只在一些带触摸屏的设备上支持。
|
||||
* 这个特性旨在说明设备上是否带触摸屏。
|
||||
*/
|
||||
INPUT_TOUCH = 'INPUT_TOUCH',
|
||||
/**
|
||||
* @en Feature to support dispatching EventKeyboard.
|
||||
* @zh 是否支持派发 EventKeyboard。
|
||||
*/
|
||||
EVENT_KEYBOARD = 'EVENT_KEYBOARD',
|
||||
/**
|
||||
* @en Feature to support dispatching EventMouse.
|
||||
* @zh 是否支持派发 EventMouse。
|
||||
*/
|
||||
EVENT_MOUSE = 'EVENT_MOUSE',
|
||||
/**
|
||||
* @en Feature to support dispatching EventTouch.
|
||||
* On some devices without touch screen, we still can simulate dispatching EventTouch from EventMouse.
|
||||
* @zh 是否支持派发 EventTouch。
|
||||
* 在一些不带触摸屏的设备上,我们仍然会从 EventMouse 模拟派发 EventTouch。
|
||||
*/
|
||||
EVENT_TOUCH = 'EVENT_TOUCH',
|
||||
/**
|
||||
* @en Feature to support dispatching EventAcceleration.
|
||||
* @zh 是否支持派发 EventAcceleration。
|
||||
*/
|
||||
EVENT_ACCELEROMETER = 'EVENT_ACCELEROMETER',
|
||||
/**
|
||||
* @en Feature to support dispatching EventGamepad.
|
||||
* @zh 是否支持派发 EventGamepad.
|
||||
*/
|
||||
EVENT_GAMEPAD = 'EVENT_GAMEPAD',
|
||||
/**
|
||||
* @en Feature to support dispatching EventHandle.
|
||||
* @zh 是否支持派发 EventHandle
|
||||
*/
|
||||
EVENT_HANDLE = 'EVENT_HANDLE',
|
||||
/**
|
||||
* @en Feature to support dispatching EventHMD.
|
||||
* @zh 是否支持派发 EventHMD
|
||||
*/
|
||||
EVENT_HMD = 'EVENT_HMD',
|
||||
/**
|
||||
* @en Feature to support dispatching EventHandheld.
|
||||
* @zh 是否支持派发 EventHandheld
|
||||
*/
|
||||
EVENT_HANDHELD = 'EVENT_HANDHELD',
|
||||
/**
|
||||
* @en Check whether Webassembly is supported at runtime. Generally, it needs to be checked when the constant `NATIVE_CODE_BUNDLE_MODE` is 2.
|
||||
* If it is not supported, you need to fallback to the Asm solution.
|
||||
* @zh 运行时检测是否支持 Webassembly,一般在宏 `NATIVE_CODE_BUNDLE_MODE` 为 2 时需要检测,如果不支持,需要回滚到 Asm 方案
|
||||
*/
|
||||
WASM = 'WASM',
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export * from './browser-type';
|
||||
export * from './event';
|
||||
export * from './language';
|
||||
export * from './network-type';
|
||||
export * from './operating-system';
|
||||
export * from './platform';
|
||||
export * from './feature';
|
||||
@@ -1,151 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum Language {
|
||||
/**
|
||||
* @en Unknown language code
|
||||
* @zh 语言代码 - 未知
|
||||
*/
|
||||
UNKNOWN = 'unknown',
|
||||
|
||||
/**
|
||||
* @en English language code
|
||||
* @zh 语言代码 - 英语
|
||||
*/
|
||||
ENGLISH = 'en',
|
||||
|
||||
/**
|
||||
* @en Chinese language code
|
||||
* @zh 语言代码 - 中文
|
||||
*/
|
||||
CHINESE = 'zh',
|
||||
|
||||
/**
|
||||
* @en French language code
|
||||
* @zh 语言代码 - 法语
|
||||
*/
|
||||
FRENCH = 'fr',
|
||||
|
||||
/**
|
||||
* @en Italian language code
|
||||
* @zh 语言代码 - 意大利语
|
||||
*/
|
||||
ITALIAN = 'it',
|
||||
|
||||
/**
|
||||
* @en German language code
|
||||
* @zh 语言代码 - 德语
|
||||
*/
|
||||
GERMAN = 'de',
|
||||
|
||||
/**
|
||||
* @en Spanish language code
|
||||
* @zh 语言代码 - 西班牙语
|
||||
*/
|
||||
SPANISH = 'es',
|
||||
|
||||
/**
|
||||
* @en Spanish language code
|
||||
* @zh 语言代码 - 荷兰语
|
||||
*/
|
||||
DUTCH = 'du',
|
||||
|
||||
/**
|
||||
* @en Russian language code
|
||||
* @zh 语言代码 - 俄罗斯语
|
||||
*/
|
||||
RUSSIAN = 'ru',
|
||||
|
||||
/**
|
||||
* @en Korean language code
|
||||
* @zh 语言代码 - 韩语
|
||||
*/
|
||||
KOREAN = 'ko',
|
||||
|
||||
/**
|
||||
* @en Japanese language code
|
||||
* @zh 语言代码 - 日语
|
||||
*/
|
||||
JAPANESE = 'ja',
|
||||
|
||||
/**
|
||||
* @en Hungarian language code
|
||||
* @zh 语言代码 - 匈牙利语
|
||||
*/
|
||||
HUNGARIAN = 'hu',
|
||||
|
||||
/**
|
||||
* @en Portuguese language code
|
||||
* @zh 语言代码 - 葡萄牙语
|
||||
*/
|
||||
PORTUGUESE = 'pt',
|
||||
|
||||
/**
|
||||
* @en Arabic language code
|
||||
* @zh 语言代码 - 阿拉伯语
|
||||
*/
|
||||
ARABIC = 'ar',
|
||||
|
||||
/**
|
||||
* @en Norwegian language code
|
||||
* @zh 语言代码 - 挪威语
|
||||
*/
|
||||
NORWEGIAN = 'no',
|
||||
|
||||
/**
|
||||
* @en Polish language code
|
||||
* @zh 语言代码 - 波兰语
|
||||
*/
|
||||
POLISH = 'pl',
|
||||
|
||||
/**
|
||||
* @en Turkish language code
|
||||
* @zh 语言代码 - 土耳其语
|
||||
*/
|
||||
TURKISH = 'tr',
|
||||
|
||||
/**
|
||||
* @en Ukrainian language code
|
||||
* @zh 语言代码 - 乌克兰语
|
||||
*/
|
||||
UKRAINIAN = 'uk',
|
||||
|
||||
/**
|
||||
* @en Romanian language code
|
||||
* @zh 语言代码 - 罗马尼亚语
|
||||
*/
|
||||
ROMANIAN = 'ro',
|
||||
|
||||
/**
|
||||
* @en Bulgarian language code
|
||||
* @zh 语言代码 - 保加利亚语
|
||||
*/
|
||||
BULGARIAN = 'bg',
|
||||
|
||||
/**
|
||||
* @en Hindi language code
|
||||
* @zh 语言代码 - 印度语
|
||||
*/
|
||||
HINDI = 'hi',
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum NetworkType {
|
||||
/**
|
||||
* @en Network is unreachable.
|
||||
* @zh 网络不通
|
||||
*/
|
||||
NONE,
|
||||
/**
|
||||
* @en Network is reachable via WiFi or cable.
|
||||
* @zh 通过无线或者有线本地网络连接因特网
|
||||
*/
|
||||
LAN,
|
||||
/**
|
||||
* @en Network is reachable via Wireless Wide Area Network
|
||||
* @zh 通过蜂窝移动网络连接因特网
|
||||
*/
|
||||
WWAN,
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum OS {
|
||||
/**
|
||||
* @en Operating System - Unknown
|
||||
* @zh 操作系统 - 未知
|
||||
*/
|
||||
UNKNOWN = 'Unknown',
|
||||
/**
|
||||
* @en Operating System - iOS
|
||||
* @zh 操作系统 - iOS
|
||||
*/
|
||||
IOS = 'iOS',
|
||||
/**
|
||||
* @en Operating System - Android
|
||||
* @zh 操作系统 - 安卓
|
||||
*/
|
||||
ANDROID = 'Android',
|
||||
/**
|
||||
* @en Operating System - Windows
|
||||
* @zh 操作系统 - Windows
|
||||
*/
|
||||
WINDOWS = 'Windows',
|
||||
/**
|
||||
* @en Operating System - Linux
|
||||
* @zh 操作系统 - Linux
|
||||
*/
|
||||
LINUX = 'Linux',
|
||||
/**
|
||||
* @en Operating System - Mac OS X
|
||||
* @zh 操作系统 - Mac OS X
|
||||
*/
|
||||
OSX = 'OS X',
|
||||
/**
|
||||
* @en Operating System - HarmonyOS
|
||||
* @zh 操作系统 - 鸿蒙
|
||||
*/
|
||||
OHOS = 'OHOS',
|
||||
/**
|
||||
* @en Operating System - OpenHarmony
|
||||
* @zh 操作系统 - OpenHarmony
|
||||
*/
|
||||
OPENHARMONY = 'OpenHarmony',
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export enum Platform {
|
||||
UNKNOWN = 'UNKNOWN',
|
||||
// Web Based
|
||||
EDITOR_PAGE = 'EDITOR_PAGE',
|
||||
EDITOR_CORE = 'EDITOR_CORE',
|
||||
NODEJS_PAGE = 'NODEJS_PAGE',
|
||||
MOBILE_BROWSER = 'MOBILE_BROWSER',
|
||||
DESKTOP_BROWSER = 'DESKTOP_BROWSER',
|
||||
// Native
|
||||
WIN32 = 'WIN32',
|
||||
ANDROID = 'ANDROID',
|
||||
IOS = 'IOS',
|
||||
MACOS = 'MACOS',
|
||||
OHOS = 'OHOS',
|
||||
OPENHARMONY = 'OPENHARMONY',
|
||||
// Minigame
|
||||
WECHAT_GAME = 'WECHAT_GAME',
|
||||
WECHAT_MINI_PROGRAM = 'WECHAT_MINI_PROGRAM',
|
||||
XIAOMI_QUICK_GAME = 'XIAOMI_QUICK_GAME',
|
||||
ALIPAY_MINI_GAME = 'ALIPAY_MINI_GAME',
|
||||
TAOBAO_CREATIVE_APP = 'TAOBAO_CREATIVE_APP',
|
||||
TAOBAO_MINI_GAME = 'TAOBAO_MINI_GAME',
|
||||
BYTEDANCE_MINI_GAME = 'BYTEDANCE_MINI_GAME',
|
||||
// Runtime Based
|
||||
OPPO_MINI_GAME = 'OPPO_MINI_GAME',
|
||||
VIVO_MINI_GAME = 'VIVO_MINI_GAME',
|
||||
HUAWEI_QUICK_GAME = 'HUAWEI_QUICK_GAME',
|
||||
MIGU_MINI_GAME = 'MIGU_MINI_GAME',
|
||||
HONOR_MINI_GAME = 'HONOR_MINI_GAME',
|
||||
SUD_MINI_GAME = 'SUD_MINI_GAME',
|
||||
SUDV2_MINI_GAME = 'SUDV2_MINI_GAME',
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ALIPAY, BYTEDANCE, HUAWEI, OPPO, RUNTIME_BASED, SUD, SUDV2, VIVO, MIGU, HONOR, WECHAT, XIAOMI, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { minigame, SystemInfo as MinigameSystemInfo, WindowInfo } from 'pal/minigame';
|
||||
import { IFeatureMap } from 'pal/system-info';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type';
|
||||
import { warn } from '../../../cocos/core/platform/debug';
|
||||
import { versionCompare } from '../../utils';
|
||||
|
||||
// NOTE: register minigame platform here
|
||||
let currentPlatform: Platform;
|
||||
if (WECHAT) {
|
||||
currentPlatform = Platform.WECHAT_GAME;
|
||||
} else if (WECHAT_MINI_PROGRAM) {
|
||||
currentPlatform = Platform.WECHAT_MINI_PROGRAM;
|
||||
} else if (XIAOMI) {
|
||||
currentPlatform = Platform.XIAOMI_QUICK_GAME;
|
||||
} else if (ALIPAY) {
|
||||
currentPlatform = Platform.ALIPAY_MINI_GAME;
|
||||
} else if (TAOBAO) {
|
||||
currentPlatform = Platform.TAOBAO_CREATIVE_APP;
|
||||
} else if (TAOBAO_MINIGAME) {
|
||||
currentPlatform = Platform.TAOBAO_MINI_GAME;
|
||||
} else if (BYTEDANCE) {
|
||||
currentPlatform = Platform.BYTEDANCE_MINI_GAME;
|
||||
} else if (OPPO) {
|
||||
currentPlatform = Platform.OPPO_MINI_GAME;
|
||||
} else if (VIVO) {
|
||||
currentPlatform = Platform.VIVO_MINI_GAME;
|
||||
} else if (HUAWEI) {
|
||||
currentPlatform = Platform.HUAWEI_QUICK_GAME;
|
||||
} else if (MIGU) {
|
||||
currentPlatform = Platform.MIGU_MINI_GAME;
|
||||
} else if (HONOR) {
|
||||
currentPlatform = Platform.HONOR_MINI_GAME;
|
||||
} else if (SUD) {
|
||||
currentPlatform = Platform.SUD_MINI_GAME;
|
||||
} else if (SUDV2) {
|
||||
currentPlatform = Platform.SUDV2_MINI_GAME;
|
||||
}
|
||||
|
||||
let isVersionGreaterOrEqualTo;
|
||||
if (BYTEDANCE) {
|
||||
isVersionGreaterOrEqualTo = function isVersionGreaterOrEqualTo (versionA: string, versionB: string): boolean {
|
||||
if (!versionA || !versionB) {
|
||||
return false;
|
||||
}
|
||||
// Split the version number string into an array of integers
|
||||
function parseVersion (version: string): number[] {
|
||||
return version.split('.').map((part: string) => parseInt(part, 10));
|
||||
}
|
||||
|
||||
// Parse the version number strings into arrays
|
||||
const versionArrayA = parseVersion(versionA);
|
||||
const versionArrayB = parseVersion(versionB);
|
||||
|
||||
if (versionArrayA.length !== versionArrayB.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compare versions level by level
|
||||
for (let i = 0; i < versionArrayA.length; i++) {
|
||||
if (versionArrayA[i] > versionArrayB[i]) {
|
||||
// versionA > versionB
|
||||
return true;
|
||||
} else if (versionArrayA[i] < versionArrayB[i]) {
|
||||
// versionA < versionB
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// versionA === versionB
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
const originalGetSystemInfoSync = minigame.getSystemInfoSync;
|
||||
// Some platforms may not have this interface(getWindowInfo).
|
||||
const originalGetWindowInfo = minigame.getWindowInfo;
|
||||
let _cachedSystemInfo: MinigameSystemInfo = originalGetSystemInfoSync.call(minigame);
|
||||
let _cachedWindowInfo: WindowInfo | undefined = originalGetWindowInfo?.call(minigame);
|
||||
|
||||
function testAndUpdateSystemInfoCache (testAmount: number, testInterval: number): void {
|
||||
let successfullyTestTimes = 0;
|
||||
let intervalTimer: number | null = null;
|
||||
function testCachedSystemInfo (): void {
|
||||
const currentSystemInfo = originalGetSystemInfoSync.call(minigame);
|
||||
if (_cachedSystemInfo.screenWidth === currentSystemInfo.screenWidth && _cachedSystemInfo.screenHeight === currentSystemInfo.screenHeight) {
|
||||
if (++successfullyTestTimes >= testAmount && intervalTimer !== null) {
|
||||
clearInterval(intervalTimer);
|
||||
intervalTimer = null;
|
||||
}
|
||||
} else {
|
||||
successfullyTestTimes = 0;
|
||||
}
|
||||
_cachedSystemInfo = currentSystemInfo;
|
||||
}
|
||||
intervalTimer = setInterval(testCachedSystemInfo, testInterval);
|
||||
}
|
||||
|
||||
if (WECHAT && versionCompare(minigame.getAppBaseInfo().SDKVersion, '2.25.3') < 0) {
|
||||
testAndUpdateSystemInfoCache(10, 500);
|
||||
}
|
||||
|
||||
minigame.onWindowResize?.(() => {
|
||||
// update cached system info
|
||||
_cachedSystemInfo = originalGetSystemInfoSync.call(minigame);
|
||||
_cachedWindowInfo = originalGetWindowInfo?.call(minigame);
|
||||
});
|
||||
|
||||
minigame.getSystemInfoSync = function (): MinigameSystemInfo {
|
||||
return _cachedSystemInfo;
|
||||
};
|
||||
|
||||
if (originalGetWindowInfo !== undefined) {
|
||||
minigame.getWindowInfo = function (): WindowInfo {
|
||||
return _cachedWindowInfo!;
|
||||
};
|
||||
}
|
||||
|
||||
class SystemInfo extends EventTarget {
|
||||
public declare readonly networkType: NetworkType;
|
||||
public declare readonly isNative: boolean;
|
||||
public declare readonly isBrowser: boolean;
|
||||
public declare readonly isMobile: boolean;
|
||||
public declare readonly isLittleEndian: boolean;
|
||||
public declare readonly platform: Platform;
|
||||
public declare readonly language: Language;
|
||||
public declare readonly nativeLanguage: string;
|
||||
public declare readonly os: OS;
|
||||
public declare readonly osVersion: string;
|
||||
public declare readonly osMainVersion: number;
|
||||
public declare readonly browserType: BrowserType;
|
||||
public declare readonly browserVersion: string;
|
||||
public declare readonly isXR: boolean;
|
||||
private declare _featureMap: IFeatureMap;
|
||||
private _initPromise: Promise<void>[] = [];
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
const minigameSysInfo = minigame.getSystemInfoSync();
|
||||
this.networkType = NetworkType.LAN; // TODO
|
||||
this.isNative = false;
|
||||
this.isBrowser = false;
|
||||
|
||||
// init isLittleEndian
|
||||
this.isLittleEndian = ((): boolean => {
|
||||
const buffer = new ArrayBuffer(2);
|
||||
new DataView(buffer).setInt16(0, 256, true);
|
||||
// Int16Array uses the platform's endianness.
|
||||
return new Int16Array(buffer)[0] === 256;
|
||||
})();
|
||||
|
||||
// init languageCode and language
|
||||
this.nativeLanguage = minigameSysInfo.language;
|
||||
this.language = minigameSysInfo.language.substring(0, 2) as Language;
|
||||
|
||||
// init os, osVersion and osMainVersion
|
||||
const minigamePlatform = minigameSysInfo.platform.toLocaleLowerCase();
|
||||
switch (minigamePlatform) {
|
||||
case 'android':
|
||||
this.os = OS.ANDROID;
|
||||
break;
|
||||
case 'ios':
|
||||
this.os = OS.IOS;
|
||||
break;
|
||||
case 'windows':
|
||||
this.os = OS.WINDOWS;
|
||||
break;
|
||||
case 'mac':
|
||||
this.os = OS.OSX;
|
||||
break;
|
||||
default:
|
||||
this.os = OS.UNKNOWN;
|
||||
break;
|
||||
}
|
||||
|
||||
let minigameSystem = minigameSysInfo.system.toLowerCase();
|
||||
// Adaptation to Android P
|
||||
if (minigameSystem === 'android p') {
|
||||
minigameSystem = 'android p 9.0';
|
||||
}
|
||||
const version = /[\d.]+/.exec(minigameSystem);
|
||||
this.osVersion = version ? version[0] : minigameSystem;
|
||||
this.osMainVersion = parseInt(this.osVersion);
|
||||
|
||||
// init isMobile and platform
|
||||
this.platform = currentPlatform;
|
||||
// Some minigame platforms don't support getting the platform, such as runtime and Xiaomi, so this.os returns UNKNOWN.
|
||||
// Most platforms are mobile, so set UNKNOWN to mobile.
|
||||
this.isMobile = this.os === OS.ANDROID || this.os === OS.IOS || this.os === OS.UNKNOWN;
|
||||
|
||||
// init browserType and browserVersion
|
||||
this.browserType = BrowserType.UNKNOWN;
|
||||
this.browserVersion = '';
|
||||
|
||||
this.isXR = false;
|
||||
|
||||
const isPCWechat = WECHAT && this.os === OS.WINDOWS && !minigame.isDevTool;
|
||||
|
||||
const supportWasm = ((): boolean => {
|
||||
if (WECHAT) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (BYTEDANCE) {
|
||||
let minSDKVersionSupportWasm = '';
|
||||
if (this.os === OS.ANDROID) {
|
||||
minSDKVersionSupportWasm = '3.9.0';
|
||||
} else if (this.os === OS.IOS) {
|
||||
minSDKVersionSupportWasm = '3.8.0';
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error TTWebAssembly is defined if bytedance client supports wasm.
|
||||
if (isVersionGreaterOrEqualTo(minigameSysInfo.SDKVersion, minSDKVersionSupportWasm) && typeof TTWebAssembly === 'object') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (RUNTIME_BASED) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error ral.WebAssembly is defined if runtime based platform supports wasm.
|
||||
if (typeof ral.WebAssembly === 'object') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
})();
|
||||
|
||||
this._featureMap = {
|
||||
[Feature.WEBP]: false, // Initialize in Promise,
|
||||
[Feature.IMAGE_BITMAP]: false,
|
||||
[Feature.WEB_VIEW]: false,
|
||||
[Feature.VIDEO_PLAYER]: WECHAT || WECHAT_MINI_PROGRAM || OPPO,
|
||||
[Feature.SAFE_AREA]: WECHAT || WECHAT_MINI_PROGRAM || BYTEDANCE,
|
||||
[Feature.HPE]: false,
|
||||
|
||||
[Feature.INPUT_TOUCH]: !isPCWechat,
|
||||
[Feature.EVENT_KEYBOARD]: isPCWechat,
|
||||
[Feature.EVENT_MOUSE]: isPCWechat,
|
||||
[Feature.EVENT_TOUCH]: true,
|
||||
[Feature.EVENT_ACCELEROMETER]: !isPCWechat,
|
||||
[Feature.EVENT_GAMEPAD]: false,
|
||||
[Feature.EVENT_HANDLE]: this.isXR,
|
||||
[Feature.EVENT_HMD]: this.isXR,
|
||||
[Feature.EVENT_HANDHELD]: false,
|
||||
[Feature.WASM]: supportWasm,
|
||||
};
|
||||
|
||||
this._initPromise.push(this._supportsWebpPromise());
|
||||
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _supportsWebpPromise (): Promise<void> {
|
||||
if (!TEST) {
|
||||
return this._supportsWebp().then((isSupport) => {
|
||||
this._setFeature(Feature.WEBP, isSupport);
|
||||
});
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private _supportsWebp (): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve, reject) => {
|
||||
if (WECHAT_MINI_PROGRAM) {
|
||||
resolve(true);
|
||||
return;
|
||||
}
|
||||
// HACK: webp base64 doesn't support on Wechat Android, which reports some internal error log.
|
||||
if (WECHAT && this.os === OS.ANDROID) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const img = document.createElement('img');
|
||||
const timer = setTimeout((): void => {
|
||||
resolve(false);
|
||||
}, 500);
|
||||
img.onload = function onload (): void {
|
||||
clearTimeout(timer);
|
||||
const result = (img.width > 0) && (img.height > 0);
|
||||
resolve(result);
|
||||
};
|
||||
img.onerror = function onerror (err): void {
|
||||
clearTimeout(timer);
|
||||
if (DEBUG) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
||||
warn('Create Webp image failed, message: '.concat(err.toString()));
|
||||
}
|
||||
resolve(false);
|
||||
};
|
||||
img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
|
||||
} catch (error) {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
minigame.onHide((): void => {
|
||||
this.emit('hide');
|
||||
});
|
||||
minigame.onShow((): void => {
|
||||
this.emit('show');
|
||||
});
|
||||
}
|
||||
|
||||
private _setFeature (feature: Feature, value: boolean): boolean {
|
||||
return this._featureMap[feature] = value;
|
||||
}
|
||||
|
||||
public init (): Promise<void[]> {
|
||||
return Promise.all(this._initPromise);
|
||||
}
|
||||
|
||||
public hasFeature (feature: Feature): boolean {
|
||||
return this._featureMap[feature];
|
||||
}
|
||||
|
||||
public getBatteryLevel (): number {
|
||||
return minigame.getBatteryInfoSync().level / 100;
|
||||
}
|
||||
public triggerGC (): void {
|
||||
minigame.triggerGC?.();
|
||||
}
|
||||
public openURL (url: string): void {
|
||||
if (DEBUG) {
|
||||
warn('openURL is not supported');
|
||||
}
|
||||
}
|
||||
public now (): number {
|
||||
if (Date.now) {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
return +(new Date());
|
||||
}
|
||||
public restartJSVM (): void {
|
||||
if (DEBUG) {
|
||||
warn('restartJSVM is not supported.');
|
||||
}
|
||||
}
|
||||
|
||||
public exit (): void {
|
||||
minigame.exitMiniProgram?.();
|
||||
}
|
||||
|
||||
public close (): void {
|
||||
// TODO(qgh):The minigame platform does not have an exit interface,
|
||||
// so there is no need to send a close message to the engine to release resources.
|
||||
// this.emit('close');
|
||||
this.exit();
|
||||
}
|
||||
}
|
||||
|
||||
export const systemInfo = new SystemInfo();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/system-info')>(withImpl<typeof import('./system-info')>());
|
||||
@@ -1,199 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { OPEN_HARMONY, IOS } from 'internal:constants';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type';
|
||||
|
||||
type IFeatureMap = {
|
||||
[feature in Feature]: boolean;
|
||||
};
|
||||
|
||||
// NOTE: these methods are implemented on native.
|
||||
declare function __getPlatform(): string;
|
||||
declare function __getCurrentLanguageCode(): string;
|
||||
declare function __getCurrentLanguage(): Language;
|
||||
declare function __getOS(): OS;
|
||||
declare function __getOSVersion(): string;
|
||||
declare const __supportHPE: (() => boolean) | undefined;
|
||||
declare function __restartVM(): void;
|
||||
declare function __close(): void;
|
||||
declare function __exit(): void;
|
||||
|
||||
const networkTypeMap: Record<string, NetworkType> = {
|
||||
0: NetworkType.NONE,
|
||||
1: NetworkType.LAN,
|
||||
2: NetworkType.WWAN,
|
||||
};
|
||||
const platformMap: Record<number, Platform> = {
|
||||
0: Platform.WIN32,
|
||||
// 1 is Linux platform in native engine
|
||||
2: Platform.MACOS,
|
||||
3: Platform.ANDROID,
|
||||
// 4 is IPHONE
|
||||
4: Platform.IOS,
|
||||
// 5 is IPAD
|
||||
5: Platform.IOS,
|
||||
6: Platform.OHOS,
|
||||
7: Platform.OPENHARMONY,
|
||||
};
|
||||
|
||||
class SystemInfo extends EventTarget {
|
||||
public declare readonly isNative: boolean;
|
||||
public declare readonly isBrowser: boolean;
|
||||
public declare readonly isMobile: boolean;
|
||||
public declare readonly isLittleEndian: boolean;
|
||||
public declare readonly platform: Platform;
|
||||
public declare readonly language: Language;
|
||||
public declare readonly nativeLanguage: string;
|
||||
public declare readonly os: OS;
|
||||
public declare readonly osVersion: string;
|
||||
public declare readonly osMainVersion: number;
|
||||
public declare readonly browserType: BrowserType;
|
||||
public declare readonly browserVersion: string;
|
||||
public declare readonly isXR: boolean;
|
||||
private declare _featureMap: IFeatureMap;
|
||||
private _initPromise: Promise<void>[] = [];
|
||||
// TODO: need to wrap the function __isObjectValid()
|
||||
|
||||
public get networkType (): NetworkType {
|
||||
return networkTypeMap[jsb.device.getNetworkType()];
|
||||
}
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
this.isNative = true;
|
||||
this.isBrowser = false;
|
||||
|
||||
this.platform = platformMap[__getPlatform()];
|
||||
// eslint-disable-next-line max-len
|
||||
this.isMobile = this.platform === Platform.ANDROID || this.platform === Platform.IOS || this.platform === Platform.OHOS || this.platform === Platform.OPENHARMONY;
|
||||
|
||||
// init isLittleEndian
|
||||
this.isLittleEndian = ((): boolean => {
|
||||
const buffer = new ArrayBuffer(2);
|
||||
new DataView(buffer).setInt16(0, 256, true);
|
||||
// Int16Array uses the platform's endianness.
|
||||
return new Int16Array(buffer)[0] === 256;
|
||||
})();
|
||||
|
||||
// init languageCode and language
|
||||
const currLanguage = __getCurrentLanguageCode();
|
||||
this.nativeLanguage = currLanguage ? currLanguage.toLowerCase() : Language.UNKNOWN;
|
||||
this.language = __getCurrentLanguage();
|
||||
|
||||
this.os = __getOS();
|
||||
this.osVersion = __getOSVersion();
|
||||
this.osMainVersion = parseInt(this.osVersion);
|
||||
|
||||
// init browserType and browserVersion
|
||||
this.browserType = BrowserType.UNKNOWN;
|
||||
this.browserVersion = '';
|
||||
|
||||
this.isXR = (typeof xr !== 'undefined' && typeof xr.XrEntry !== 'undefined');
|
||||
|
||||
const isHPE: boolean = typeof __supportHPE === 'function' ? __supportHPE() : false;
|
||||
const isHarmonyOSNext = this.platform === Platform.OPENHARMONY;
|
||||
|
||||
this._featureMap = {
|
||||
[Feature.WEBP]: true,
|
||||
[Feature.IMAGE_BITMAP]: false,
|
||||
[Feature.WEB_VIEW]: this.isMobile,
|
||||
[Feature.VIDEO_PLAYER]: this.isMobile,
|
||||
[Feature.SAFE_AREA]: this.isMobile,
|
||||
[Feature.HPE]: isHPE,
|
||||
|
||||
[Feature.INPUT_TOUCH]: this.isMobile,
|
||||
[Feature.EVENT_KEYBOARD]: true,
|
||||
[Feature.EVENT_MOUSE]: isHPE || !this.isMobile || isHarmonyOSNext,
|
||||
[Feature.EVENT_TOUCH]: true,
|
||||
[Feature.EVENT_ACCELEROMETER]: this.isMobile,
|
||||
[Feature.EVENT_GAMEPAD]: true,
|
||||
[Feature.EVENT_HANDLE]: this.isXR,
|
||||
[Feature.EVENT_HMD]: this.isXR,
|
||||
[Feature.EVENT_HANDHELD]: (typeof xr !== 'undefined' && typeof xr.ARModule !== 'undefined'),
|
||||
// Although the iOS OS supports WASM, the engine does not yet support loading WASM on this platform.
|
||||
[Feature.WASM]: !OPEN_HARMONY && !IOS,
|
||||
};
|
||||
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
jsb.onPause = (): void => {
|
||||
this.emit('hide');
|
||||
};
|
||||
jsb.onResume = (): void => {
|
||||
this.emit('show');
|
||||
};
|
||||
jsb.onClose = (): void => {
|
||||
this.emit('close');
|
||||
};
|
||||
}
|
||||
|
||||
private _setFeature (feature: Feature, value: boolean): boolean {
|
||||
return this._featureMap[feature] = value;
|
||||
}
|
||||
|
||||
public init (): Promise<void[]> {
|
||||
return Promise.all(this._initPromise);
|
||||
}
|
||||
|
||||
public hasFeature (feature: Feature): boolean {
|
||||
return this._featureMap[feature];
|
||||
}
|
||||
|
||||
public getBatteryLevel (): number {
|
||||
return jsb.device.getBatteryLevel();
|
||||
}
|
||||
public triggerGC (): void {
|
||||
jsb.garbageCollect();
|
||||
}
|
||||
public openURL (url: string): void {
|
||||
jsb.openURL(url);
|
||||
}
|
||||
public now (): number {
|
||||
if (Date.now) {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
return +(new Date());
|
||||
}
|
||||
public restartJSVM (): void {
|
||||
__restartVM();
|
||||
}
|
||||
|
||||
public close (): void {
|
||||
__close();
|
||||
}
|
||||
|
||||
public exit (): void {
|
||||
__exit();
|
||||
}
|
||||
}
|
||||
|
||||
export const systemInfo = new SystemInfo();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/system-info')>(withImpl<typeof import('./system-info')>());
|
||||
@@ -1,164 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
import { DEBUG } from 'internal:constants';
|
||||
import { IFeatureMap } from 'pal/system-info';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type';
|
||||
import { warn } from '../../../cocos/core/platform/debug';
|
||||
|
||||
class SystemInfo extends EventTarget {
|
||||
public declare readonly networkType: NetworkType;
|
||||
public declare readonly isNative: boolean;
|
||||
public declare readonly isBrowser: boolean;
|
||||
public declare readonly isMobile: boolean;
|
||||
public declare readonly isLittleEndian: boolean;
|
||||
public declare readonly platform: Platform;
|
||||
public declare readonly language: Language;
|
||||
public declare readonly nativeLanguage: string;
|
||||
public declare readonly os: OS;
|
||||
public declare readonly osVersion: string;
|
||||
public declare readonly osMainVersion: number;
|
||||
public declare readonly browserType: BrowserType;
|
||||
public declare readonly browserVersion: string;
|
||||
public declare readonly isXR: boolean;
|
||||
private declare _featureMap: IFeatureMap;
|
||||
private _initPromise: Promise<void>[] = [];
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
|
||||
this.networkType = NetworkType.LAN; // TODO
|
||||
this.isNative = false;
|
||||
this.isBrowser = false;
|
||||
|
||||
this.isMobile = false;
|
||||
this.platform = Platform.NODEJS_PAGE; // TODO
|
||||
|
||||
this.browserType = BrowserType.UNKNOWN;
|
||||
this.browserVersion = '';
|
||||
|
||||
const osInfo = globalThis.nodeEnv.require('os');
|
||||
let osName = OS.UNKNOWN;
|
||||
if (osInfo.type().indexOf('wiWindows_NTn') !== -1) {
|
||||
osName = OS.WINDOWS;
|
||||
} else if (osInfo.type().indexOf('Darwin') !== -1) {
|
||||
osName = OS.OSX;
|
||||
} else if (osInfo.type().indexOf('Linux') !== -1) {
|
||||
osName = OS.LINUX;
|
||||
}
|
||||
this.os = osName;
|
||||
this.osVersion = osInfo.release();
|
||||
this.osMainVersion = parseInt(this.osVersion);
|
||||
|
||||
// init isLittleEndian
|
||||
this.isLittleEndian = ((): boolean => {
|
||||
const buffer = new ArrayBuffer(2);
|
||||
new DataView(buffer).setInt16(0, 256, true);
|
||||
// Int16Array uses the platform's endianness.
|
||||
return new Int16Array(buffer)[0] === 256;
|
||||
})();
|
||||
|
||||
// init languageCode and language
|
||||
let currLanguage = globalThis.nodeEnv.systemLanguage;
|
||||
this.nativeLanguage = currLanguage.toLowerCase();
|
||||
currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH;
|
||||
this.language = currLanguage as Language;
|
||||
|
||||
this.isXR = false;
|
||||
this._featureMap = {
|
||||
[Feature.WEBP]: true,
|
||||
[Feature.IMAGE_BITMAP]: false,
|
||||
[Feature.WEB_VIEW]: false,
|
||||
[Feature.VIDEO_PLAYER]: false,
|
||||
[Feature.SAFE_AREA]: false,
|
||||
[Feature.HPE]: false,
|
||||
|
||||
[Feature.INPUT_TOUCH]: false,
|
||||
[Feature.EVENT_KEYBOARD]: false,
|
||||
[Feature.EVENT_MOUSE]: false,
|
||||
[Feature.EVENT_TOUCH]: false,
|
||||
[Feature.EVENT_ACCELEROMETER]: false,
|
||||
// NOTE: webkitGetGamepads is not standard web interface
|
||||
[Feature.EVENT_GAMEPAD]: false,
|
||||
[Feature.EVENT_HANDLE]: false,
|
||||
[Feature.EVENT_HMD]: false,
|
||||
[Feature.EVENT_HANDHELD]: false,
|
||||
[Feature.WASM]: true,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
public init (): Promise<void[]> {
|
||||
return Promise.all(this._initPromise);
|
||||
}
|
||||
|
||||
public hasFeature (feature: Feature): boolean {
|
||||
return this._featureMap[feature];
|
||||
}
|
||||
|
||||
public getBatteryLevel (): number {
|
||||
if (DEBUG) {
|
||||
warn("getBatteryLevel is not supported.");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
public triggerGC (): void {
|
||||
if (global.gc) {
|
||||
global.gc();
|
||||
}
|
||||
}
|
||||
|
||||
public openURL (url: string): void {
|
||||
var open = globalThis.nodeEnv.require('open');
|
||||
open(url);
|
||||
}
|
||||
|
||||
public now (): number {
|
||||
if (Date.now) {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
return +(new Date());
|
||||
}
|
||||
|
||||
public restartJSVM (): void {
|
||||
if (DEBUG) {
|
||||
warn('restartJSVM is not supported.');
|
||||
}
|
||||
}
|
||||
|
||||
public exit (): void {
|
||||
globalThis.nodeEnv.process.exit();
|
||||
}
|
||||
|
||||
public close (): void {
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
export const systemInfo = new SystemInfo();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/system-info')>(withImpl<typeof import('./system-info')>());
|
||||
@@ -1,401 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { DEBUG, EDITOR, PREVIEW, TEST } from 'internal:constants';
|
||||
import { IFeatureMap } from 'pal/system-info';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
import { checkPalIntegrity, withImpl } from '../../integrity-check';
|
||||
import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../enum-type';
|
||||
import { warn } from '../../../cocos/core/platform/debug';
|
||||
|
||||
class SystemInfo extends EventTarget {
|
||||
public declare readonly networkType: NetworkType;
|
||||
public declare readonly isNative: boolean;
|
||||
public declare readonly isBrowser: boolean;
|
||||
public declare readonly isMobile: boolean;
|
||||
public declare readonly isLittleEndian: boolean;
|
||||
public declare readonly platform: Platform;
|
||||
public declare readonly language: Language;
|
||||
public declare readonly nativeLanguage: string;
|
||||
public declare readonly os: OS;
|
||||
public declare readonly osVersion: string;
|
||||
public declare readonly osMainVersion: number;
|
||||
public declare readonly browserType: BrowserType;
|
||||
public declare readonly browserVersion: string;
|
||||
public declare readonly isXR: boolean;
|
||||
private _battery: any = null;
|
||||
private declare _featureMap: IFeatureMap;
|
||||
private _initPromise: Promise<void>[] = [];
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
const nav = window.navigator;
|
||||
const ua = nav.userAgent.toLowerCase();
|
||||
// NOTE: getBattery is not totally supported on Web standard
|
||||
(nav as any).getBattery?.().then((battery) => {
|
||||
this._battery = battery;
|
||||
});
|
||||
|
||||
this.networkType = NetworkType.LAN; // TODO
|
||||
this.isNative = false;
|
||||
this.isBrowser = true;
|
||||
|
||||
// init isMobile and platform
|
||||
if (EDITOR) {
|
||||
this.isMobile = false;
|
||||
this.platform = Platform.EDITOR_PAGE; // TODO
|
||||
} else {
|
||||
this.isMobile = /mobile|android|iphone|ipad/.test(ua);
|
||||
this.platform = this.isMobile ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER;
|
||||
}
|
||||
|
||||
// init isLittleEndian
|
||||
this.isLittleEndian = ((): boolean => {
|
||||
const buffer = new ArrayBuffer(2);
|
||||
new DataView(buffer).setInt16(0, 256, true);
|
||||
// Int16Array uses the platform's endianness.
|
||||
return new Int16Array(buffer)[0] === 256;
|
||||
})();
|
||||
|
||||
// init languageCode and language
|
||||
let currLanguage = nav.language;
|
||||
this.nativeLanguage = currLanguage.toLowerCase();
|
||||
currLanguage = currLanguage || (nav as any).browserLanguage;
|
||||
currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH;
|
||||
this.language = currLanguage as Language;
|
||||
|
||||
// init os, osVersion and osMainVersion
|
||||
let isAndroid = false; let iOS = false; let osVersion = ''; let osMajorVersion = 0;
|
||||
let uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform);
|
||||
if (uaResult) {
|
||||
isAndroid = true;
|
||||
osVersion = uaResult[1] || '';
|
||||
osMajorVersion = parseInt(osVersion) || 0;
|
||||
}
|
||||
uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);
|
||||
if (uaResult) {
|
||||
iOS = true;
|
||||
osVersion = uaResult[2] || '';
|
||||
osMajorVersion = parseInt(osVersion) || 0;
|
||||
// refer to https://github.com/cocos-creator/engine/pull/5542 , thanks for contribition from @krapnikkk
|
||||
// ipad OS 13 safari identifies itself as "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko)"
|
||||
// so use maxTouchPoints to check whether it's desktop safari or not.
|
||||
// reference: https://stackoverflow.com/questions/58019463/how-to-detect-device-name-in-safari-on-ios-13-while-it-doesnt-show-the-correct
|
||||
// FIXME: should remove it when touch-enabled mac are available
|
||||
// TODO: due to compatibility issues, it is still determined to be ios, and a new operating system type ipados may be added later?
|
||||
} else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || (nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1)) {
|
||||
iOS = true;
|
||||
osVersion = '';
|
||||
osMajorVersion = 0;
|
||||
}
|
||||
|
||||
let osName = OS.UNKNOWN;
|
||||
if (nav.appVersion.indexOf('Win') !== -1) {
|
||||
osName = OS.WINDOWS;
|
||||
} else if (iOS) {
|
||||
osName = OS.IOS;
|
||||
} else if (nav.appVersion.indexOf('Mac') !== -1) {
|
||||
osName = OS.OSX;
|
||||
} else if (nav.appVersion.indexOf('X11') !== -1 && nav.appVersion.indexOf('Linux') === -1) {
|
||||
osName = OS.LINUX;
|
||||
} else if (isAndroid) {
|
||||
osName = OS.ANDROID;
|
||||
} else if (nav.appVersion.indexOf('Linux') !== -1 || ua.indexOf('ubuntu') !== -1) {
|
||||
osName = OS.LINUX;
|
||||
}
|
||||
|
||||
this.os = osName;
|
||||
this.osVersion = osVersion;
|
||||
this.osMainVersion = osMajorVersion;
|
||||
|
||||
// TODO: use dack-type to determine the browserType
|
||||
// init browserType and browserVersion
|
||||
this.browserType = BrowserType.UNKNOWN;
|
||||
const typeReg0 = /wechat|weixin|micromessenger/i;
|
||||
const typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i;
|
||||
const typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge|HuaweiBrowser/i;
|
||||
const typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i;
|
||||
const browserTypes = typeReg0.exec(ua) || typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua);
|
||||
|
||||
let browserType = browserTypes ? browserTypes[0].toLowerCase() : OS.UNKNOWN;
|
||||
if (browserType === 'safari' && isAndroid) {
|
||||
browserType = BrowserType.ANDROID;
|
||||
} else if (browserType === 'qq' && /android.*applewebkit/i.test(ua)) {
|
||||
browserType = BrowserType.ANDROID;
|
||||
}
|
||||
const typeMap = {
|
||||
micromessenger: BrowserType.WECHAT,
|
||||
wechat: BrowserType.WECHAT,
|
||||
weixin: BrowserType.WECHAT,
|
||||
trident: BrowserType.IE,
|
||||
edge: BrowserType.EDGE,
|
||||
'360 aphone': BrowserType.BROWSER_360,
|
||||
mxbrowser: BrowserType.MAXTHON,
|
||||
'opr/': BrowserType.OPERA,
|
||||
ubrowser: BrowserType.UC,
|
||||
huaweibrowser: BrowserType.HUAWEI,
|
||||
};
|
||||
|
||||
this.browserType = typeMap[browserType] || browserType;
|
||||
|
||||
// init browserVersion
|
||||
this.browserVersion = '';
|
||||
const versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i;
|
||||
const versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i;
|
||||
let tmp = versionReg1.exec(ua);
|
||||
if (!tmp) {
|
||||
tmp = versionReg2.exec(ua);
|
||||
}
|
||||
this.browserVersion = tmp ? tmp[4] : '';
|
||||
|
||||
this.isXR = false;
|
||||
|
||||
// init capability
|
||||
const _tmpCanvas1 = document.createElement('canvas');
|
||||
const supportCanvas = TEST ? false : !!_tmpCanvas1.getContext('2d');
|
||||
let supportWebGL = false;
|
||||
if (TEST) {
|
||||
supportWebGL = false;
|
||||
} else if (window.WebGLRenderingContext) {
|
||||
supportWebGL = true;
|
||||
}
|
||||
let supportWebp;
|
||||
try {
|
||||
supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp');
|
||||
} catch (e) {
|
||||
supportWebp = false;
|
||||
}
|
||||
if (this.os === OS.IOS) {
|
||||
// if we're on iOS all major browsers will identify as BrowserType.SAFARI but Chrome and Firefox DO NOT have the
|
||||
// version in the browser identifier, using "applewebkit" solves this issue for all browsers on iOS
|
||||
const result = / applewebkit\/(\d+)/.exec(ua)?.[1];
|
||||
if (typeof result === 'string') {
|
||||
if (Number.parseInt(result) >= 604) {
|
||||
// safari 14+ support webp, but canvas.toDataURL is not supported by default
|
||||
supportWebp = true;
|
||||
}
|
||||
}
|
||||
} else if (this.browserType === BrowserType.SAFARI) {
|
||||
//non-ios safari (desktop)
|
||||
const result = / version\/(\d+)/.exec(ua)?.[1];
|
||||
if (typeof result === 'string') {
|
||||
if (Number.parseInt(result) >= 14) {
|
||||
// safari 14+ support webp, but canvas.toDataURL is not supported by default
|
||||
supportWebp = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const supportTouch = (document.documentElement.ontouchstart !== undefined || document.ontouchstart !== undefined || EDITOR);
|
||||
const supportMouse = document.documentElement.onmouseup !== undefined || EDITOR;
|
||||
// NOTE: xr is not totally supported on web
|
||||
const supportXR = typeof (navigator as any).xr !== 'undefined';
|
||||
// refer https://stackoverflow.com/questions/47879864/how-can-i-check-if-a-browser-supports-webassembly
|
||||
const supportWasm = ((): boolean => {
|
||||
// NOTE: safari on iOS 15.4 and MacOS 15.4 has some wasm memory issue, can not use wasm for bullet
|
||||
const isSafari_15_4 = (this.os === OS.IOS || this.os === OS.OSX) && /(OS 15_4)|(Version\/15.4)/.test(window.navigator.userAgent);
|
||||
if (isSafari_15_4) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
if (typeof WebAssembly === 'object'
|
||||
&& typeof WebAssembly.instantiate === 'function') {
|
||||
const module = new WebAssembly.Module(new Uint8Array([0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
|
||||
if (module instanceof WebAssembly.Module) {
|
||||
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
})();
|
||||
this._featureMap = {
|
||||
[Feature.WEBP]: supportWebp,
|
||||
[Feature.IMAGE_BITMAP]: false, // Initialize in Promise
|
||||
[Feature.WEB_VIEW]: true,
|
||||
[Feature.VIDEO_PLAYER]: true,
|
||||
[Feature.SAFE_AREA]: false,
|
||||
[Feature.HPE]: false,
|
||||
|
||||
[Feature.INPUT_TOUCH]: supportTouch,
|
||||
[Feature.EVENT_KEYBOARD]: document.documentElement.onkeyup !== undefined || EDITOR,
|
||||
[Feature.EVENT_MOUSE]: supportMouse,
|
||||
[Feature.EVENT_TOUCH]: supportTouch || supportMouse,
|
||||
[Feature.EVENT_ACCELEROMETER]: (window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined),
|
||||
// NOTE: webkitGetGamepads is not standard web interface
|
||||
[Feature.EVENT_GAMEPAD]: (navigator.getGamepads !== undefined || (navigator as any).webkitGetGamepads !== undefined || supportXR),
|
||||
[Feature.EVENT_HANDLE]: EDITOR || PREVIEW,
|
||||
[Feature.EVENT_HMD]: supportXR,
|
||||
[Feature.EVENT_HANDHELD]: supportXR,
|
||||
[Feature.WASM]: supportWasm,
|
||||
};
|
||||
|
||||
this._initPromise.push(this._supportsImageBitmapPromise());
|
||||
|
||||
this._registerEvent();
|
||||
}
|
||||
|
||||
private _supportsImageBitmapPromise (): Promise<void> {
|
||||
if (!TEST && typeof createImageBitmap !== 'undefined' && typeof Blob !== 'undefined') {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = canvas.height = 2;
|
||||
const promise = createImageBitmap(canvas);
|
||||
if (promise instanceof Promise) {
|
||||
return promise.then((imageBitmap) => {
|
||||
if (imageBitmap && imageBitmap.close) {
|
||||
this._setFeature(Feature.IMAGE_BITMAP, true);
|
||||
imageBitmap.close();
|
||||
}
|
||||
});
|
||||
} else if (DEBUG) {
|
||||
warn('The return value of createImageBitmap is not Promise.');
|
||||
}
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private _registerEvent (): void {
|
||||
let hiddenPropName: string;
|
||||
if (typeof document.hidden !== 'undefined') {
|
||||
hiddenPropName = 'hidden';
|
||||
} else if (typeof document.mozHidden !== 'undefined') {
|
||||
hiddenPropName = 'mozHidden';
|
||||
} else if (typeof document.msHidden !== 'undefined') {
|
||||
hiddenPropName = 'msHidden';
|
||||
} else if (typeof document.webkitHidden !== 'undefined') {
|
||||
hiddenPropName = 'webkitHidden';
|
||||
} else {
|
||||
hiddenPropName = 'hidden';
|
||||
}
|
||||
|
||||
let hidden = false;
|
||||
const onHidden = (): void => {
|
||||
if (!hidden) {
|
||||
hidden = true;
|
||||
this.emit('hide');
|
||||
}
|
||||
};
|
||||
// In order to adapt the most of platforms the onshow API.
|
||||
const onShown = (arg0?, arg1?, arg2?, arg3?, arg4?): void => {
|
||||
if (hidden) {
|
||||
hidden = false;
|
||||
this.emit('show', arg0, arg1, arg2, arg3, arg4);
|
||||
}
|
||||
};
|
||||
|
||||
if (hiddenPropName) {
|
||||
const changeList = [
|
||||
'visibilitychange',
|
||||
'mozvisibilitychange',
|
||||
'msvisibilitychange',
|
||||
'webkitvisibilitychange',
|
||||
'qbrowserVisibilityChange',
|
||||
];
|
||||
|
||||
for (let i = 0; i < changeList.length; i++) {
|
||||
document.addEventListener(changeList[i], (event) => {
|
||||
let visible = document[hiddenPropName];
|
||||
// NOTE: QQ App need hidden property
|
||||
visible = visible || (event as any).hidden;
|
||||
if (visible) {
|
||||
onHidden();
|
||||
} else {
|
||||
onShown();
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
window.addEventListener('blur', onHidden);
|
||||
window.addEventListener('focus', onShown);
|
||||
}
|
||||
|
||||
if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) {
|
||||
window.onfocus = onShown;
|
||||
}
|
||||
|
||||
if ('onpageshow' in window && 'onpagehide' in window) {
|
||||
window.addEventListener('pagehide', onHidden);
|
||||
window.addEventListener('pageshow', onShown);
|
||||
// Taobao UIWebKit
|
||||
document.addEventListener('pagehide', onHidden);
|
||||
document.addEventListener('pageshow', onShown);
|
||||
}
|
||||
}
|
||||
|
||||
private _setFeature (feature: Feature, value: boolean): boolean {
|
||||
return this._featureMap[feature] = value;
|
||||
}
|
||||
|
||||
public init (): Promise<void[]> {
|
||||
return Promise.all(this._initPromise);
|
||||
}
|
||||
|
||||
public hasFeature (feature: Feature): boolean {
|
||||
return this._featureMap[feature];
|
||||
}
|
||||
|
||||
public getBatteryLevel (): number {
|
||||
if (this._battery) {
|
||||
return this._battery.level as number;
|
||||
} else {
|
||||
if (DEBUG) {
|
||||
warn('getBatteryLevel is not supported');
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
public triggerGC (): void {
|
||||
if (DEBUG) {
|
||||
warn('triggerGC is not supported.');
|
||||
}
|
||||
}
|
||||
public openURL (url: string): void {
|
||||
window.open(url);
|
||||
}
|
||||
public now (): number {
|
||||
if (Date.now) {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
return +(new Date());
|
||||
}
|
||||
public restartJSVM (): void {
|
||||
if (DEBUG) {
|
||||
warn('restartJSVM is not supported.');
|
||||
}
|
||||
}
|
||||
|
||||
public exit (): void {
|
||||
window.close();
|
||||
}
|
||||
|
||||
public close (): void {
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
export const systemInfo = new SystemInfo();
|
||||
|
||||
checkPalIntegrity<typeof import('pal/system-info')>(withImpl<typeof import('./system-info')>());
|
||||
-242
@@ -1,242 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR, NODEJS, USE_XR } from 'internal:constants';
|
||||
import { warnID } from '../cocos/core/platform/debug';
|
||||
|
||||
/**
|
||||
* This method clones methods in minigame environment, sub as `wx`, `swan` etc. to a module called minigame.
|
||||
* @param targetObject Usually it's specified as the minigame module.
|
||||
* @param originObj Original minigame environment such as `wx`, `swan` etc.
|
||||
*/
|
||||
export function cloneObject<T extends object = any> (targetObject: T, originObj: T): void {
|
||||
Object.keys(originObj).forEach((key) => {
|
||||
if (typeof originObj[key] === 'function') {
|
||||
targetObject[key] = originObj[key].bind(originObj);
|
||||
return;
|
||||
}
|
||||
targetObject[key] = originObj[key];
|
||||
});
|
||||
}
|
||||
|
||||
type MiningameAudioCallbackName = 'onPlay' | 'onPause' | 'onStop' | 'onSeek';
|
||||
type InnerAudioContextPolyfillConfig = {
|
||||
[CallbackName in MiningameAudioCallbackName]: boolean;
|
||||
};
|
||||
/**
|
||||
* This method is to create a polyfill on minigame platform when the innerAudioContext callback doesn't work.
|
||||
* @param minigameEnv Specify the minigame enviroment such as `wx`, `swan` etc.
|
||||
* @param polyfillConfig Specify the field, if it's true, the polyfill callback will be applied.
|
||||
* @param isAsynchronous Specify whether the callback is called asynchronous.
|
||||
* @returns A polyfilled createInnerAudioContext method.
|
||||
*/
|
||||
export function createInnerAudioContextPolyfill (minigameEnv: any, polyfillConfig: InnerAudioContextPolyfillConfig, isAsynchronous = false) {
|
||||
return (): InnerAudioContext => {
|
||||
const audioContext: InnerAudioContext = minigameEnv.createInnerAudioContext();
|
||||
|
||||
// add polyfill if onPlay method doesn't work this platform
|
||||
if (polyfillConfig.onPlay) {
|
||||
const originalPlay = audioContext.play;
|
||||
let _onPlayCB: (() => void) | null = null;
|
||||
Object.defineProperty(audioContext, 'onPlay', {
|
||||
configurable: true,
|
||||
value (cb: () => void) {
|
||||
_onPlayCB = cb;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(audioContext, 'play', {
|
||||
configurable: true,
|
||||
value () {
|
||||
originalPlay.call(audioContext);
|
||||
if (_onPlayCB) {
|
||||
if (isAsynchronous) {
|
||||
setTimeout(_onPlayCB, 0);
|
||||
} else {
|
||||
_onPlayCB();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// add polyfill if onPause method doesn't work this platform
|
||||
if (polyfillConfig.onPause) {
|
||||
const originalPause = audioContext.pause;
|
||||
let _onPauseCB: (() => void) | null = null;
|
||||
Object.defineProperty(audioContext, 'onPause', {
|
||||
configurable: true,
|
||||
value (cb: () => void) {
|
||||
_onPauseCB = cb;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(audioContext, 'pause', {
|
||||
configurable: true,
|
||||
value () {
|
||||
originalPause.call(audioContext);
|
||||
if (_onPauseCB) {
|
||||
if (isAsynchronous) {
|
||||
setTimeout(_onPauseCB, 0);
|
||||
} else {
|
||||
_onPauseCB();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// add polyfill if onStop method doesn't work on this platform
|
||||
if (polyfillConfig.onStop) {
|
||||
const originalStop = audioContext.stop;
|
||||
let _onStopCB: (() => void) | null = null;
|
||||
Object.defineProperty(audioContext, 'onStop', {
|
||||
configurable: true,
|
||||
value (cb: () => void) {
|
||||
_onStopCB = cb;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(audioContext, 'stop', {
|
||||
configurable: true,
|
||||
value () {
|
||||
originalStop.call(audioContext);
|
||||
if (_onStopCB) {
|
||||
if (isAsynchronous) {
|
||||
setTimeout(_onStopCB, 0);
|
||||
} else {
|
||||
_onStopCB();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// add polyfill if onSeeked method doesn't work on this platform
|
||||
if (polyfillConfig.onSeek) {
|
||||
const originalSeek = audioContext.seek;
|
||||
let _onSeekCB: (() => void) | null = null;
|
||||
Object.defineProperty(audioContext, 'onSeeked', {
|
||||
configurable: true,
|
||||
value (cb: () => void) {
|
||||
_onSeekCB = cb;
|
||||
},
|
||||
});
|
||||
Object.defineProperty(audioContext, 'seek', {
|
||||
configurable: true,
|
||||
value (time: number) {
|
||||
originalSeek.call(audioContext, time);
|
||||
if (_onSeekCB) {
|
||||
if (isAsynchronous) {
|
||||
setTimeout(_onSeekCB, 0);
|
||||
} else {
|
||||
_onSeekCB();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return audioContext;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two version, version should in pattern like 3.0.0.
|
||||
* If versionA > versionB, return number larger than 0.
|
||||
* If versionA = versionB, return number euqal to 0.
|
||||
* If versionA < versionB, return number smaller than 0.
|
||||
* @param versionA
|
||||
* @param versionB
|
||||
*/
|
||||
export function versionCompare (versionA: string, versionB: string): number {
|
||||
const versionRegExp = /\d+\.\d+\.\d+/;
|
||||
if (!(versionRegExp.test(versionA) && versionRegExp.test(versionB))) {
|
||||
warnID(16356);
|
||||
return 0;
|
||||
}
|
||||
const versionNumbersA = versionA.split('.').map((num: string) => Number.parseInt(num));
|
||||
const versionNumbersB = versionB.split('.').map((num: string) => Number.parseInt(num));
|
||||
for (let i = 0; i < 3; ++i) {
|
||||
const numberA = versionNumbersA[i];
|
||||
const numberB = versionNumbersB[i];
|
||||
if (numberA !== numberB) {
|
||||
return numberA - numberB;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* A custom implementation of setTimeout that uses requestAnimationFrame.
|
||||
* @param callback The function to be executed after a delay.
|
||||
* @param delay The delay time in milliseconds.
|
||||
* @param args The arguments to be passed to the callback function.
|
||||
* @returns A unique identifier for the timer.
|
||||
*/
|
||||
export function setTimeoutRAF<T extends any[]> (callback: (...args: T) => void, delay: number, ...args: T): number {
|
||||
const start = performance.now();
|
||||
|
||||
const raf = requestAnimationFrame
|
||||
|| window.requestAnimationFrame
|
||||
|| window.webkitRequestAnimationFrame
|
||||
|| window.mozRequestAnimationFrame
|
||||
|| window.oRequestAnimationFrame
|
||||
|| window.msRequestAnimationFrame;
|
||||
|
||||
if (EDITOR || NODEJS || raf === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) {
|
||||
return setTimeout(callback, delay, ...args);
|
||||
}
|
||||
|
||||
const handleRAF = (): void => {
|
||||
if (performance.now() - start < delay) {
|
||||
raf(handleRAF);
|
||||
} else {
|
||||
callback(...args);
|
||||
}
|
||||
};
|
||||
|
||||
return raf(handleRAF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a timer that was created using the rafTimeout function.
|
||||
* @param id A numeric ID that represents the timer to be canceled.
|
||||
* @returns Nothing.
|
||||
*/
|
||||
export function clearTimeoutRAF (id: number): void {
|
||||
const caf = cancelAnimationFrame
|
||||
|| window.cancelAnimationFrame
|
||||
|| window.cancelRequestAnimationFrame
|
||||
|| window.msCancelRequestAnimationFrame
|
||||
|| window.mozCancelRequestAnimationFrame
|
||||
|| window.oCancelRequestAnimationFrame
|
||||
|| window.webkitCancelRequestAnimationFrame
|
||||
|| window.msCancelAnimationFrame
|
||||
|| window.mozCancelAnimationFrame
|
||||
|| window.webkitCancelAnimationFrame
|
||||
|| window.ocancelAnimationFrame;
|
||||
if (EDITOR || caf === undefined || (USE_XR && globalThis.__globalXR?.isWebXR)) {
|
||||
clearTimeout(id);
|
||||
} else {
|
||||
caf(id);
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { HUAWEI, TAOBAO_MINIGAME, WASM_SUBPACKAGE, XIAOMI } from 'internal:constants';
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { basename } from '../../cocos/core/utils/path';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
import { log } from '../../cocos/core/platform/debug';
|
||||
|
||||
// NOTE: The global variable `CCWebAssembly` is assigned in platforms/(bytedance|wechat)/wrapper/builtin/index.js
|
||||
declare namespace CCWebAssembly {
|
||||
// The first argument of `instantiate` function in mini-game platforms is always a wasm url.
|
||||
function instantiate(url: string, importObject?: WebAssembly.Imports): Promise<WebAssembly.WebAssemblyInstantiatedSource>;
|
||||
}
|
||||
|
||||
export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise<any> {
|
||||
return getPlatformBinaryUrl(wasmUrl).then((url: string) => CCWebAssembly.instantiate(url, importObject));
|
||||
}
|
||||
|
||||
export function fetchBuffer (binaryUrl: string): Promise<ArrayBuffer> {
|
||||
return new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
getPlatformBinaryUrl(binaryUrl).then((url) => {
|
||||
// NOTE: fsUtils is defined in engine-adapter, we need to access globalThis explicitly for Taobao platform
|
||||
globalThis.fsUtils.readArrayBuffer(url, (err, arrayBuffer: ArrayBuffer) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(arrayBuffer);
|
||||
});
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
}).catch((e) => {});
|
||||
});
|
||||
}
|
||||
|
||||
export function fetchUrl (binaryUrl: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
getPlatformBinaryUrl(binaryUrl).then((url) => {
|
||||
resolve(url);
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
}).catch((e) => {
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function loadSubpackage (name: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (minigame.loadSubpackage) {
|
||||
minigame.loadSubpackage({
|
||||
name,
|
||||
success () {
|
||||
resolve();
|
||||
},
|
||||
fail (err) {
|
||||
log(`Load subpacakge '${name}' failed, maybe we don't need this subpacakge or it's an engine build issue, for detailed: `, err);
|
||||
resolve();
|
||||
},
|
||||
});
|
||||
} else {
|
||||
reject(new Error(`Subpackage is not supported on this platform`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let promiseToLoadWasmModule: Promise<void> | undefined;
|
||||
|
||||
export function ensureWasmModuleReady (): Promise<void> {
|
||||
if (promiseToLoadWasmModule) {
|
||||
return promiseToLoadWasmModule;
|
||||
}
|
||||
return promiseToLoadWasmModule = new Promise<void>((resolve, reject) => {
|
||||
if (WASM_SUBPACKAGE) {
|
||||
if (HUAWEI) {
|
||||
// NOTE: huawei quick game doesn't support concurrent loading subpackage.
|
||||
loadSubpackage('__ccWasmAssetSubpkg__').then(() => loadSubpackage('__ccWasmChunkSubpkg__')).then(() => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
} else {
|
||||
Promise.all(['__ccWasmAssetSubpkg__', '__ccWasmChunkSubpkg__'].map((pkgName) => loadSubpackage(pkgName)))
|
||||
.then(() => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
}
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The binary url can be different on different platforms.
|
||||
* @param binaryUrl the basic build output binary url
|
||||
* @returns the real binary url on the exact platform
|
||||
*/
|
||||
function getPlatformBinaryUrl (binaryUrl: string): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
if (XIAOMI) {
|
||||
resolve(`src/cocos-js/${binaryUrl}`);
|
||||
} if (TAOBAO_MINIGAME && WASM_SUBPACKAGE) {
|
||||
resolve(`__ccWasmAssetSubpkg__/${basename(binaryUrl)}`);
|
||||
} else {
|
||||
resolve(`cocos-js/${binaryUrl}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/wasm')>(withImpl<typeof import('./wasm-minigame')>());
|
||||
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
import { EDITOR } from 'internal:constants';
|
||||
import { native } from '../../cocos/native-binding/index';
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise<any> {
|
||||
return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject));
|
||||
}
|
||||
|
||||
export function fetchBuffer (binaryUrl: string): Promise<ArrayBuffer> {
|
||||
return new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
try {
|
||||
// NOTE: when it's in EDITOR, binaryUrl is a url with `external:` protocol.
|
||||
if (EDITOR) {
|
||||
Editor.Message.request('engine', 'query-engine-info').then((info) => {
|
||||
const externalRoot = `${info.native.path}/external/`;
|
||||
binaryUrl = binaryUrl.replace('external:', externalRoot);
|
||||
const arrayBuffer = native.fileUtils.getDataFromFile(binaryUrl);
|
||||
resolve(arrayBuffer);
|
||||
});
|
||||
return;
|
||||
}
|
||||
binaryUrl = `src/cocos-js/${binaryUrl}`;
|
||||
const arrayBuffer = native.fileUtils.getDataFromFile(binaryUrl);
|
||||
resolve(arrayBuffer);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function fetchUrl (binaryUrl: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
try {
|
||||
// NOTE: when it's in EDITOR, binaryUrl is a url with `external:` protocol.
|
||||
if (EDITOR) {
|
||||
Editor.Message.request('engine', 'query-engine-info').then((info) => {
|
||||
const externalRoot = `${info.native.path}/external/`;
|
||||
binaryUrl = binaryUrl.replace('external:', externalRoot);
|
||||
resolve(binaryUrl);
|
||||
});
|
||||
return;
|
||||
}
|
||||
binaryUrl = `src/cocos-js/${binaryUrl}`;
|
||||
resolve(binaryUrl);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function ensureWasmModuleReady (): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/wasm')>(withImpl<typeof import('./wasm-native')>());
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2023 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
import { checkPalIntegrity, withImpl } from '../integrity-check';
|
||||
|
||||
export function instantiateWasm (wasmUrl: string, importObject: WebAssembly.Imports): Promise<any> {
|
||||
return fetchBuffer(wasmUrl).then((arrayBuffer) => WebAssembly.instantiate(arrayBuffer, importObject));
|
||||
}
|
||||
|
||||
export function fetchBuffer (binaryUrl: string): Promise<ArrayBuffer> {
|
||||
return new Promise<ArrayBuffer>((resolve, reject) => {
|
||||
try {
|
||||
const externalRoot = `${globalThis.nodeEnv.enginePath}/native/external/`;
|
||||
binaryUrl = binaryUrl.replace('external:', externalRoot);
|
||||
const fs = globalThis.nodeEnv.require('fs-extra');
|
||||
const arrayBuffer = fs.readFileSync(binaryUrl) as ArrayBuffer;
|
||||
resolve(arrayBuffer);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function fetchUrl(binaryUrl: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
try {
|
||||
const externalRoot = `${globalThis.nodeEnv.enginePath}/native/external/`;
|
||||
binaryUrl = binaryUrl.replace('external:', externalRoot);
|
||||
resolve(binaryUrl);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function ensureWasmModuleReady (): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
checkPalIntegrity<typeof import('pal/wasm')>(withImpl<typeof import('./wasm-nodejs')>());
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user