refactor: src 除入口外全部移入 monorepo

This commit is contained in:
AncTe committed 2025-03-09 16:43:59 +08:00
1 parent cca10a429c
commit 0679bbb1a5
103 files changed
+340 -252

No files matched your search

@@ -0,0 +1,165 @@
import { KeyCode } from '@motajs/client-base';
import { Hotkey, HotkeyData } from '@motajs/system-action';
import type { HeroMover, IMoveController } from '@user/data-state';
import { Ticker } from 'mutate-animate';
import { mainScope } from '@motajs/legacy-ui';
type MoveKey = Record<Dir, HotkeyData>;
type MoveKeyConfig = Record<Dir, string>;
export class HeroKeyMover {
/** 当前按下的键 */
private pressedKey: Set<Dir> = new Set();
/** 当前的移动方向 */
private moveDir: Dir = 'down';
/** 当前是否正在使用按键移动 */
private moving: boolean = false;
/** 当前移动的控制器 */
private controller?: IMoveController;
/** 按键接续ticker */
private ticker = new Ticker();
/** 当前移动实例绑定的热键 */
hotkey: Hotkey;
/** 当前热键的移动按键信息 */
hotkeyData: MoveKey;
/** 移动实例 */
mover: HeroMover;
/** 移动可触发的作用域 */
scope: symbol = mainScope;
constructor(hotkey: Hotkey, mover: HeroMover, config?: MoveKeyConfig) {
this.hotkey = hotkey;
this.mover = mover;
hotkey.on('press', this.onPressKey);
hotkey.on('release', this.onReleaseKey);
const data = hotkey.data;
this.hotkeyData = {
left: data[config?.left ?? 'moveLeft'],
right: data[config?.right ?? 'moveRight'],
up: data[config?.up ?? 'moveUp'],
down: data[config?.down ?? 'moveDown']
};
this.ticker.add(() => {
if (!this.moving) {
if (this.pressedKey.size > 0) {
const dir = [...this.pressedKey].at(-1);
if (!dir) return;
this.moveDir = dir;
this.tryStartMove();
}
}
});
}
private onPressKey = (code: KeyCode) => {
if (core.isReplaying() || !core.isPlaying()) return;
core.waitHeroToStop();
if (code === this.hotkeyData.left.key) this.press('left');
else if (code === this.hotkeyData.right.key) this.press('right');
else if (code === this.hotkeyData.up.key) this.press('up');
else if (code === this.hotkeyData.down.key) this.press('down');
};
private onReleaseKey = (code: KeyCode) => {
if (code === this.hotkeyData.left.key) this.release('left');
else if (code === this.hotkeyData.right.key) this.release('right');
else if (code === this.hotkeyData.up.key) this.release('up');
else if (code === this.hotkeyData.down.key) this.release('down');
};
/**
* 设置按键触发作用域
*/
setScope(scope: symbol) {
this.scope = scope;
}
/**
* 按下某个方向键
* @param dir 移动方向
*/
press(dir: Dir) {
if (this.hotkey.scope !== this.scope || core.status.lockControl) return;
this.pressedKey.add(dir);
this.moveDir = dir;
if (!this.moving) {
this.tryStartMove();
}
}
/**
* 松开方向键
* @param dir 移动方向
*/
release(dir: Dir) {
this.pressedKey.delete(dir);
if (this.pressedKey.size > 0) {
this.moveDir = [...this.pressedKey][0];
} else {
this.endMove();
}
}
/**
* 尝试开始移动
* @returns 是否成功开始移动
*/
tryStartMove() {
if (this.moving || core.status.lockControl) return false;
this.mover.oneStep(this.moveDir);
const controller = this.mover.startMove(false, false, false, true);
if (!controller) return;
this.controller = controller;
controller.onEnd.then(() => {
this.moving = false;
this.controller = void 0;
this.mover.off('stepEnd', this.onStepEnd);
});
this.moving = true;
this.mover.on('stepEnd', this.onStepEnd);
return true;
}
/**
* 停止本次按键移动
*/
endMove() {
this.controller?.stop();
}
private onStepEnd = () => {
const con = this.controller;
if (!con) return;
if (core.status.lockControl) {
con.stop();
return;
}
if (!this.moving) {
con.stop();
return;
}
if (this.pressedKey.size > 0) {
if (con.queue.length === 0) {
con.push({ type: 'dir', value: this.moveDir });
}
} else {
con.stop();
}
};
destroy() {
this.hotkey.off('press', this.onPressKey);
this.hotkey.off('release', this.onReleaseKey);
this.mover.off('stepEnd', this.onStepEnd);
this.ticker.destroy();
}
}
@@ -0,0 +1,268 @@
import EventEmitter from 'eventemitter3';
import { audioPlayer, AudioPlayer, AudioRoute, AudioStatus } from './player';
import { guessTypeByExt, isAudioSupport } from './support';
import { logger } from '@motajs/common';
import { StreamLoader } from '../loader';
import { linear, sleep, Transition } from 'mutate-animate';
import { VolumeEffect } from './effect';
interface BgmVolume {
effect: VolumeEffect;
transition: Transition;
}
interface BgmControllerEvent {
play: [];
pause: [];
resume: [];
stop: [];
}
export class BgmController<
T extends string = BgmIds
> extends EventEmitter<BgmControllerEvent> {
/** bgm音频名称的前缀 */
prefix: string = 'bgms.';
/** 每个 bgm 的音量控制器 */
readonly gain: Map<T, BgmVolume> = new Map();
/** 正在播放的 bgm */
playingBgm?: T;
/** 是否正在播放 */
playing: boolean = false;
/** 是否已经启用 */
enabled: boolean = true;
/** 主音量控制器 */
private readonly mainGain: VolumeEffect;
/** 是否屏蔽所有的音乐切换 */
private blocking: boolean = false;
/** 渐变时长 */
private transitionTime: number = 2000;
constructor(public readonly player: AudioPlayer) {
super();
this.mainGain = player.createVolumeEffect();
}
/**
* 设置音频渐变时长
* @param time 渐变时长
*/
setTransitionTime(time: number) {
this.transitionTime = time;
for (const [, value] of this.gain) {
value.transition.time(time);
}
}
/**
* 屏蔽音乐切换
*/
blockChange() {
this.blocking = true;
}
/**
* 取消屏蔽音乐切换
*/
unblockChange() {
this.blocking = false;
}
/**
* 设置总音量大小
* @param volume 音量大小
*/
setVolume(volume: number) {
this.mainGain.setVolume(volume);
}
/**
* 获取总音量大小
*/
getVolume() {
return this.mainGain.getVolume();
}
/**
* 设置是否启用
* @param enabled 是否启用
*/
setEnabled(enabled: boolean) {
if (enabled) this.resume();
else this.stop();
this.enabled = enabled;
}
/**
* 设置 bgm 音频名称的前缀
*/
setPrefix(prefix: string) {
this.prefix = prefix;
}
private getId(name: T) {
return `${this.prefix}${name}`;
}
/**
* 根据 bgm 名称获取其 AudioRoute 实例
* @param id 音频名称
*/
get(id: T) {
return this.player.getRoute(this.getId(id));
}
/**
* 添加一个 bgm
* @param id 要添加的 bgm 的名称
* @param url 指定 bgm 的加载地址
*/
addBgm(id: T, url: string = `project/bgms/${id}`) {
const type = guessTypeByExt(id);
if (!type) {
logger.warn(50, id.split('.').slice(0, -1).join('.'));
return;
}
const gain = this.player.createVolumeEffect();
if (isAudioSupport(type)) {
const source = audioPlayer.createElementSource();
source.setSource(url);
source.setLoop(true);
const route = new AudioRoute(source, audioPlayer);
route.addEffect([gain, this.mainGain]);
audioPlayer.addRoute(this.getId(id), route);
this.setTransition(id, route, gain);
} else {
const source = audioPlayer.createStreamSource();
const stream = new StreamLoader(url);
stream.pipe(source);
source.setLoop(true);
const route = new AudioRoute(source, audioPlayer);
route.addEffect([gain, this.mainGain]);
audioPlayer.addRoute(this.getId(id), route);
this.setTransition(id, route, gain);
}
}
/**
* 移除一个 bgm
* @param id 要移除的 bgm 的名称
*/
removeBgm(id: T) {
this.player.removeRoute(this.getId(id));
const gain = this.gain.get(id);
gain?.transition.ticker.destroy();
this.gain.delete(id);
}
private setTransition(id: T, route: AudioRoute, gain: VolumeEffect) {
const transition = new Transition();
transition
.time(this.transitionTime)
.mode(linear())
.transition('volume', 0);
const tick = () => {
gain.setVolume(transition.value.volume);
};
/**
* @param expect 在结束时应该是正在播放还是停止
*/
const setTick = async (expect: AudioStatus) => {
transition.ticker.remove(tick);
transition.ticker.add(tick);
const identifier = route.stopIdentifier;
await sleep(this.transitionTime + 500);
if (
route.status === expect &&
identifier === route.stopIdentifier
) {
transition.ticker.remove(tick);
if (route.status === AudioStatus.Playing) {
gain.setVolume(1);
} else {
gain.setVolume(0);
}
}
};
route.onStart(async () => {
transition.transition('volume', 1);
setTick(AudioStatus.Playing);
});
route.onEnd(() => {
transition.transition('volume', 0);
setTick(AudioStatus.Paused);
});
route.setEndTime(this.transitionTime);
this.gain.set(id, { effect: gain, transition });
}
/**
* 播放一个 bgm
* @param id 要播放的 bgm 名称
*/
play(id: T, when?: number) {
if (this.blocking) return;
if (id !== this.playingBgm && this.playingBgm) {
this.player.pause(this.getId(this.playingBgm));
}
this.playingBgm = id;
if (!this.enabled) return;
this.player.play(this.getId(id), when);
this.playing = true;
this.emit('play');
}
/**
* 继续当前的 bgm
*/
resume() {
if (this.blocking || !this.enabled || this.playing) return;
if (this.playingBgm) {
this.player.resume(this.getId(this.playingBgm));
}
this.playing = true;
this.emit('resume');
}
/**
* 暂停当前的 bgm
*/
pause() {
if (this.blocking || !this.enabled) return;
if (this.playingBgm) {
this.player.pause(this.getId(this.playingBgm));
}
this.playing = false;
this.emit('pause');
}
/**
* 停止当前的 bgm
*/
stop() {
if (this.blocking || !this.enabled) return;
if (this.playingBgm) {
this.player.stop(this.getId(this.playingBgm));
}
this.playing = false;
this.emit('stop');
}
}
export const bgmController = new BgmController<BgmIds>(audioPlayer);
export function loadAllBgm() {
const loading = Mota.require('var', 'loading');
loading.once('coreInit', () => {
const data = data_a1e2fb4a_e986_4524_b0da_9b7ba7c0874d;
for (const bgm of data.main.bgms) {
bgmController.addBgm(bgm);
}
});
}
@@ -0,0 +1,201 @@
import { logger } from '@motajs/common';
import { OggVorbisDecoderWebWorker } from '@wasm-audio-decoders/ogg-vorbis';
import { OggOpusDecoderWebWorker } from 'ogg-opus-decoder';
import { AudioType, isAudioSupport } from './support';
import type { AudioPlayer } from './player';
const fileSignatures: [AudioType, number[]][] = [
[AudioType.Mp3, [0x49, 0x44, 0x33]],
[AudioType.Ogg, [0x4f, 0x67, 0x67, 0x53]],
[AudioType.Wav, [0x52, 0x49, 0x46, 0x46]],
[AudioType.Flac, [0x66, 0x4c, 0x61, 0x43]],
[AudioType.Aac, [0xff, 0xf1]],
[AudioType.Aac, [0xff, 0xf9]]
];
const oggHeaders: [AudioType, number[]][] = [
[AudioType.Opus, [0x4f, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64]]
];
export function checkAudioType(data: Uint8Array) {
let audioType: AudioType | '' = '';
// 检查头文件获取音频类型,仅检查前256个字节
const toCheck = data.slice(0, 256);
for (const [type, value] of fileSignatures) {
if (value.every((v, i) => toCheck[i] === v)) {
audioType = type;
break;
}
}
if (audioType === AudioType.Ogg) {
// 如果是ogg的话,进一步判断是不是opus
for (const [key, value] of oggHeaders) {
const has = toCheck.some((_, i) => {
return value.every((v, ii) => toCheck[i + ii] === v);
});
if (has) {
audioType = key;
break;
}
}
}
return audioType;
}
export interface IAudioDecodeError {
/** 错误信息 */
message: string;
}
export interface IAudioDecodeData {
/** 每个声道的音频信息 */
channelData: Float32Array[];
/** 已经被解码的 PCM 采样数 */
samplesDecoded: number;
/** 音频采样率 */
sampleRate: number;
/** 解码错误信息 */
errors: IAudioDecodeError[];
}
export abstract class AudioDecoder {
static readonly decoderMap: Map<AudioType, new () => AudioDecoder> =
new Map();
/**
* 注册一个解码器
* @param type 要注册的解码器允许解码的类型
* @param decoder 解码器对象
*/
static registerDecoder(type: AudioType, decoder: new () => AudioDecoder) {
if (this.decoderMap.has(type)) {
logger.warn(47, type);
return;
}
this.decoderMap.set(type, decoder);
}
/**
* 解码音频数据
* @param data 音频文件数据
* @param player AudioPlayer实例
*/
static async decodeAudioData(data: Uint8Array, player: AudioPlayer) {
// 检查头文件获取音频类型,仅检查前256个字节
const toCheck = data.slice(0, 256);
const type = checkAudioType(data);
if (type === '') {
logger.error(
25,
[...toCheck]
.map(v => v.toString(16).padStart(2, '0'))
.join(' ')
.toUpperCase()
);
return null;
}
if (isAudioSupport(type)) {
if (data.buffer instanceof ArrayBuffer) {
return player.ac.decodeAudioData(data.buffer);
} else {
return null;
}
} else {
const Decoder = this.decoderMap.get(type);
if (!Decoder) {
return null;
} else {
const decoder = new Decoder();
await decoder.create();
const decodedData = await decoder.decode(data);
if (!decodedData) return null;
const buffer = player.ac.createBuffer(
decodedData.channelData.length,
decodedData.channelData[0].length,
decodedData.sampleRate
);
decodedData.channelData.forEach((v, i) => {
buffer.copyToChannel(v, i);
});
decoder.destroy();
return buffer;
}
}
}
/**
* 创建音频解码器
*/
abstract create(): Promise<void>;
/**
* 摧毁这个解码器
*/
abstract destroy(): void;
/**
* 解码流数据
* @param data 流数据
*/
abstract decode(data: Uint8Array): Promise<IAudioDecodeData | undefined>;
/**
* 解码整个文件
* @param data 文件数据
*/
abstract decodeAll(data: Uint8Array): Promise<IAudioDecodeData | undefined>;
/**
* 当音频解码完成后,会调用此函数,需要返回之前还未解析或未返回的音频数据。调用后,该解码器将不会被再次使用
*/
abstract flush(): Promise<IAudioDecodeData | undefined>;
}
export class VorbisDecoder implements AudioDecoder {
decoder?: OggVorbisDecoderWebWorker;
async create(): Promise<void> {
this.decoder = new OggVorbisDecoderWebWorker();
await this.decoder.ready;
}
destroy(): void {
this.decoder?.free();
}
async decode(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
return this.decoder?.decode(data);
}
async decodeAll(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
return this.decoder?.decodeFile(data);
}
async flush(): Promise<IAudioDecodeData | undefined> {
return this.decoder?.flush();
}
}
export class OpusDecoder implements AudioDecoder {
decoder?: OggOpusDecoderWebWorker;
async create(): Promise<void> {
this.decoder = new OggOpusDecoderWebWorker();
await this.decoder.ready;
}
destroy(): void {
this.decoder?.free();
}
async decode(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
return this.decoder?.decode(data);
}
async decodeAll(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
return this.decoder?.decodeFile(data);
}
async flush(): Promise<IAudioDecodeData | undefined> {
return await this.decoder?.flush();
}
}
@@ -0,0 +1,288 @@
import { isNil } from 'lodash-es';
import { sleep } from 'mutate-animate';
export interface IAudioInput {
/** 输入节点 */
input: AudioNode;
}
export interface IAudioOutput {
/** 输出节点 */
output: AudioNode;
}
export abstract class AudioEffect implements IAudioInput, IAudioOutput {
/** 输出节点 */
abstract output: AudioNode;
/** 输入节点 */
abstract input: AudioNode;
constructor(public readonly ac: AudioContext) {}
/**
* 当音频播放结束时触发,可以用于节点结束后处理
*/
abstract end(): void;
/**
* 当音频开始播放时触发,可以用于节点初始化
*/
abstract start(): void;
/**
* 连接至其他效果器
* @param target 目标输入
* @param output 当前效果器输出通道
* @param input 目标效果器的输入通道
*/
connect(target: IAudioInput, output?: number, input?: number) {
this.output.connect(target.input, output, input);
}
/**
* 与其他效果器取消连接
* @param target 目标输入
* @param output 当前效果器输出通道
* @param input 目标效果器的输入通道
*/
disconnect(target?: IAudioInput, output?: number, input?: number) {
if (!target) {
if (!isNil(output)) {
this.output.disconnect(output);
} else {
this.output.disconnect();
}
} else {
if (!isNil(output)) {
if (!isNil(input)) {
this.output.disconnect(target.input, output, input);
} else {
this.output.disconnect(target.input, output);
}
} else {
this.output.disconnect(target.input);
}
}
}
}
export class StereoEffect extends AudioEffect {
output: PannerNode;
input: PannerNode;
constructor(ac: AudioContext) {
super(ac);
const panner = ac.createPanner();
this.input = panner;
this.output = panner;
}
/**
* 设置音频朝向,x正方形水平向右,y正方形垂直于地面向上,z正方向垂直屏幕远离用户
* @param x 朝向x坐标
* @param y 朝向y坐标
* @param z 朝向z坐标
*/
setOrientation(x: number, y: number, z: number) {
this.output.orientationX.value = x;
this.output.orientationY.value = y;
this.output.orientationZ.value = z;
}
/**
* 设置音频位置,x正方形水平向右,y正方形垂直于地面向上,z正方向垂直屏幕远离用户
* @param x 位置x坐标
* @param y 位置y坐标
* @param z 位置z坐标
*/
setPosition(x: number, y: number, z: number) {
this.output.positionX.value = x;
this.output.positionY.value = y;
this.output.positionZ.value = z;
}
end(): void {}
start(): void {}
}
export class VolumeEffect extends AudioEffect {
output: GainNode;
input: GainNode;
constructor(ac: AudioContext) {
super(ac);
const gain = ac.createGain();
this.input = gain;
this.output = gain;
}
/**
* 设置音量大小
* @param volume 音量大小
*/
setVolume(volume: number) {
this.output.gain.value = volume;
}
/**
* 获取音量大小
*/
getVolume(): number {
return this.output.gain.value;
}
end(): void {}
start(): void {}
}
export class ChannelVolumeEffect extends AudioEffect {
output: ChannelMergerNode;
input: ChannelSplitterNode;
/** 所有的音量控制节点 */
private readonly gain: GainNode[] = [];
constructor(ac: AudioContext) {
super(ac);
const splitter = ac.createChannelSplitter();
const merger = ac.createChannelMerger();
this.output = merger;
this.input = splitter;
for (let i = 0; i < 6; i++) {
const gain = ac.createGain();
splitter.connect(gain, i);
gain.connect(merger, 0, i);
this.gain.push(gain);
}
}
/**
* 设置某个声道的音量大小
* @param channel 要设置的声道,可填0-5
* @param volume 这个声道的音量大小
*/
setVolume(channel: number, volume: number) {
if (!this.gain[channel]) return;
this.gain[channel].gain.value = volume;
}
/**
* 获取某个声道的音量大小,可填0-5
* @param channel 要获取的声道
*/
getVolume(channel: number): number {
if (!this.gain[channel]) return 0;
return this.gain[channel].gain.value;
}
end(): void {}
start(): void {}
}
export class DelayEffect extends AudioEffect {
output: DelayNode;
input: DelayNode;
constructor(ac: AudioContext) {
super(ac);
const delay = ac.createDelay();
this.input = delay;
this.output = delay;
}
/**
* 设置延迟时长
* @param delay 延迟时长,单位秒
*/
setDelay(delay: number) {
this.output.delayTime.value = delay;
}
/**
* 获取延迟时长
*/
getDelay() {
return this.output.delayTime.value;
}
end(): void {}
start(): void {}
}
export class EchoEffect extends AudioEffect {
output: GainNode;
input: GainNode;
/** 延迟节点 */
private readonly delay: DelayNode;
/** 反馈增益节点 */
private readonly gainNode: GainNode;
/** 当前增益 */
private gain: number = 0.5;
/** 是否正在播放 */
private playing: boolean = false;
constructor(ac: AudioContext) {
super(ac);
const delay = ac.createDelay();
const gain = ac.createGain();
gain.gain.value = 0.5;
delay.delayTime.value = 0.05;
delay.connect(gain);
gain.connect(delay);
this.delay = delay;
this.gainNode = gain;
this.input = gain;
this.output = gain;
}
/**
* 设置回声反馈增益大小
* @param gain 增益大小,范围 0-1,大于等于1的视为0.5,小于0的视为0
*/
setFeedbackGain(gain: number) {
const resolved = gain >= 1 ? 0.5 : gain < 0 ? 0 : gain;
this.gain = resolved;
if (this.playing) this.gainNode.gain.value = resolved;
}
/**
* 设置回声间隔时长
* @param delay 回声时长,范围 0.01-Infinity,小于0.01的视为0.01
*/
setEchoDelay(delay: number) {
const resolved = delay < 0.01 ? 0.01 : delay;
this.delay.delayTime.value = resolved;
}
/**
* 获取反馈节点增益
*/
getFeedbackGain() {
return this.gain;
}
/**
* 获取回声间隔时长
*/
getEchoDelay() {
return this.delay.delayTime.value;
}
end(): void {
this.playing = false;
const echoTime = Math.ceil(Math.log(0.001) / Math.log(this.gain)) + 10;
sleep(this.delay.delayTime.value * echoTime).then(() => {
if (!this.playing) this.gainNode.gain.value = 0;
});
}
start(): void {
this.playing = true;
this.gainNode.gain.value = this.gain;
}
}
@@ -0,0 +1,16 @@
import { loadAllBgm } from './bgm';
import { OpusDecoder, VorbisDecoder } from './decoder';
import { AudioType } from './support';
import { AudioDecoder } from './decoder';
loadAllBgm();
AudioDecoder.registerDecoder(AudioType.Ogg, VorbisDecoder);
AudioDecoder.registerDecoder(AudioType.Opus, OpusDecoder);
export * from './support';
export * from './effect';
export * from './player';
export * from './source';
export * from './bgm';
export * from './decoder';
export * from './sound';
@@ -0,0 +1,595 @@
import EventEmitter from 'eventemitter3';
import {
AudioBufferSource,
AudioElementSource,
AudioSource,
AudioStreamSource
} from './source';
import {
AudioEffect,
ChannelVolumeEffect,
DelayEffect,
EchoEffect,
IAudioOutput,
StereoEffect,
VolumeEffect
} from './effect';
import { isNil } from 'lodash-es';
import { logger } from '@motajs/common';
import { sleep } from 'mutate-animate';
import { AudioDecoder } from './decoder';
interface AudioPlayerEvent {}
export class AudioPlayer extends EventEmitter<AudioPlayerEvent> {
/** 音频播放上下文 */
readonly ac: AudioContext;
/** 所有的音频播放路由 */
readonly audioRoutes: Map<string, AudioRoute> = new Map();
/** 音量节点 */
readonly gain: GainNode;
constructor() {
super();
this.ac = new AudioContext();
this.gain = this.ac.createGain();
this.gain.connect(this.ac.destination);
}
/**
* 解码音频数据
* @param data 音频数据
*/
decodeAudioData(data: Uint8Array) {
return AudioDecoder.decodeAudioData(data, this);
}
/**
* 设置音量
* @param volume 音量
*/
setVolume(volume: number) {
this.gain.gain.value = volume;
}
/**
* 获取音量
*/
getVolume() {
return this.gain.gain.value;
}
/**
* 创建一个音频源
* @param Source 音频源类
*/
createSource<T extends AudioSource>(
Source: new (ac: AudioContext) => T
): T {
return new Source(this.ac);
}
/**
* 创建一个兼容流式音频源,可以与流式加载相结合,主要用于处理 opus ogg 不兼容的情况
*/
createStreamSource() {
return new AudioStreamSource(this.ac);
}
/**
* 创建一个通过 audio 元素播放的音频源
*/
createElementSource() {
return new AudioElementSource(this.ac);
}
/**
* 创建一个通过 AudioBuffer 播放的音频源
*/
createBufferSource() {
return new AudioBufferSource(this.ac);
}
/**
* 获取音频目的地
*/
getDestination() {
return this.gain;
}
/**
* 创建一个音频效果器
* @param Effect 效果器类
*/
createEffect<T extends AudioEffect>(
Effect: new (ac: AudioContext) => T
): T {
return new Effect(this.ac);
}
/**
* 创建一个修改音量的效果器
* ```txt
* |----------|
* Input ----> | GainNode | ----> Output
* |----------|
* ```
*/
createVolumeEffect() {
return new VolumeEffect(this.ac);
}
/**
* 创建一个立体声效果器
* ```txt
* |------------|
* Input ----> | PannerNode | ----> Output
* |------------|
* ```
*/
createStereoEffect() {
return new StereoEffect(this.ac);
}
/**
* 创建一个修改单个声道音量的效果器
* ```txt
* |----------|
* -> | GainNode | \
* |--------------| / |----------| -> |------------|
* Input ----> | SplitterNode | ...... | MergerNode | ----> Output
* |--------------| \ |----------| -> |------------|
* -> | GainNode | /
* |----------|
* ```
*/
createChannelVolumeEffect() {
return new ChannelVolumeEffect(this.ac);
}
/**
* 创建一个延迟效果器
* |-----------|
* Input ----> | DelayNode | ----> Output
* |-----------|
*/
createDelay() {
return new DelayEffect(this.ac);
}
/**
* 创建一个回声效果器
* ```txt
* |----------|
* Input ----> | GainNode | ----> Output
* ^ |----------| |
* | |
* | |------------| ↓
* |-- | Delay Node | <--
* |------------|
* ```
*/
createEchoEffect() {
return new EchoEffect(this.ac);
}
/**
* 创建一个音频播放路由
* @param source 音频源
*/
createRoute(source: AudioSource) {
return new AudioRoute(source, this);
}
/**
* 添加一个音频播放路由,可以直接被播放
* @param id 这个音频播放路由的名称
* @param route 音频播放路由对象
*/
addRoute(id: string, route: AudioRoute) {
if (this.audioRoutes.has(id)) {
logger.warn(45, id);
}
this.audioRoutes.set(id, route);
}
/**
* 根据名称获取音频播放路由对象
* @param id 音频播放路由的名称
*/
getRoute(id: string) {
return this.audioRoutes.get(id);
}
/**
* 移除一个音频播放路由
* @param id 要移除的播放路由的名称
*/
removeRoute(id: string) {
this.audioRoutes.delete(id);
}
/**
* 播放音频
* @param id 音频名称
* @param when 从音频的哪个位置开始播放,单位秒
*/
play(id: string, when: number = 0) {
const route = this.getRoute(id);
if (!route) {
logger.warn(53, 'play', id);
return;
}
route.play(when);
}
/**
* 暂停音频播放
* @param id 音频名称
* @returns 当音乐真正停止时兑现
*/
pause(id: string) {
const route = this.getRoute(id);
if (!route) {
logger.warn(53, 'pause', id);
return;
}
return route.pause();
}
/**
* 停止音频播放
* @param id 音频名称
* @returns 当音乐真正停止时兑现
*/
stop(id: string) {
const route = this.getRoute(id);
if (!route) {
logger.warn(53, 'stop', id);
return;
}
return route.stop();
}
/**
* 继续音频播放
* @param id 音频名称
*/
resume(id: string) {
const route = this.getRoute(id);
if (!route) {
logger.warn(53, 'play', id);
return;
}
route.resume();
}
/**
* 设置听者位置,x正方向水平向右,y正方向垂直于地面向上,z正方向垂直屏幕远离用户
* @param x 位置x坐标
* @param y 位置y坐标
* @param z 位置z坐标
*/
setListenerPosition(x: number, y: number, z: number) {
const listener = this.ac.listener;
listener.positionX.value = x;
listener.positionY.value = y;
listener.positionZ.value = z;
}
/**
* 设置听者朝向,x正方向水平向右,y正方向垂直于地面向上,z正方向垂直屏幕远离用户
* @param x 朝向x坐标
* @param y 朝向y坐标
* @param z 朝向z坐标
*/
setListenerOrientation(x: number, y: number, z: number) {
const listener = this.ac.listener;
listener.forwardX.value = x;
listener.forwardY.value = y;
listener.forwardZ.value = z;
}
/**
* 设置听者头顶朝向,x正方向水平向右,y正方向垂直于地面向上,z正方向垂直屏幕远离用户
* @param x 头顶朝向x坐标
* @param y 头顶朝向y坐标
* @param z 头顶朝向z坐标
*/
setListenerUp(x: number, y: number, z: number) {
const listener = this.ac.listener;
listener.upX.value = x;
listener.upY.value = y;
listener.upZ.value = z;
}
}
export const enum AudioStatus {
Playing,
Pausing,
Paused,
Stoping,
Stoped
}
type AudioStartHook = (route: AudioRoute) => void;
type AudioEndHook = (time: number, route: AudioRoute) => void;
interface AudioRouteEvent {
updateEffect: [];
play: [];
stop: [];
pause: [];
resume: [];
}
export class AudioRoute
extends EventEmitter<AudioRouteEvent>
implements IAudioOutput
{
output: AudioNode;
/** 效果器路由图 */
readonly effectRoute: AudioEffect[] = [];
/** 结束时长,当音频暂停或停止时,会经过这么长时间之后才真正终止播放,期间可以做音频淡入淡出等效果 */
endTime: number = 0;
/** 当前播放状态 */
status: AudioStatus = AudioStatus.Stoped;
/** 暂停时刻 */
private pauseTime: number = 0;
/** 暂停时播放了多长时间 */
private pauseCurrentTime: number = 0;
/** 音频时长,单位秒 */
get duration() {
return this.source.duration;
}
/** 当前播放了多长时间,单位秒 */
get currentTime() {
if (this.status === AudioStatus.Paused) {
return this.pauseCurrentTime;
} else {
return this.source.currentTime;
}
}
set currentTime(time: number) {
this.source.stop();
this.source.play(time);
}
private shouldStop: boolean = false;
/**
* 每次暂停或停止时自增,用于判断当前正在处理的情况。
* 假如暂停后很快播放,然后很快暂停,那么需要根据这个来判断实际是否应该执行暂停后操作
*/
stopIdentifier: number = 0;
private audioStartHook?: AudioStartHook;
private audioEndHook?: AudioEndHook;
constructor(
public readonly source: AudioSource,
public readonly player: AudioPlayer
) {
super();
this.output = source.output;
source.on('end', () => {
if (this.status === AudioStatus.Playing) {
this.status = AudioStatus.Stoped;
}
});
source.on('play', () => {
if (this.status !== AudioStatus.Playing) {
this.status = AudioStatus.Playing;
}
});
}
/**
* 设置结束时间,暂停或停止时,会经过这么长时间才终止音频的播放,这期间可以做一下音频淡出的效果。
* @param time 暂停或停止时,经过多长时间之后才会结束音频的播放
*/
setEndTime(time: number) {
this.endTime = time;
}
/**
* 当音频播放时执行的函数,可以用于音频淡入效果
* @param fn 音频开始播放时执行的函数
*/
onStart(fn?: AudioStartHook) {
this.audioStartHook = fn;
}
/**
* 当音频暂停或停止时执行的函数,可以用于音频淡出效果
* @param fn 音频在暂停或停止时执行的函数,不填时表示取消这个钩子。
* 包含两个参数,第一个参数是结束时长,第二个参数是当前音频播放路由对象
*/
onEnd(fn?: AudioEndHook) {
this.audioEndHook = fn;
}
/**
* 开始播放这个音频
* @param when 从音频的什么时候开始播放,单位秒
*/
async play(when: number = 0) {
if (this.status === AudioStatus.Playing) return;
this.link();
await this.player.ac.resume();
if (this.effectRoute.length > 0) {
const first = this.effectRoute[0];
this.source.connect(first);
const last = this.effectRoute.at(-1)!;
last.connect({ input: this.player.getDestination() });
} else {
this.source.connect({ input: this.player.getDestination() });
}
this.source.play(when);
this.status = AudioStatus.Playing;
this.pauseTime = 0;
this.audioStartHook?.(this);
this.startAllEffect();
this.emit('play');
}
/**
* 暂停音频播放
*/
async pause() {
if (this.status !== AudioStatus.Playing) return;
this.status = AudioStatus.Pausing;
this.stopIdentifier++;
const identifier = this.stopIdentifier;
if (this.audioEndHook) {
this.audioEndHook(this.endTime, this);
await sleep(this.endTime);
}
if (
this.status !== AudioStatus.Pausing ||
this.stopIdentifier !== identifier
) {
return;
}
this.pauseCurrentTime = this.source.currentTime;
const time = this.source.stop();
this.pauseTime = time;
if (this.shouldStop) {
this.status = AudioStatus.Stoped;
this.endAllEffect();
this.emit('stop');
this.shouldStop = false;
} else {
this.status = AudioStatus.Paused;
this.endAllEffect();
this.emit('pause');
}
}
/**
* 继续音频播放
*/
resume() {
if (this.status === AudioStatus.Playing) return;
if (
this.status === AudioStatus.Pausing ||
this.status === AudioStatus.Stoping
) {
this.audioStartHook?.(this);
this.emit('resume');
return;
}
if (this.status === AudioStatus.Paused) {
this.play(this.pauseTime);
} else {
this.play(0);
}
this.status = AudioStatus.Playing;
this.pauseTime = 0;
this.audioStartHook?.(this);
this.startAllEffect();
this.emit('resume');
}
/**
* 停止音频播放
*/
async stop() {
if (this.status !== AudioStatus.Playing) {
if (this.status === AudioStatus.Pausing) {
this.shouldStop = true;
}
return;
}
this.status = AudioStatus.Stoping;
this.stopIdentifier++;
const identifier = this.stopIdentifier;
if (this.audioEndHook) {
this.audioEndHook(this.endTime, this);
await sleep(this.endTime);
}
if (
this.status !== AudioStatus.Stoping ||
this.stopIdentifier !== identifier
) {
return;
}
this.source.stop();
this.status = AudioStatus.Stoped;
this.pauseTime = 0;
this.endAllEffect();
this.emit('stop');
}
/**
* 添加效果器
* @param effect 要添加的效果,可以是数组,表示一次添加多个
* @param index 从哪个位置开始添加,如果大于数组长度,那么加到末尾,如果小于0,那么将会从后面往前数。默认添加到末尾
*/
addEffect(effect: AudioEffect | AudioEffect[], index?: number) {
if (isNil(index)) {
if (effect instanceof Array) {
this.effectRoute.push(...effect);
} else {
this.effectRoute.push(effect);
}
} else {
if (effect instanceof Array) {
this.effectRoute.splice(index, 0, ...effect);
} else {
this.effectRoute.splice(index, 0, effect);
}
}
this.setOutput();
if (this.source.playing) this.link();
this.emit('updateEffect');
}
/**
* 移除一个效果器
* @param effect 要移除的效果
*/
removeEffect(effect: AudioEffect) {
const index = this.effectRoute.indexOf(effect);
if (index === -1) return;
this.effectRoute.splice(index, 1);
effect.disconnect();
this.setOutput();
if (this.source.playing) this.link();
this.emit('updateEffect');
}
private setOutput() {
const effect = this.effectRoute.at(-1);
if (!effect) this.output = this.source.output;
else this.output = effect.output;
}
/**
* 连接音频路由图
*/
private link() {
this.effectRoute.forEach(v => v.disconnect());
this.effectRoute.forEach((v, i) => {
const next = this.effectRoute[i + 1];
if (next) {
v.connect(next);
}
});
}
private startAllEffect() {
this.effectRoute.forEach(v => v.start());
}
private endAllEffect() {
this.effectRoute.forEach(v => v.end());
}
}
export const audioPlayer = new AudioPlayer();
// window.audioPlayer = audioPlayer;
@@ -0,0 +1,132 @@
import EventEmitter from 'eventemitter3';
import { audioPlayer, AudioPlayer } from './player';
import { logger } from '@motajs/common';
import { VolumeEffect } from './effect';
type LocationArray = [number, number, number];
interface SoundPlayerEvent {}
export class SoundPlayer<
T extends string = SoundIds
> extends EventEmitter<SoundPlayerEvent> {
/** 每个音效的唯一标识符 */
private num: number = 0;
/** 每个音效的数据 */
readonly buffer: Map<T, AudioBuffer> = new Map();
/** 所有正在播放的音乐 */
readonly playing: Set<number> = new Set();
/** 音量节点 */
readonly gain: VolumeEffect;
/** 是否已经启用 */
enabled: boolean = true;
constructor(public readonly player: AudioPlayer) {
super();
this.gain = player.createVolumeEffect();
}
/**
* 设置是否启用音效
* @param enabled 是否启用音效
*/
setEnabled(enabled: boolean) {
if (!enabled) this.stopAllSounds();
this.enabled = enabled;
}
/**
* 设置音量大小
* @param volume 音量大小
*/
setVolume(volume: number) {
this.gain.setVolume(volume);
}
/**
* 获取音量大小
*/
getVolume() {
return this.gain.getVolume();
}
/**
* 添加一个音效
* @param id 音效名称
* @param data 音效的Uint8Array数据
*/
async add(id: T, data: Uint8Array) {
const buffer = await this.player.decodeAudioData(data);
if (!buffer) {
logger.warn(51, id);
return;
}
this.buffer.set(id, buffer);
}
/**
* 播放一个音效
* @param id 音效名称
* @param position 音频位置,[0, 0, 0]表示正中心,x轴指向水平向右,y轴指向水平向上,z轴指向竖直向上
* @param orientation 音频朝向,[0, 1, 0]表示朝向前方
*/
play(
id: T,
position: LocationArray = [0, 0, 0],
orientation: LocationArray = [1, 0, 0]
) {
if (!this.enabled) return -1;
const buffer = this.buffer.get(id);
if (!buffer) {
logger.warn(52, id);
return -1;
}
const soundNum = this.num++;
const source = this.player.createBufferSource();
source.setBuffer(buffer);
const route = this.player.createRoute(source);
const stereo = this.player.createStereoEffect();
stereo.setPosition(position[0], position[1], position[2]);
stereo.setOrientation(orientation[0], orientation[1], orientation[2]);
route.addEffect([stereo, this.gain]);
this.player.addRoute(`sounds.${soundNum}`, route);
route.play();
source.output.addEventListener('ended', () => {
this.playing.delete(soundNum);
});
this.playing.add(soundNum);
return soundNum;
}
/**
* 停止一个音效
* @param num 音效的唯一 id
*/
stop(num: number) {
const id = `sounds.${num}`;
const route = this.player.getRoute(id);
if (route) {
route.stop();
this.player.removeRoute(id);
this.playing.delete(num);
}
}
/**
* 停止播放所有音效
*/
stopAllSounds() {
this.playing.forEach(v => {
const id = `sounds.${v}`;
const route = this.player.getRoute(id);
if (route) {
route.stop();
this.player.removeRoute(id);
}
});
this.playing.clear();
}
}
export const soundPlayer = new SoundPlayer<SoundIds>(audioPlayer);
@@ -0,0 +1,562 @@
import EventEmitter from 'eventemitter3';
import { IStreamController, IStreamReader } from '../loader';
import { IAudioInput, IAudioOutput } from './effect';
import { logger } from '@motajs/common';
import { AudioType } from './support';
import CodecParser, { CodecFrame, MimeType, OggPage } from 'codec-parser';
import { isNil } from 'lodash-es';
import { IAudioDecodeData, AudioDecoder, checkAudioType } from './decoder';
interface AudioSourceEvent {
play: [];
end: [];
}
export abstract class AudioSource
extends EventEmitter<AudioSourceEvent>
implements IAudioOutput
{
/** 音频源的输出节点 */
abstract readonly output: AudioNode;
/** 是否正在播放 */
playing: boolean = false;
/** 获取音频时长 */
abstract get duration(): number;
/** 获取当前音频播放了多长时间 */
abstract get currentTime(): number;
constructor(public readonly ac: AudioContext) {
super();
}
/**
* 开始播放这个音频源
*/
abstract play(when?: number): void;
/**
* 停止播放这个音频源
* @returns 音频暂停的时刻
*/
abstract stop(): number;
/**
* 连接到音频路由图上,每次调用播放的时候都会执行一次
* @param target 连接至的目标
*/
abstract connect(target: IAudioInput): void;
/**
* 设置是否循环播放
* @param loop 是否循环
*/
abstract setLoop(loop: boolean): void;
}
const mimeTypeMap: Record<AudioType, MimeType> = {
[AudioType.Aac]: 'audio/aac',
[AudioType.Flac]: 'audio/flac',
[AudioType.Mp3]: 'audio/mpeg',
[AudioType.Ogg]: 'application/ogg',
[AudioType.Opus]: 'application/ogg',
[AudioType.Wav]: 'application/ogg'
};
function isOggPage(data: any): data is OggPage {
return !isNil(data.isFirstPage);
}
export class AudioStreamSource extends AudioSource implements IStreamReader {
output: AudioBufferSourceNode;
/** 音频数据 */
buffer?: AudioBuffer;
/** 是否已经完全加载完毕 */
loaded: boolean = false;
/** 已经缓冲了多长时间,如果缓冲完那么跟歌曲时长一致 */
buffered: number = 0;
/** 已经缓冲的采样点数量 */
bufferedSamples: number = 0;
/** 歌曲时长,加载完毕之前保持为 0 */
duration: number = 0;
/** 当前已经播放了多长时间 */
get currentTime(): number {
return this.ac.currentTime - this.lastStartTime + this.lastStartWhen;
}
/** 在流传输阶段,至少缓冲多长时间的音频之后才开始播放,单位秒 */
bufferPlayDuration: number = 1;
/** 音频的采样率,未成功解析出之前保持为 0 */
sampleRate: number = 0;
private controller?: IStreamController;
private loop: boolean = false;
private target?: IAudioInput;
/** 上一次播放是从何时开始的 */
private lastStartWhen: number = 0;
/** 开始播放时刻 */
private lastStartTime: number = 0;
/** 上一次播放的缓存长度 */
private lastBufferSamples: number = 0;
/** 是否已经获取到头文件 */
private headerRecieved: boolean = false;
/** 音频类型 */
private audioType: AudioType | '' = '';
/** 音频解码器 */
private decoder?: AudioDecoder;
/** 音频解析器 */
private parser?: CodecParser;
/** 每多长时间组成一个缓存 Float32Array */
private bufferChunkSize = 10;
/** 缓存音频数据,每 bufferChunkSize 秒钟组成一个 Float32Array,用于流式解码 */
private audioData: Float32Array[][] = [];
private errored: boolean = false;
constructor(context: AudioContext) {
super(context);
this.output = context.createBufferSource();
}
/**
* 设置每个缓存数据的大小,默认为10秒钟一个缓存数据
* @param size 每个缓存数据的时长,单位秒
*/
setChunkSize(size: number) {
if (this.controller?.loading || this.loaded) return;
this.bufferChunkSize = size;
}
piped(controller: IStreamController): void {
this.controller = controller;
}
async pump(data: Uint8Array | undefined, done: boolean): Promise<void> {
if (!data || this.errored) return;
if (!this.headerRecieved) {
// 检查头文件获取音频类型,仅检查前256个字节
const toCheck = data.slice(0, 256);
this.audioType = checkAudioType(data);
if (!this.audioType) {
logger.error(
25,
[...toCheck]
.map(v => v.toString().padStart(2, '0'))
.join(' ')
.toUpperCase()
);
return;
}
// 创建解码器
const Decoder = AudioDecoder.decoderMap.get(this.audioType);
if (!Decoder) {
this.errored = true;
logger.error(24, this.audioType);
return Promise.reject(
`Cannot decode stream source type of '${this.audioType}', since there is no registered decoder for that type.`
);
}
this.decoder = new Decoder();
// 创建数据解析器
const mime = mimeTypeMap[this.audioType];
const parser = new CodecParser(mime);
this.parser = parser;
await this.decoder.create();
this.headerRecieved = true;
}
const decoder = this.decoder;
const parser = this.parser;
if (!decoder || !parser) {
this.errored = true;
return Promise.reject(
'No parser or decoder attached in this AudioStreamSource'
);
}
await this.decodeData(data, decoder, parser);
if (done) await this.decodeFlushData(decoder, parser);
this.checkBufferedPlay();
}
/**
* 检查采样率,如果还未解析出采样率,那么将设置采样率,如果当前采样率与之前不同,那么发出警告
*/
private checkSampleRate(info: (OggPage | CodecFrame)[]) {
for (const one of info) {
const frame = isOggPage(one) ? one.codecFrames[0] : one;
if (frame) {
const rate = frame.header.sampleRate;
if (this.sampleRate === 0) {
this.sampleRate = rate;
break;
} else {
if (rate !== this.sampleRate) {
logger.warn(48);
}
}
}
}
}
/**
* 解析音频数据
*/
private async decodeData(
data: Uint8Array,
decoder: AudioDecoder,
parser: CodecParser
) {
// 解析音频数据
const audioData = await decoder.decode(data);
if (!audioData) return;
// @ts-expect-error 库类型声明错误
const audioInfo = [...parser.parseChunk(data)] as (
| OggPage
| CodecFrame
)[];
// 检查采样率
this.checkSampleRate(audioInfo);
// 追加音频数据
this.appendDecodedData(audioData, audioInfo);
}
/**
* 解码剩余数据
*/
private async decodeFlushData(decoder: AudioDecoder, parser: CodecParser) {
const audioData = await decoder.flush();
if (!audioData) return;
// @ts-expect-error 库类型声明错误
const audioInfo = [...parser.flush()] as (OggPage | CodecFrame)[];
this.checkSampleRate(audioInfo);
this.appendDecodedData(audioData, audioInfo);
}
/**
* 追加音频数据
*/
private appendDecodedData(
data: IAudioDecodeData,
info: (CodecFrame | OggPage)[]
) {
const channels = data.channelData.length;
if (channels === 0) return;
if (this.audioData.length !== channels) {
this.audioData = [];
for (let i = 0; i < channels; i++) {
this.audioData.push([]);
}
}
// 计算出应该放在哪
const chunk = this.sampleRate * this.bufferChunkSize;
const sampled = this.bufferedSamples;
const pushIndex = Math.floor(sampled / chunk);
const bufferIndex = sampled % chunk;
const dataLength = data.channelData[0].length;
let buffered = 0;
let nowIndex = pushIndex;
let toBuffer = bufferIndex;
while (buffered < dataLength) {
const rest = toBuffer !== 0 ? chunk - bufferIndex : chunk;
for (let i = 0; i < channels; i++) {
const audioData = this.audioData[i];
if (!audioData[nowIndex]) {
audioData.push(new Float32Array(chunk));
}
const toPush = data.channelData[i].slice(
buffered,
buffered + rest
);
audioData[nowIndex].set(toPush, toBuffer);
}
buffered += rest;
nowIndex++;
toBuffer = 0;
}
this.buffered +=
info.reduce((prev, curr) => prev + curr.duration, 0) / 1000;
this.bufferedSamples += info.reduce(
(prev, curr) => prev + curr.samples,
0
);
}
/**
* 检查已缓冲内容,并在未开始播放时播放
*/
private checkBufferedPlay() {
if (this.playing || this.sampleRate === 0) return;
const played = this.lastBufferSamples / this.sampleRate;
const dt = this.buffered - played;
if (this.loaded) {
this.playAudio(played);
return;
}
if (dt < this.bufferPlayDuration) return;
this.lastBufferSamples = this.bufferedSamples;
// 需要播放
this.mergeBuffers();
if (!this.buffer) return;
if (this.playing) this.output.stop();
this.createSourceNode(this.buffer);
this.output.loop = false;
this.output.start(0, played);
this.lastStartTime = this.ac.currentTime;
this.playing = true;
this.output.addEventListener('ended', () => {
this.playing = false;
this.checkBufferedPlay();
});
}
private mergeBuffers() {
const buffer = this.ac.createBuffer(
this.audioData.length,
this.bufferedSamples,
this.sampleRate
);
const chunk = this.sampleRate * this.bufferChunkSize;
const bufferedChunks = Math.floor(this.bufferedSamples / chunk);
const restLength = this.bufferedSamples % chunk;
for (let i = 0; i < this.audioData.length; i++) {
const audio = this.audioData[i];
const data = new Float32Array(this.bufferedSamples);
for (let j = 0; j < bufferedChunks; j++) {
data.set(audio[j], chunk * j);
}
if (restLength !== 0) {
data.set(
audio[bufferedChunks].slice(0, restLength),
chunk * bufferedChunks
);
}
buffer.copyToChannel(data, i, 0);
}
this.buffer = buffer;
}
async start() {
delete this.buffer;
this.headerRecieved = false;
this.audioType = '';
this.errored = false;
this.buffered = 0;
this.sampleRate = 0;
this.bufferedSamples = 0;
this.duration = 0;
this.loaded = false;
if (this.playing) this.output.stop();
this.playing = false;
this.lastStartTime = this.ac.currentTime;
}
end(done: boolean, reason?: string): void {
if (done && this.buffer) {
this.loaded = true;
delete this.controller;
this.mergeBuffers();
this.duration = this.buffered;
this.audioData = [];
this.decoder?.destroy();
delete this.decoder;
delete this.parser;
} else {
logger.warn(44, reason ?? '');
}
}
private playAudio(when?: number) {
if (!this.buffer) return;
this.lastStartTime = this.ac.currentTime;
if (this.playing) this.output.stop();
this.emit('play');
this.createSourceNode(this.buffer);
this.output.start(0, when);
this.playing = true;
this.output.addEventListener('ended', () => {
this.playing = false;
this.emit('end');
if (this.loop && !this.output.loop) this.play(0);
});
}
play(when?: number): void {
if (this.playing || this.errored) return;
if (this.loaded && this.buffer) {
this.playing = true;
this.playAudio(when);
} else {
this.controller?.start();
}
}
private createSourceNode(buffer: AudioBuffer) {
if (!this.target) return;
const node = this.ac.createBufferSource();
node.buffer = buffer;
if (this.playing) this.output.stop();
this.playing = false;
this.output = node;
node.connect(this.target.input);
node.loop = this.loop;
}
stop(): number {
if (this.playing) this.output.stop();
this.playing = false;
return this.ac.currentTime - this.lastStartTime;
}
connect(target: IAudioInput): void {
this.target = target;
}
setLoop(loop: boolean): void {
this.loop = loop;
}
}
export class AudioElementSource extends AudioSource {
output: MediaElementAudioSourceNode;
/** audio 元素 */
readonly audio: HTMLAudioElement;
get duration(): number {
return this.audio.duration;
}
get currentTime(): number {
return this.audio.currentTime;
}
constructor(context: AudioContext) {
super(context);
const audio = new Audio();
audio.preload = 'none';
this.output = context.createMediaElementSource(audio);
this.audio = audio;
audio.addEventListener('play', () => {
this.playing = true;
this.emit('play');
});
audio.addEventListener('ended', () => {
this.playing = false;
this.emit('end');
});
}
/**
* 设置音频源的路径
* @param url 音频路径
*/
setSource(url: string) {
this.audio.src = url;
}
play(when: number = 0): void {
if (this.playing) return;
this.audio.currentTime = when;
this.audio.play();
}
stop(): number {
this.audio.pause();
this.playing = false;
this.emit('end');
return this.audio.currentTime;
}
connect(target: IAudioInput): void {
this.output.connect(target.input);
}
setLoop(loop: boolean): void {
this.audio.loop = loop;
}
}
export class AudioBufferSource extends AudioSource {
output: AudioBufferSourceNode;
/** 音频数据 */
buffer?: AudioBuffer;
/** 是否循环 */
private loop: boolean = false;
duration: number = 0;
get currentTime(): number {
return this.ac.currentTime - this.lastStartTime + this.lastStartWhen;
}
/** 上一次播放是从何时开始的 */
private lastStartWhen: number = 0;
/** 播放开始时刻 */
private lastStartTime: number = 0;
private target?: IAudioInput;
constructor(context: AudioContext) {
super(context);
this.output = context.createBufferSource();
}
/**
* 设置音频源数据
* @param buffer 音频源,可以是未解析的 ArrayBuffer,也可以是已解析的 AudioBuffer
*/
async setBuffer(buffer: ArrayBuffer | AudioBuffer) {
if (buffer instanceof ArrayBuffer) {
this.buffer = await this.ac.decodeAudioData(buffer);
} else {
this.buffer = buffer;
}
this.duration = this.buffer.duration;
}
play(when?: number): void {
if (this.playing || !this.buffer) return;
this.playing = true;
this.lastStartTime = this.ac.currentTime;
this.emit('play');
this.createSourceNode(this.buffer);
this.output.start(0, when);
this.output.addEventListener('ended', () => {
this.playing = false;
this.emit('end');
if (this.loop && !this.output.loop) this.play(0);
});
}
private createSourceNode(buffer: AudioBuffer) {
if (!this.target) return;
const node = this.ac.createBufferSource();
node.buffer = buffer;
this.output = node;
node.connect(this.target.input);
node.loop = this.loop;
}
stop(): number {
this.output.stop();
return this.ac.currentTime - this.lastStartTime;
}
connect(target: IAudioInput): void {
this.target = target;
}
setLoop(loop: boolean): void {
this.loop = loop;
}
}
@@ -0,0 +1,55 @@
const audio = new Audio();
const supportMap = new Map<string, boolean>();
export const enum AudioType {
Mp3 = 'audio/mpeg',
Wav = 'audio/wav; codecs="1"',
Flac = 'audio/flac',
Opus = 'audio/ogg; codecs="opus"',
Ogg = 'audio/ogg; codecs="vorbis"',
Aac = 'audio/aac'
}
/**
* 检查一种音频类型是否能被播放
* @param type 音频类型
*/
export function isAudioSupport(type: AudioType): boolean {
if (supportMap.has(type)) return supportMap.get(type)!;
else {
const support = audio.canPlayType(type);
const canPlay = support === 'maybe' || support === 'probably';
supportMap.set(type, canPlay);
return canPlay;
}
}
const typeMap = new Map<string, AudioType>([
['ogg', AudioType.Ogg],
['mp3', AudioType.Mp3],
['wav', AudioType.Wav],
['flac', AudioType.Flac],
['opus', AudioType.Opus],
['aac', AudioType.Aac]
]);
/**
* 根据文件名拓展猜测其类型
* @param file 文件名
*/
export function guessTypeByExt(file: string): AudioType | '' {
const ext = /\.[a-zA-Z\d]+$/.exec(file);
if (!ext?.[0]) return '';
const type = ext[0].slice(1);
return typeMap.get(type.toLocaleLowerCase()) ?? '';
}
isAudioSupport(AudioType.Ogg);
isAudioSupport(AudioType.Mp3);
isAudioSupport(AudioType.Wav);
isAudioSupport(AudioType.Flac);
isAudioSupport(AudioType.Opus);
isAudioSupport(AudioType.Aac);
console.log(supportMap);
@@ -0,0 +1,70 @@
import { Patch, PatchClass } from '@motajs/legacy-common';
import { audioPlayer, bgmController, soundPlayer } from '../audio';
import { mainSetting } from '@motajs/legacy-ui';
import { sleep } from 'mutate-animate';
import { isNil } from 'lodash-es';
// todo: 添加弃用警告 logger.warn(56)
export function patchAudio() {
const patch = new Patch(PatchClass.Control);
const play = (bgm: BgmIds, when?: number) => {
bgmController.play(bgm, when);
};
const pause = () => {
bgmController.pause();
};
patch.add('playBgm', function (bgm, startTime) {
play(bgm, startTime);
});
patch.add('pauseBgm', function () {
pause();
});
patch.add('resumeBgm', function () {
bgmController.resume();
});
patch.add('checkBgm', function () {
if (bgmController.playing) return;
if (mainSetting.getValue('audio.bgmEnabled')) {
if (bgmController.playingBgm) {
bgmController.play(bgmController.playingBgm);
} else {
play(main.startBgm, 0);
}
} else {
pause();
}
});
patch.add('triggerBgm', function () {
if (bgmController.playing) bgmController.pause();
else bgmController.resume();
});
patch.add(
'playSound',
function (sound, _pitch, callback, position, orientation) {
const name = core.getMappedName(sound) as SoundIds;
const num = soundPlayer.play(name, position, orientation);
const route = audioPlayer.getRoute(`sounds.${num}`);
if (!route) {
callback?.();
return -1;
} else {
sleep(route.duration).then(() => callback?.());
return num;
}
}
);
patch.add('stopSound', function (id) {
if (isNil(id)) {
soundPlayer.stopAllSounds();
} else {
soundPlayer.stop(id);
}
});
patch.add('getPlayingSounds', function () {
return [...soundPlayer.playing];
});
}
@@ -0,0 +1,14 @@
import { Patch } from '@motajs/legacy-common';
import { patchAudio } from './audio';
import { patchWeather } from './weather';
import { patchUI } from './ui';
export function patchAll() {
patchAudio();
patchWeather();
patchUI();
const loading = Mota.require('var', 'loading');
loading.once('coreInit', () => {
Patch.patchAll();
});
}
@@ -0,0 +1,11 @@
import { Patch, PatchClass } from '@motajs/legacy-common';
import { TipStore } from '../render/components/tip';
export function patchUI() {
const patch = new Patch(PatchClass.UI);
patch.add('drawTip', function (text, id) {
const tip = TipStore.get('main-tip');
tip?.drawTip(text, id);
});
}
@@ -0,0 +1,23 @@
import { Patch, PatchClass } from '@motajs/legacy-common';
import { WeatherController } from '../weather';
import { isNil } from 'lodash-es';
// todo: 添加弃用警告 logger.warn(56)
export function patchWeather() {
const patch = new Patch(PatchClass.Control);
let nowWeather: string = '';
let nowLevel: number = 0;
patch.add('setWeather', (type, level) => {
const weather = WeatherController.get('main');
if (!weather) return;
if (type === nowWeather && level === nowLevel) return;
weather.clearWeather();
if (!isNil(type)) {
weather.activate(type, level);
nowWeather = type;
nowLevel = level ?? 5;
}
});
}
@@ -0,0 +1,9 @@
import { patchAll } from './fallback';
patchAll();
export * from './weather';
export * from './audio';
export * from './loader';
export * from './fallback';
export * from './render';
@@ -0,0 +1 @@
export * from './stream';
@@ -0,0 +1,128 @@
import { logger } from '@motajs/common';
import EventEmitter from 'eventemitter3';
export interface IStreamController<T = void> {
readonly loading: boolean;
/**
* 开始流传输
*/
start(): Promise<T>;
/**
* 主动终止流传输
* @param reason 终止原因
*/
cancel(reason?: string): void;
}
export interface IStreamReader<T = any> {
/**
* 接受字节流流传输的数据
* @param data 传入的字节流数据,只包含本分块的内容
* @param done 是否传输完成
*/
pump(
data: Uint8Array | undefined,
done: boolean,
response: Response
): Promise<void>;
/**
* 当前对象被传递给加载流时执行的函数
* @param controller 传输流控制对象
*/
piped(controller: IStreamController<T>): void;
/**
* 开始流传输
* @param stream 传输流对象
* @param controller 传输流控制对象
*/
start(
stream: ReadableStream,
controller: IStreamController<T>,
response: Response
): Promise<void>;
/**
* 结束流传输
* @param done 是否传输完成,如果为 false 的话,说明可能是由于出现错误导致的终止
* @param reason 如果没有传输完成,那么表示失败的原因
*/
end(done: boolean, reason?: string): void;
}
interface StreamLoaderEvent {
data: [data: Uint8Array | undefined, done: boolean];
}
export class StreamLoader
extends EventEmitter<StreamLoaderEvent>
implements IStreamController<void>
{
/** 传输目标 */
private target: Set<IStreamReader> = new Set();
/** 读取流对象 */
private stream?: ReadableStream;
loading: boolean = false;
constructor(public readonly url: string) {
super();
}
/**
* 将加载流传递给字节流读取对象
* @param reader 字节流读取对象
*/
pipe(reader: IStreamReader) {
if (this.loading) {
logger.warn(46);
return;
}
this.target.add(reader);
reader.piped(this);
return this;
}
async start() {
if (this.loading) return;
this.loading = true;
const response = await window.fetch(this.url);
const stream = response.body;
if (!stream) {
logger.error(23);
return;
}
// 获取读取器
this.stream = stream;
const reader = response.body?.getReader();
const targets = [...this.target];
await Promise.all(targets.map(v => v.start(stream, this, response)));
if (reader && reader.read) {
// 开始流传输
while (true) {
const { value, done } = await reader.read();
await Promise.all(
targets.map(v => v.pump(value, done, response))
);
if (done) break;
}
} else {
// 如果不支持流传输
const buffer = await response.arrayBuffer();
const data = new Uint8Array(buffer);
await Promise.all(targets.map(v => v.pump(data, true, response)));
}
this.loading = false;
targets.forEach(v => v.end(true));
}
cancel(reason?: string) {
if (!this.stream) return;
this.stream.cancel(reason);
this.loading = false;
this.target.forEach(v => v.end(false, reason));
}
}
@@ -0,0 +1,637 @@
import { DefaultProps, ElementLocator, Font, useKey } from '@motajs/render';
import { computed, defineComponent, reactive, ref } from 'vue';
import { Background, Selection } from './misc';
import { TextContent, TextContentExpose, TextContentProps } from './textbox';
import { SetupComponentOptions } from './types';
import { TextAlign } from './textboxTyper';
import { Page, PageExpose } from './page';
import { GameUI, IUIMountable } from '@motajs/system-ui';
export interface ConfirmBoxProps extends DefaultProps, TextContentProps {
text: string;
width: number;
loc: ElementLocator;
selFont?: Font;
selFill?: CanvasStyle;
pad?: number;
yesText?: string;
noText?: string;
winskin?: ImageIds;
defaultYes?: boolean;
color?: CanvasStyle;
border?: CanvasStyle;
}
export type ConfirmBoxEmits = {
yes: () => void;
no: () => void;
};
const confirmBoxProps = {
props: [
'text',
'width',
'loc',
'selFont',
'selFill',
'pad',
'yesText',
'noText',
'winskin',
'defaultYes',
'color',
'border'
],
emits: ['no', 'yes']
} satisfies SetupComponentOptions<
ConfirmBoxProps,
ConfirmBoxEmits,
keyof ConfirmBoxEmits
>;
/**
* 确认框组件,与 2.x 的 drawConfirm 类似,可以键盘操作,单次调用参考 {@link getConfirm}。
* 参数参考 {@link ConfirmBoxProps},事件参考 {@link ConfirmBoxEmits},用例如下:
* ```tsx
* const onYes = () => console.log('yes');
* const onNo = () => console.log('no');
*
* <ConfirmBox
* text="是否要返回标题界面"
* width={240}
* // 确认框会自动计算宽度和高度,因此不需要手动指定,即使手动指定也无效
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
* // 使用 winskin 图片作为背景
* winskin="winskin.png"
* // 使用颜色作为背景和边框,如果设置了 winskin,那么此参数无效
* color="#333"
* border="gold"
* // 设置选项的字体
* selFont={new Font('Verdana', 16)}
* // 设置选项的文本颜色
* selFill="#d48"
* // 完全继承 TextContent 的参数,因此可以填写 font 参数指定文本字体
* font={new Font('arial')}
* onYes={onYes}
* onNo={onNo}
* />
* ```
*/
export const ConfirmBox = defineComponent<
ConfirmBoxProps,
ConfirmBoxEmits,
keyof ConfirmBoxEmits
>((props, { emit, attrs }) => {
const content = ref<TextContentExpose>();
const height = ref(200);
const selected = ref(props.defaultYes ? true : false);
const yesSize = ref<[number, number]>([0, 0]);
const noSize = ref<[number, number]>([0, 0]);
const loc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, height.value, ax, ay];
});
const yesText = computed(() => props.yesText ?? '确认');
const noText = computed(() => props.noText ?? '取消');
const pad = computed(() => props.pad ?? 32);
const yesLoc = computed<ElementLocator>(() => {
const y = height.value - pad.value;
return [props.width / 3, y, void 0, void 0, 0.5, 1];
});
const noLoc = computed<ElementLocator>(() => {
const y = height.value - pad.value;
return [(props.width / 3) * 2, y, void 0, void 0, 0.5, 1];
});
const contentLoc = computed<ElementLocator>(() => {
const width = props.width - pad.value * 2;
return [props.width / 2, pad.value, width, 0, 0.5, 0];
});
const selectLoc = computed<ElementLocator>(() => {
if (selected.value) {
const [x = 0, y = 0] = yesLoc.value;
const [width, height] = yesSize.value;
return [x, y + 4, width + 8, height + 8, 0.5, 1];
} else {
const [x = 0, y = 0] = noLoc.value;
const [width, height] = noSize.value;
return [x, y + 4, width + 8, height + 8, 0.5, 1];
}
});
const onUpdateHeight = (textHeight: number) => {
height.value = textHeight + pad.value * 4;
};
const setYes = (_: string, width: number, height: number) => {
yesSize.value = [width, height];
};
const setNo = (_: string, width: number, height: number) => {
noSize.value = [width, height];
};
const [key] = useKey();
key.realize('confirm', () => {
if (selected.value) emit('yes');
else emit('no');
});
key.realize('moveLeft', () => void (selected.value = true));
key.realize('moveRight', () => void (selected.value = false));
return () => (
<container loc={loc.value}>
<Background
loc={[0, 0, props.width, height.value]}
winskin={props.winskin}
color={props.color}
border={props.border}
zIndex={0}
/>
<TextContent
{...attrs}
ref={content}
loc={contentLoc.value}
text={props.text}
width={props.width - pad.value * 2}
zIndex={5}
textAlign={TextAlign.Center}
autoHeight
onUpdateHeight={onUpdateHeight}
/>
<Selection
loc={selectLoc.value}
winskin={props.winskin}
border={props.border}
noevent
zIndex={10}
/>
<text
loc={yesLoc.value}
text={yesText.value}
fillStyle={props.selFill}
font={props.selFont}
cursor="pointer"
zIndex={15}
onClick={() => emit('yes')}
onEnter={() => (selected.value = true)}
onSetText={setYes}
/>
<text
loc={noLoc.value}
text={noText.value}
fillStyle={props.selFill}
font={props.selFont}
cursor="pointer"
zIndex={15}
onClick={() => emit('no')}
onEnter={() => (selected.value = false)}
onSetText={setNo}
/>
</container>
);
}, confirmBoxProps);
export type ChoiceKey = string | number | symbol;
export type ChoiceItem = [key: ChoiceKey, text: string];
export interface ChoicesProps extends DefaultProps, TextContentProps {
choices: ChoiceItem[];
loc: ElementLocator;
width: number;
maxHeight?: number;
text?: string;
title?: string;
winskin?: ImageIds;
color?: CanvasStyle;
border?: CanvasStyle;
selFont?: Font;
selFill?: CanvasStyle;
titleFont?: Font;
titleFill?: CanvasStyle;
pad?: number;
interval?: number;
}
export type ChoicesEmits = {
choose: (key: ChoiceKey) => void;
};
const choicesProps = {
props: [
'choices',
'loc',
'width',
'maxHeight',
'text',
'title',
'winskin',
'color',
'border',
'selFont',
'selFill',
'titleFont',
'titleFill',
'pad',
'interval'
],
emits: ['choose']
} satisfies SetupComponentOptions<
ChoicesProps,
ChoicesEmits,
keyof ChoicesEmits
>;
/**
* 选项框组件,用于在多个选项中选择一个,例如样板的系统设置就由它实现。单次调用参考 {@link getChoice}。
* 参数参考 {@link ChoicesProps},事件参考 {@link ChoicesEmits}。用例如下:
* ```tsx
* <Choices
* // 选项数组,每一项是一个二元素数组,第一项表示这个选项的 id,在选中时会以此作为参数传递给事件
* // 第二项表示这一项的内容,即展示给玩家看的内容
* choices={[[0, '选项1'], [100, '选项2']]}
* // 选项框会自动计算宽度和高度,因此不需要手动指定,即使手动指定也无效
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
* text="请选择一项"
* title="选项"
* // 使用 winskin 图片作为背景
* winskin="winskin.png"
* // 使用颜色作为背景和边框,如果设置了 winskin,那么此参数无效
* color="#333"
* border="gold"
* // 调整每两个选项之间的间隔
* interval={12}
* // 设置选项的字体
* selFont={new Font('Verdana', 16)}
* // 设置选项的文本颜色
* selFill="#d48"
* // 设置标题的字体
* titleFont={new Font('Verdana', 16)}
* // 设置标题的文本颜色
* selFill="gold"
* // 完全继承 TextContent 的参数,因此可以填写 font 参数指定文本字体
* font={new Font('arial')}
* // 当选择某一项时触发
* onChoice={(choice) => console.log(choice)}
* />
* ```
*/
export const Choices = defineComponent<
ChoicesProps,
ChoicesEmits,
keyof ChoicesEmits
>((props, { emit, attrs }) => {
const titleHeight = ref(0);
const contentHeight = ref(0);
const selected = ref(0);
const pageCom = ref<PageExpose>();
const choiceSize = reactive<[number, number][]>([]);
const selFont = computed(() => props.selFont ?? new Font());
const maxHeight = computed(() => props.maxHeight ?? 360);
const pad = computed(() => props.pad ?? 28);
const choiceInterval = computed(() => props.interval ?? 16);
const hasText = computed(() => !!props.text);
const hasTitle = computed(() => !!props.title);
const contentWidth = computed(() => props.width - pad.value * 2);
const choiceHeight = computed(
() => selFont.value.size + 8 + choiceInterval.value
);
const contentY = computed(() => {
if (hasTitle.value) {
return pad.value * 2 + titleHeight.value;
} else {
return pad.value;
}
});
const choicesY = computed(() => {
const padding = pad.value;
const text = hasText.value;
let y = padding;
if (hasTitle.value) {
y += titleHeight.value;
if (text) {
y += padding / 2;
} else {
y += padding;
}
}
if (text) {
y += contentHeight.value;
y += padding / 2;
}
return y;
});
const choicesMaxHeight = computed(
() =>
maxHeight.value -
choicesY.value -
pad.value * 2 -
selFont.value.size -
8
);
const choiceCountPerPage = computed(() =>
Math.max(Math.floor(choicesMaxHeight.value / choiceHeight.value), 1)
);
const pages = computed(() =>
Math.ceil(props.choices.length / choiceCountPerPage.value)
);
const choicesHeight = computed(() => {
const padBottom = pages.value > 1 ? pad.value + selFont.value.size : 0;
if (props.choices.length > choiceCountPerPage.value) {
return choiceCountPerPage.value * choiceHeight.value + padBottom;
} else {
return props.choices.length * choiceHeight.value + padBottom;
}
});
const boxHeight = computed(() => {
if (props.choices.length > choiceCountPerPage.value) {
return (
choicesHeight.value +
choicesY.value +
// 不乘2是因为 choiceY 已经算上了顶部填充
pad.value
);
} else {
return (
choicesHeight.value +
choicesY.value +
// 不乘2是因为 choiceY 已经算上了顶部填充
pad.value
);
}
});
const boxLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, boxHeight.value, ax, ay];
});
const titleLoc = computed<ElementLocator>(() => {
return [props.width / 2, pad.value, void 0, void 0, 0.5, 0];
});
const contentLoc = computed<ElementLocator>(() => {
return [
props.width / 2,
contentY.value,
contentWidth.value,
void 0,
0.5,
0
];
});
const choiceLoc = computed<ElementLocator>(() => {
return [
props.width / 2,
choicesY.value,
contentWidth.value,
choicesHeight.value,
0.5,
0
];
});
const selectionLoc = computed<ElementLocator>(() => {
const [width = 200, height = 200] = choiceSize[selected.value] ?? [];
return [
props.width / 2 - pad.value,
(selected.value + 0.5) * choiceHeight.value,
width + 8,
height + 8,
0.5,
0.5
];
});
const getPageContent = (page: number) => {
const count = choiceCountPerPage.value;
return props.choices.slice(page * count, (page + 1) * count);
};
const getChoiceLoc = (index: number): ElementLocator => {
return [
props.width / 2 - pad.value,
choiceHeight.value * (index + 0.5),
void 0,
void 0,
0.5,
0.5
];
};
const updateContentHeight = (height: number) => {
contentHeight.value = height;
};
const updateTitleHeight = (_0: string, _1: number, height: number) => {
titleHeight.value = height;
};
const updateChoiceSize = (index: number, width: number, height: number) => {
choiceSize[index] = [width, height];
};
const onPageChange = () => {
selected.value = 0;
};
const [key] = useKey();
key.realize('moveUp', () => {
if (selected.value === 0) {
if (pageCom.value?.now() !== 0) {
pageCom.value?.movePage(-1);
selected.value = choiceCountPerPage.value - 1;
}
} else {
selected.value--;
}
});
key.realize('moveDown', () => {
if (selected.value === choiceCountPerPage.value - 1) {
pageCom.value?.movePage(1);
selected.value = 0;
} else {
const page = pageCom.value?.now() ?? 1;
const index = page * choiceCountPerPage.value + selected.value;
if (index < props.choices.length - 1) {
selected.value++;
}
}
});
key.realize('moveLeft', () => pageCom.value?.movePage(-1));
key.realize('moveRight', () => pageCom.value?.movePage(1));
key.realize('confirm', () => {
const page = pageCom.value?.now() ?? 1;
const index = page * choiceCountPerPage.value + selected.value;
emit('choose', props.choices[index][0]);
});
return () => (
<container loc={boxLoc.value}>
<Background
loc={[0, 0, props.width, boxHeight.value]}
winskin={props.winskin}
color={props.color}
border={props.border}
/>
{hasTitle.value && (
<text
loc={titleLoc.value}
text={props.title}
font={props.titleFont ?? new Font(void 0, 18)}
fillStyle={props.titleFill ?? 'gold'}
zIndex={5}
onSetText={updateTitleHeight}
/>
)}
{hasText.value && (
<TextContent
{...attrs}
text={props.text}
loc={contentLoc.value}
width={contentWidth.value}
zIndex={5}
autoHeight
onUpdateHeight={updateContentHeight}
/>
)}
<Page
ref={pageCom}
loc={choiceLoc.value}
pages={pages.value}
font={props.selFont}
hideIfSingle
onPageChange={onPageChange}
>
{(page: number) => [
<Selection
loc={selectionLoc.value}
winskin={props.winskin}
color={props.color}
border={props.border}
/>,
...getPageContent(page).map((v, i) => {
return (
<text
text={v[1]}
loc={getChoiceLoc(i)}
font={props.selFont}
cursor="pointer"
zIndex={5}
onClick={() => emit('choose', v[0])}
onSetText={(_, width, height) =>
updateChoiceSize(i, width, height)
}
onEnter={() => (selected.value = i)}
/>
);
})
]}
</Page>
</container>
);
}, choicesProps);
/**
* 弹出一个确认框,然后将确认结果返回,例如给玩家弹出一个确认框,并获取玩家是否确认:
* ```ts
* const confirm = await getConfirm(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 确认内容
* '确认要 xxx 吗?',
* // 确认框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 宽度设为 240
* 240,
* // 可以给选择框传入其他的 props,例如指定字体,此项可选
* { font: new Font('Verdana', 20) }
* );
* // 之后,就可以直接判断 confirm 来执行不同的操作了
* if (confirm) { ... }
* ```
* @param controller UI 控制器
* @param text 确认文本内容
* @param loc 确认框的位置
* @param width 确认框的宽度
* @param props 额外的 props,参考 {@link ConfirmBoxProps}
*/
export function getConfirm(
controller: IUIMountable,
text: string,
loc: ElementLocator,
width: number,
props?: Partial<ConfirmBoxProps>
) {
return new Promise<boolean>(res => {
const instance = controller.open(
ConfirmBoxUI,
{
...(props ?? {}),
loc,
text,
width,
onYes: () => {
controller.close(instance);
res(true);
},
onNo: () => {
controller.close(instance);
res(false);
}
},
true
);
});
}
/**
* 弹出一个选择框,然后将选择结果返回,例如给玩家弹出一个选择框,并获取玩家选择了哪个:
* ```ts
* const choice = await getChoice(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 选项内容,参考 Choices 的注释
* [[0, '选项1'], [1, '选项2'], [2, '选项3']],
* // 选择框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 宽度设为 240
* 240,
* // 可以给选择框传入其他的 props,例如指定标题,此项可选
* { title: '选项标题' }
* );
* // 之后,就可以直接判断 choice 来执行不同的操作了
* if (choice === 0) { ... }
* ```
* @param controller UI 控制器
* @param choices 选择框的选项
* @param loc 选择框的位置
* @param width 选择框的宽度
* @param props 额外的 props,参考 {@link ChoicesProps}
*/
export function getChoice<T extends ChoiceKey = ChoiceKey>(
controller: IUIMountable,
choices: ChoiceItem[],
loc: ElementLocator,
width: number,
props?: Partial<ChoicesProps>
) {
return new Promise<T>(res => {
const instance = controller.open(
ChoicesUI,
{
...(props ?? {}),
choices,
loc,
width,
onChoose: key => {
controller.close(instance);
res(key as T);
}
},
true
);
});
}
/** @see {@link ConfirmBox} */
export const ConfirmBoxUI = new GameUI('confirm-box', ConfirmBox);
/** @see {@link Choices} */
export const ChoicesUI = new GameUI('choices', Choices);
@@ -0,0 +1,503 @@
import { DefaultProps, ElementLocator, GraphicPropsBase } from '@motajs/render';
import { computed, defineComponent, onMounted, Ref, ref, watch } from 'vue';
import { SetupComponentOptions } from './types';
export interface IconsProps extends DefaultProps<GraphicPropsBase> {
loc: ElementLocator;
}
const iconsProps = {
props: ['loc']
} satisfies SetupComponentOptions<IconsProps>;
type PathGenerator = (width: number, height: number) => Path2D;
/**
* @param ox 横向偏移坐标
* @param oy 纵向偏移坐标
* @param width 路径宽度
* @param height 路径高度
*/
type PathFn = (ox: number, oy: number, width: number, height: number) => Path2D;
function adjustPath(
aspect: number,
ref: Ref<Path2D | undefined>,
fn: PathFn
): PathGenerator {
let beforeWidth = 200;
let beforeHeight = 200;
let path: Path2D | undefined;
return (width, height) => {
if (width === beforeWidth && height === beforeHeight && path) {
return path;
}
beforeWidth = width;
beforeHeight = height;
const eleAspect = width / height;
let ox = 0;
let oy = 0;
let dw = 0;
let dh = 0;
if (aspect >= eleAspect) {
ox = 0;
dw = width;
dh = width / aspect;
oy = (height - dh) / 2;
} else {
oy = 0;
dh = height;
dw = height * aspect;
ox = (width - dw) / 2;
}
path = fn(ox, oy, dw, dh);
ref.value = path;
return path;
};
}
export const RollbackIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const arc = width / 10;
const arrow = width / 10;
const left = ox + width / 10;
const top = oy + height / 5;
const right = ox + width - width / 10;
const bottom = oy + height - height / 5;
const end = left + width / 4;
path.moveTo(left, bottom);
path.lineTo(right - arc, bottom);
path.arcTo(right, bottom, right, bottom - arc, arc);
path.lineTo(right, top + arc);
path.arcTo(right, top, right - arc, top, arc);
path.lineTo(end, top);
path.moveTo(end + arrow, top - arrow);
path.lineTo(end, top);
path.lineTo(end + arrow, top + arrow);
path.moveTo(left, top);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const RetweetIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const arc = width / 10;
const arrow = width / 10;
const left = ox + width / 10;
const top = oy + height / 5;
const right = ox + width - width / 10;
const bottom = oy + height - height / 5;
const end = left + width / 2;
path.moveTo(end, bottom);
path.lineTo(left + arc, bottom);
path.arcTo(left, bottom, left, bottom - arc, arc);
path.lineTo(left, top + arc);
path.arcTo(left, top, left + arc, top, arc);
path.lineTo(right, top);
path.moveTo(right - arrow, top - arrow);
path.lineTo(right, top);
path.lineTo(right - arrow, top + arrow);
path.moveTo(left, top);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const ViewMapIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
path.rect(left, top, right - left, bottom - top);
path.moveTo(cx, top);
path.lineTo(cx, bottom);
path.moveTo(left, cy);
path.lineTo(right, cy);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const DanmakuIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
const rx = width / 3;
const ry = height / 4;
const start = (Math.PI * 16) / 18;
const end = (Math.PI * 12) / 18;
path.ellipse(cx, cy, rx, ry, 0, start, end);
path.lineTo(left - width / 24, bottom - height / 36);
path.closePath();
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const ReplayIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const arc = width / 10;
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cy = oy + height / 2;
path.moveTo(right, cy - height / 8);
path.lineTo(right, top + arc);
path.arcTo(right, top, right - arc, top, arc);
path.lineTo(left + arc, top);
path.arcTo(left, top, left, top + arc, arc);
path.lineTo(left, cy);
path.moveTo(left + arc, cy - arc);
path.lineTo(left, cy);
path.lineTo(left - arc, cy - arc);
path.moveTo(left, cy + height / 8);
path.lineTo(left, bottom - arc);
path.arcTo(left, bottom, left + arc, bottom, arc);
path.lineTo(right - arc, bottom);
path.arcTo(right, bottom, right, bottom - arc, arc);
path.lineTo(right, cy);
path.moveTo(right - arc, cy + arc);
path.lineTo(right, cy);
path.lineTo(right + arc, cy + arc);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const NumpadIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
path.rect(left, top, right - left, bottom - top);
const path2 = new Path2D();
path2.ellipse(cx, cy, width / 9, height / 6, 0, 0, Math.PI * 2);
path.addPath(path2);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const PlayIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
path.moveTo(left, top);
path.lineTo(right, oy + height / 2);
path.lineTo(left, bottom);
path.closePath();
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
fill
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const PauseIcon = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const cx = ox + width / 2;
const top = oy + height / 5;
const bottom = oy + height - height / 5;
path.moveTo(cx - width / 5, top);
path.lineTo(cx - width / 5, bottom);
path.moveTo(cx + width / 5, top);
path.lineTo(cx + width / 5, bottom);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const DoubleArrow = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const path2 = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
const cx = ox + width / 2;
const cy = oy + height / 2;
path.moveTo(left, top + height / 12);
path.lineTo(cx + width / 8, cy);
path.lineTo(left, bottom - height / 12);
path.closePath();
path2.moveTo(cx, top + height / 12);
path2.lineTo(right, cy);
path2.lineTo(cx, bottom - height / 12);
path2.closePath();
path.addPath(path2);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
fill
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
export const StepForward = defineComponent<IconsProps>(props => {
const path = ref<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
const path = new Path2D();
const path2 = new Path2D();
const left = ox + width / 5;
const top = oy + height / 5;
const right = ox + width - width / 5;
const bottom = oy + height - height / 5;
path.moveTo(left, top);
path.lineTo(right, oy + height / 2);
path.lineTo(left, bottom);
path.closePath();
path2.moveTo(right, top);
path2.lineTo(right, bottom);
path.addPath(path2);
return path;
});
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => {
return (
<g-path
loc={props.loc}
path={path.value}
stroke
fill
lineJoin="round"
lineCap="round"
></g-path>
);
};
}, iconsProps);
@@ -0,0 +1,9 @@
export * from './choices';
export * from './icons';
export * from './misc';
export * from './page';
export * from './scroll';
export * from './textbox';
export * from './textboxTyper';
export * from './tip';
export * from './types';
@@ -0,0 +1,583 @@
import {
DefaultProps,
ElementLocator,
onTick,
PathProps,
Sprite
} from '@motajs/render';
import { computed, defineComponent, ref, SetupContext, watch } from 'vue';
import { SetupComponentOptions } from './types';
import { MotaOffscreenCanvas2D } from '@motajs/render';
import { TextboxProps, TextContent, TextContentProps } from './textbox';
import { Scroll, ScrollExpose, ScrollProps } from './scroll';
import { transitioned } from '../use';
import { hyper } from 'mutate-animate';
import { logger } from '@motajs/common';
import { GameUI, IUIMountable } from '@motajs/system-ui';
interface ProgressProps extends DefaultProps {
/** 进度条的位置 */
loc: ElementLocator;
/** 进度条的进度,1表示完成,0表示未完成 */
progress: number;
/** 已完成部分的样式,默认为绿色(green) */
success?: CanvasStyle;
/** 未完成部分的样式,默认为灰色(gray) */
background?: CanvasStyle;
/** 线宽度 */
lineWidth?: number;
}
const progressProps = {
props: ['loc', 'progress', 'success', 'background']
} satisfies SetupComponentOptions<ProgressProps>;
/**
* 进度条组件,参数参考 {@link ProgressProps},用例如下:
* ```tsx
* // 定义进度
* const progress = ref(0);
*
* // 显示进度条
* <Progress loc={[12, 12, 120, 8]} progress={progress.value} />
* ```
*/
export const Progress = defineComponent<ProgressProps>(props => {
const element = ref<Sprite>();
const render = (canvas: MotaOffscreenCanvas2D) => {
const { ctx } = canvas;
const width = props.loc[2] ?? 200;
const height = props.loc[3] ?? 200;
ctx.lineCap = 'round';
const lineWidth = props.lineWidth ?? 2;
ctx.lineWidth = lineWidth;
ctx.strokeStyle = props.background ?? 'gray';
ctx.beginPath();
ctx.moveTo(lineWidth, height / 2);
ctx.lineTo(width - lineWidth, height / 2);
ctx.stroke();
if (!isNaN(props.progress)) {
ctx.strokeStyle = props.success ?? 'green';
const p = lineWidth + (width - lineWidth * 2) * props.progress;
ctx.beginPath();
ctx.moveTo(lineWidth, height / 2);
ctx.lineTo(p, height / 2);
ctx.stroke();
}
};
watch(props, () => {
element.value?.update();
});
return () => {
return <sprite ref={element} loc={props.loc} render={render}></sprite>;
};
}, progressProps);
export interface ArrowProps extends PathProps {
/** 箭头的起始和终点坐标,前两个是起始坐标,后两个是终点坐标 */
arrow: [number, number, number, number];
/** 箭头的头部大小 */
head?: number;
/** 箭头的颜色 */
color?: CanvasStyle;
}
const arrowProps = {
props: ['arrow', 'head', 'color']
} satisfies SetupComponentOptions<ArrowProps>;
/**
* 箭头组件,显示一个箭头,参数参考 {@link ArrowProps},用例如下:
* ```tsx
* // 从 (12, 12) 到 (48, 48) 的箭头
* <Arrow arrow={[12, 12, 48, 48]} />
* ```
*/
export const Arrow = defineComponent<ArrowProps>(props => {
const loc = computed<ElementLocator>(() => {
const [x1, y1, x2, y2] = props.arrow;
const left = Math.min(x1, x2);
const right = Math.max(x1, x2);
const top = Math.min(y1, y2);
const bottom = Math.max(y1, y2);
return [left, top, right - left, bottom - top];
});
const path = computed(() => {
const path = new Path2D();
const head = props.head ?? 8;
const [x = 0, y = 0] = loc.value;
const [x1, y1, x2, y2] = props.arrow;
path.moveTo(x1 - x, y1 - y);
path.lineTo(x2 - x, y2 - y);
const angle = Math.atan2(y2 - y1, x2 - x1);
path.moveTo(
x2 - head * Math.cos(angle - Math.PI / 6),
y2 - head * Math.sin(angle - Math.PI / 6)
);
path.lineTo(x2 - x, y2 - y);
path.lineTo(
x2 - head * Math.cos(angle + Math.PI / 6),
y2 - head * Math.sin(angle + Math.PI / 6)
);
return path;
});
return () => (
<g-path
loc={loc.value}
path={path.value}
stroke
strokeStyle={props.color}
lineCap="round"
lineJoin="round"
/>
);
}, arrowProps);
export interface ScrollTextProps extends TextboxProps, ScrollProps {
/** 自动滚动的速度,每秒多少像素 */
speed: number;
/** 文字的最大宽度 */
width: number;
/** 自动滚动组件的定位 */
loc: ElementLocator;
/** 文字滚动入元素之前要先滚动多少像素,默认16像素 */
pad?: number;
}
export type ScrollTextEmits = {
/**
* 当滚动完毕时触发
*/
scrollEnd: () => void;
};
export interface ScrollTextExpose {
/**
* 暂停滚动
*/
pause(): void;
/**
* 继续滚动
*/
resume(): void;
/**
* 设置滚动速度
*/
setSpeed(speed: number): void;
/**
* 立刻重新滚动
*/
rescroll(): void;
}
const scrollProps = {
props: ['speed', 'loc', 'pad', 'width'],
emits: ['scrollEnd']
} satisfies SetupComponentOptions<
ScrollTextProps,
ScrollTextEmits,
keyof ScrollTextEmits
>;
/**
* 滚动文字,可以用于展示长剧情或者 staff 表,参数参考 {@link ScrollTextProps},
* 事件参考 {@link ScrollTextEmits},函数接口参考 {@link ScrollTextExpose},用例如下:
* ```tsx
* // 用于接受函数接口
* const scroll = ref<ScrollTextExpose>();
* // 显示的文字
* const text = '滚动文字'.repeat(100);
*
* onMounted(() => {
* // 设置为每秒滚动 100 像素
* scroll.value?.setSpeed(100);
* // 暂停滚动
* scroll.value?.pause();
* });
*
* // 显示滚动文字,每秒滚动 50 像素
* <ScrollText ref={scroll} text={text} speed={50} loc={[0, 0, 180, 100]} width={180} />
* ```
*/
export const ScrollText = defineComponent<
ScrollTextProps,
ScrollTextEmits,
keyof ScrollTextEmits
>((props, { emit, expose, attrs }) => {
const scroll = ref<ScrollExpose>();
const speed = ref(props.speed);
const eleHeight = computed(() => props.loc[3] ?? props.width);
const pad = computed(() => props.pad ?? 16);
let lastFixedTime = Date.now();
let lastFixedPos = 0;
let paused = false;
let nowScroll = 0;
onTick(() => {
if (paused || !scroll.value) return;
const now = Date.now();
const dt = now - lastFixedTime;
nowScroll = (dt / 1000) * speed.value + lastFixedPos;
scroll.value.scrollTo(nowScroll, 0);
if (nowScroll >= scroll.value.getScrollLength()) {
emit('scrollEnd');
paused = true;
}
});
const pause = () => {
paused = true;
};
const resume = () => {
paused = false;
lastFixedPos = nowScroll;
lastFixedTime = Date.now();
};
const setSpeed = (value: number) => {
lastFixedPos = nowScroll;
lastFixedTime = Date.now();
speed.value = value;
};
const rescroll = () => {
nowScroll = 0;
lastFixedTime = Date.now();
lastFixedPos = 0;
};
expose<ScrollTextExpose>({ pause, resume, setSpeed, rescroll });
return () => (
<Scroll
ref={scroll}
loc={props.loc}
padEnd={eleHeight.value + pad.value}
noscroll
>
<TextContent
{...attrs}
width={props.width - 16}
loc={[8, eleHeight.value + pad.value]}
autoHeight
/>
</Scroll>
);
}, scrollProps);
export interface SelectionProps extends DefaultProps {
loc: ElementLocator;
color?: CanvasStyle;
border?: CanvasStyle;
winskin?: ImageIds;
/** 选择图标的不透明度范围 */
alphaRange?: [number, number];
}
const selectionProps = {
props: ['loc', 'color', 'border', 'winskin', 'alphaRange']
} satisfies SetupComponentOptions<SelectionProps>;
/**
* 显示一个选择光标,与 2.x 的 drawUIEventSelector 效果一致,参数参考 {@link SelectionProps},用例如下:
* ```tsx
* // 使用 winskin.png 作为选择光标,光标动画的不透明度范围是 [0.3, 0.8]
* <Selection loc={[24, 24, 80, 16]} winskin="winskin.png" alphaRange={[0.3, 0.8]} />
* // 使用指定的填充和边框颜色作为选择光标
* <Selection loc={[24, 24, 80, 16]} color="#ddd" border="gold" />
* ```
*/
export const Selection = defineComponent<SelectionProps>(props => {
const minAlpha = computed(() => props.alphaRange?.[0] ?? 0.25);
const maxAlpha = computed(() => props.alphaRange?.[1] ?? 0.55);
const alpha = transitioned(minAlpha.value, 2000, hyper('sin', 'in-out'))!;
const isWinskin = computed(() => !!props.winskin);
const winskinImage = computed(() =>
isWinskin.value ? core.material.images.images[props.winskin!] : null
);
const fixedLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, width = 200, height = 200] = props.loc;
return [x + 1, y + 1, width - 2, height - 2];
});
const renderWinskin = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
const image = winskinImage.value;
if (!image) return;
const [, , width = 200, height = 200] = props.loc;
// 背景
ctx.drawImage(image, 130, 66, 28, 28, 2, 2, width - 4, height - 4);
// 四个角
ctx.drawImage(image, 128, 64, 2, 2, 0, 0, 2, 2);
ctx.drawImage(image, 158, 64, 2, 2, width - 2, 0, 2, 2);
ctx.drawImage(image, 128, 94, 2, 2, 0, height - 2, 2, 2);
ctx.drawImage(image, 158, 94, 2, 2, width - 2, height - 2, 2, 2);
// 四条边
ctx.drawImage(image, 130, 64, 28, 2, 2, 0, width - 4, 2);
ctx.drawImage(image, 130, 94, 28, 2, 2, height - 2, width - 4, 2);
ctx.drawImage(image, 128, 66, 2, 28, 0, 2, 2, height - 4);
ctx.drawImage(image, 158, 66, 2, 28, width - 2, 2, 2, height - 4);
};
onTick(() => {
if (alpha.value === maxAlpha.value) {
alpha.set(minAlpha.value);
}
if (alpha.value === minAlpha.value) {
alpha.set(maxAlpha.value);
}
});
return () =>
isWinskin.value ? (
<sprite
loc={props.loc}
render={renderWinskin}
alpha={alpha.ref.value}
noanti
/>
) : (
<g-rectr
loc={fixedLoc.value}
circle={[4]}
alpha={alpha.ref.value}
fill
stroke
fillStyle={props.color}
strokeStyle={props.border}
lineWidth={1}
/>
);
}, selectionProps);
export interface BackgroundProps extends DefaultProps {
loc: ElementLocator;
winskin?: ImageIds;
color?: CanvasStyle;
border?: CanvasStyle;
}
const backgroundProps = {
props: ['loc', 'winskin', 'color', 'border']
} satisfies SetupComponentOptions<BackgroundProps>;
/**
* 背景组件,与 Selection 类似,不过绘制的是背景,而不是选择光标,参数参考 {@link BackgroundProps},用例如下:
* ```tsx
* // 使用 winskin2.png 作为背景
* <Background loc={[8, 8, 160, 160]} winskin="winskin2.png" />
* // 使用指定填充和边框颜色作为背景
* <Background loc={[8, 8, 160, 160]} color="#333" border="gold" />
* ```
*/
export const Background = defineComponent<BackgroundProps>(props => {
const isWinskin = computed(() => !!props.winskin);
const fixedLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, width = 200, height = 200] = props.loc;
return [x + 2, y + 2, width - 4, height - 4];
});
return () =>
isWinskin.value ? (
<winskin image={props.winskin!} loc={props.loc} noanti />
) : (
<g-rectr
loc={fixedLoc.value}
fillStyle={props.color}
strokeStyle={props.border}
fill
stroke
lineWidth={2}
circle={[4]}
/>
);
}, backgroundProps);
export interface WaitBoxProps<T>
extends Partial<BackgroundProps>,
Partial<TextContentProps> {
loc: ElementLocator;
width: number;
promise?: Promise<T>;
text?: string;
pad?: number;
}
export type WaitBoxEmits<T> = {
resolve: (data: T) => void;
};
export interface WaitBoxExpose<T> {
/**
* 手动将此组件兑现,注意调用时如果传入的 Promise 还没有兑现,
* 当 Promise 兑现后将不会再次触发 resolve 事件,即 resolve 事件只会被触发一次
* @param data 兑现值
*/
resolve(data: T): void;
}
const waitBoxProps = {
props: ['promise', 'loc', 'winskin', 'color', 'border'],
emits: ['resolve']
} satisfies SetupComponentOptions<
WaitBoxProps<unknown>,
WaitBoxEmits<unknown>,
keyof WaitBoxEmits<unknown>
>;
/**
* 等待框,可以等待某个异步操作 (Promise),操作完毕后触发兑现事件,单次调用参考 {@link waitbox}。
* 参数参考 {@link WaitBoxProps},事件参考 {@link WaitBoxEmits},函数接口参考 {@link WaitBoxExpose}。用例如下:
* ```tsx
* // 创建一个等待 1000ms 的 Promise,兑现值是等待完毕时的当前时间刻
* const promise = new Promise(res => window.setTimeout(() => res(Date.now()), 1000));
*
* <WaitBox
* // 传入要等待的 Promise
* promise={promise}
* // 等待框的位置,宽度由 width 参数指定,高度由内部计算得来,不需要手动指定,即使手动指定也无效
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
* // 等待框的宽度
* width={240}
* // 完全继承 Background 的参数,因此可以直接指定背景样式
* winskin="winskin2.png"
* // 完全继承 TextContent 的参数,因此可以直接指定字体
* font={new Font('Verdana', 28)}
* />
* ```
*/
export const WaitBox = defineComponent<
WaitBoxProps<unknown>,
WaitBoxEmits<unknown>,
keyof WaitBoxEmits<unknown>
>(
<T,>(
props: WaitBoxProps<T>,
{ emit, expose, attrs }: SetupContext<WaitBoxEmits<T>>
) => {
const contentHeight = ref(200);
const text = computed(() => props.text ?? '请等待 ...');
const pad = computed(() => props.pad ?? 24);
const containerLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, contentHeight.value, ax, ay];
});
const backLoc = computed<ElementLocator>(() => {
return [1, 1, props.width - 2, contentHeight.value - 2];
});
const contentLoc = computed<ElementLocator>(() => {
return [
pad.value,
pad.value,
props.width - pad.value * 2,
contentHeight.value - pad.value * 2
];
});
let resolved: boolean = false;
props.promise?.then(
value => {
resolve(value);
},
reason => {
logger.warn(63, reason);
}
);
const resolve = (data: T) => {
if (resolved) return;
resolved = true;
emit('resolve', data);
};
const onContentHeight = (height: number) => {
contentHeight.value = height + pad.value * 2;
};
expose<WaitBoxExpose<T>>({ resolve });
return () => (
<container loc={containerLoc.value}>
<Background
loc={backLoc.value}
zIndex={0}
winskin={props.winskin}
color={props.color}
border={props.border}
/>
<TextContent
{...attrs}
autoHeight
text={text.value}
loc={contentLoc.value}
width={props.width - pad.value * 2}
zIndex={5}
onUpdateHeight={onContentHeight}
/>
</container>
);
},
waitBoxProps
);
/**
* 打开一个等待框,等待传入的 Promise 兑现后,关闭等待框,并将兑现值返回。
* 示例,等待 1000ms:
* ```ts
* // 创建一个等待 1000ms 的 Promise,兑现值是等待完毕时的当前时间刻
* const promise = new Promise(res => window.setTimeout(() => res(Date.now()), 1000));
* const value = await waitbox(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 确认框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 确认框的宽度
* 240,
* // 要等待的 Promise
* promise,
* // 额外的 props,例如填写等待文本,此项可选,参考 WaitBoxProps
* { text: '请等待 1000ms' }
* );
* console.log(value); // 输出时间刻
* ```
* @param controller UI 控制器
* @param loc 等待框的位置
* @param width 等待框的宽度
* @param promise 要等待的 Promise
* @param props 额外的 props,参考 {@link WaitBoxProps}
*/
export function waitbox<T>(
controller: IUIMountable,
loc: ElementLocator,
width: number,
promise: Promise<T>,
props?: Partial<WaitBoxProps<T>>
): Promise<T> {
return new Promise<T>(res => {
const instance = controller.open(WaitBoxUI, {
...(props ?? {}),
loc,
width,
promise,
onResolve: data => {
controller.close(instance);
res(data as T);
}
});
});
}
export const WaitBoxUI = new GameUI('wait-box', WaitBox);
@@ -0,0 +1,320 @@
import {
computed,
defineComponent,
nextTick,
onMounted,
ref,
SlotsType,
VNode,
watch
} from 'vue';
import { SetupComponentOptions } from './types';
import { clamp } from 'lodash-es';
import { DefaultProps, ElementLocator, Font } from '@motajs/render';
/** 圆角矩形页码距离容器的边框大小,与 pageSize 相乘 */
const RECT_PAD = 0.1;
export interface PageProps extends DefaultProps {
/** 共有多少页 */
pages: number;
/** 页码组件的定位 */
loc: ElementLocator;
/** 页码的字体 */
font?: Font;
/** 只有一页的时候,是否隐藏页码 */
hideIfSingle?: boolean;
}
export type PageEmits = {
pageChange: (page: number) => void;
};
export interface PageExpose {
/**
* 切换页码
* @param page 要切换至的页码数,1 表示第一页
*/
changePage(page: number): void;
/**
* 切换到传入的页码数加上当前页码数的页码
* @param delta 页码数增量
*/
movePage(delta: number): void;
/**
* 获取当前在第几页
*/
now(): number;
}
type PageSlots = SlotsType<{
default: (page: number) => VNode | VNode[];
}>;
const pageProps = {
props: ['pages', 'loc', 'font', 'hideIfSingle'],
emits: ['pageChange']
} satisfies SetupComponentOptions<
PageProps,
PageEmits,
keyof PageEmits,
PageSlots
>;
/**
* 分页组件,用于多页切换,例如存档界面等。参数参考 {@link PageProps},函数接口参考 {@link PageExpose}
*
* ---
*
* 用例如下,是一个在每页显示文字的用例,其中 page 表示页码索引,第一页就是 0,第二页就是 1,以此类推:
* ```tsx
* <Page maxPage={5}>
* {
* (page: number) => {
* return items[page].map(v => <text text={v.text} />)
* }
* }
* </Page>
* ```
*/
export const Page = defineComponent<
PageProps,
PageEmits,
keyof PageEmits,
PageSlots
>((props, { slots, expose, emit }) => {
const nowPage = ref(0);
// 五个元素的位置
const leftLoc = ref<ElementLocator>([]);
const leftPageLoc = ref<ElementLocator>([]);
const nowPageLoc = ref<ElementLocator>([]);
const rightPageLoc = ref<ElementLocator>([]);
const rightLoc = ref<ElementLocator>([]);
/** 内容的位置 */
const contentLoc = ref<ElementLocator>([]);
/** 页码容器的位置 */
const pageLoc = ref<ElementLocator>([]);
/** 页码的矩形框的位置 */
const rectLoc = ref<ElementLocator>([0, 0, 0, 0]);
/** 页面文字的位置 */
const textLoc = ref<ElementLocator>([0, 0, 0, 0]);
// 两个监听的参数
const leftArrow = ref<Path2D>();
const rightArrow = ref<Path2D>();
const hide = computed(() => props.hideIfSingle && props.pages === 1);
const font = computed(() => props.font ?? new Font());
const isFirst = computed(() => nowPage.value === 0);
const isLast = computed(() => nowPage.value === props.pages - 1);
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const round = computed(() => font.value.size / 4);
const nowPageFont = computed(() => Font.clone(font.value, { weight: 700 }));
// 左右箭头的颜色
const leftColor = computed(() => (isFirst.value ? '#666' : '#ddd'));
const rightColor = computed(() => (isLast.value ? '#666' : '#ddd'));
let updating = false;
const updatePagePos = () => {
if (updating) return;
updating = true;
nextTick(() => {
updating = false;
});
const pageH = hide.value ? 0 : font.value.size + 8;
contentLoc.value = [0, 0, width.value, height.value - pageH];
pageLoc.value = [0, height.value - pageH, width.value, pageH];
const center = width.value / 2;
const size = font.value.size * 1.5;
nowPageLoc.value = [center, 0, size, size, 0.5, 0];
leftPageLoc.value = [center - size * 1.5, 0, size, size, 0.5, 0];
leftLoc.value = [center - size * 3, 0, size, size, 0.5, 0];
rightPageLoc.value = [center + size * 1.5, 0, size, size, 0.5, 0];
rightLoc.value = [center + size * 3, 0, size, size, 0.5, 0];
};
const updateArrowPath = () => {
const rectSize = font.value.size * 1.5;
const size = font.value.size;
const pad = rectSize - size;
const left = new Path2D();
left.moveTo(size, pad);
left.lineTo(pad, rectSize / 2);
left.lineTo(size, rectSize - pad);
const right = new Path2D();
right.moveTo(pad, pad);
right.lineTo(size, rectSize / 2);
right.lineTo(pad, rectSize - pad);
leftArrow.value = left;
rightArrow.value = right;
};
const updateRectAndText = () => {
const size = font.value.size * 1.5;
const pad = RECT_PAD * size;
rectLoc.value = [pad, pad, size - pad * 2, size - pad * 2];
textLoc.value = [size / 2, size / 2, void 0, void 0, 0.5, 0.5];
};
watch(font, () => {
updatePagePos();
updateArrowPath();
updateRectAndText();
});
watch(
() => props.loc,
() => {
updatePagePos();
updateRectAndText();
}
);
/**
* 切换页码
*/
const changePage = (page: number) => {
const target = clamp(page, 0, props.pages - 1);
if (nowPage.value !== target) {
nowPage.value = target;
emit('pageChange', target);
}
};
const movePage = (delta: number) => {
changePage(nowPage.value + delta);
};
const now = () => nowPage.value;
const lastPage = () => {
changePage(nowPage.value - 1);
};
const nextPage = () => {
changePage(nowPage.value + 1);
};
onMounted(() => {
updatePagePos();
updateArrowPath();
updateRectAndText();
});
expose<PageExpose>({ changePage, movePage, now });
return () => {
return (
<container loc={props.loc}>
<container loc={contentLoc.value}>
{slots.default?.(nowPage.value)}
</container>
<container loc={pageLoc.value} hidden={hide.value}>
<container
key={1}
loc={leftLoc.value}
onClick={lastPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle={leftColor.value}
lineWidth={1}
stroke
></g-rectr>
<g-path
path={leftArrow.value}
stroke
strokeStyle={leftColor.value}
lineWidth={1}
></g-path>
</container>
{!isFirst.value && (
<container
key={2}
loc={leftPageLoc.value}
onClick={lastPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle="#ddd"
lineWidth={1}
stroke
></g-rectr>
<text
loc={textLoc.value}
text={nowPage.value.toString()}
font={font.value}
></text>
</container>
)}
<container loc={nowPageLoc.value} key={3}>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle="#ddd"
fillStyle="#ddd"
lineWidth={1}
fill
stroke
></g-rectr>
<text
loc={textLoc.value}
text={(nowPage.value + 1).toString()}
fillStyle="#222"
font={nowPageFont.value}
></text>
</container>
{!isLast.value && (
<container
key={4}
loc={rightPageLoc.value}
onClick={nextPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle="#ddd"
lineWidth={1}
stroke
></g-rectr>
<text
loc={textLoc.value}
text={(nowPage.value + 2).toString()}
font={font.value}
></text>
</container>
)}
<container
key={5}
loc={rightLoc.value}
onClick={nextPage}
cursor="pointer"
>
<g-rectr
loc={rectLoc.value}
circle={[round.value]}
strokeStyle={rightColor.value}
lineWidth={1}
stroke
></g-rectr>
<g-path
path={rightArrow.value}
stroke
strokeStyle={rightColor.value}
lineWidth={1}
></g-path>
</container>
</container>
</container>
);
};
}, pageProps);
@@ -0,0 +1,556 @@
import {
computed,
defineComponent,
nextTick,
onMounted,
onUnmounted,
onUpdated,
ref,
SlotsType,
VNode,
watch
} from 'vue';
import { SetupComponentOptions } from './types';
import {
Container,
DefaultProps,
ElementLocator,
RenderItem,
Sprite,
Transform,
MotaOffscreenCanvas2D,
IActionEvent,
IWheelEvent,
MouseType
} from '@motajs/render';
import { hyper, linear, Transition } from 'mutate-animate';
import { clamp } from 'lodash-es';
import { transitioned } from '../use';
export const enum ScrollDirection {
Horizontal,
Vertical
}
export interface ScrollExpose {
/**
* 控制滚动条滚动至目标位置
* @param y 滚动至的目标位置
* @param time 滚动的动画时长,默认为无动画
*/
scrollTo(y: number, time?: number): void;
/**
* 获取这个滚动条组件最多可以滚动多长
*/
getScrollLength(): number;
}
export interface ScrollProps extends DefaultProps {
loc: ElementLocator;
hor?: boolean;
noscroll?: boolean;
/**
* 滚动到最下方(最右方)时的填充大小,如果默认的高度计算方式有误,
* 那么可以调整此参数来修复错误
*/
padEnd?: number;
}
type ScrollSlots = SlotsType<{
default: () => VNode | VNode[];
}>;
const scrollProps = {
props: ['hor', 'noscroll', 'loc', 'padEnd']
} satisfies SetupComponentOptions<ScrollProps, {}, string, ScrollSlots>;
/** 滚动条图示的最短长度 */
const SCROLL_MIN_LENGTH = 20;
/** 滚动条图示的宽度 */
const SCROLL_WIDTH = 10;
/** 滚动条的颜色 */
const SCROLL_COLOR = '255,255,255';
/**
* 滚动条组件,具有虚拟滚动功能,即在画面外的不渲染。参数参考 {@link ScrollProps},暴露接口参考 {@link ScrollExpose}
*
* ---
*
* 使用时,建议使用平铺式布局,即包含很多子元素,而不要用一个 container 将所有内容包裹,
* 每个子元素的高度(宽度)不建议过大,以更好地通过虚拟滚动优化
*
* **推荐写法**:
* ```tsx
* <Scroll>
* <item />
* <item />
* ...其他元素
* <item />
* <item />
* </Scroll>
* ```
* **不推荐**使用这种写法:
* ```tsx
* <Scroll>
* <container>
* <item />
* </container>
* <Scroll>
* ```
*/
export const Scroll = defineComponent<ScrollProps, {}, string, ScrollSlots>(
(props, { slots, expose }) => {
/** 滚动条的定位 */
const sp = ref<ElementLocator>([0, 0, 1, 1]);
const listenedChild: Set<RenderItem> = new Set();
const areaMap: Map<RenderItem, [number, number]> = new Map();
const content = ref<Container>();
const scroll = ref<Sprite>();
const scrollAlpha = transitioned(0.5, 100, linear())!;
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const direction = computed(() =>
props.hor ? ScrollDirection.Horizontal : ScrollDirection.Vertical
);
const scrollColor = computed(
() => `rgba(${SCROLL_COLOR},${scrollAlpha.ref.value ?? 0.5})`
);
const padEnd = computed(() => props.padEnd ?? 0);
watch(scrollColor, () => {
scroll.value?.update();
});
/** 滚动内容的当前位置 */
let contentPos = 0;
/** 滚动条的当前位置 */
let scrollPos = 0;
/** 滚动内容的目标位置 */
let contentTarget = 0;
/** 滚动条的目标位置 */
let scrollTarget = 0;
/** 滚动内容的长度 */
let maxLength = 0;
/** 滚动条的长度 */
let scrollLength = SCROLL_MIN_LENGTH;
const transition = new Transition();
transition.value.scroll = 0;
transition.value.showScroll = 0;
transition.mode(hyper('sin', 'out')).absolute();
//#region 滚动操作
transition.ticker.add(() => {
if (scrollPos !== scrollTarget) {
scrollPos = transition.value.scroll;
content.value?.update();
}
if (contentPos !== contentTarget) {
contentPos = transition.value.showScroll;
checkAllItem();
content.value?.update();
}
});
/**
* 滚动到目标值
* @param time 动画时长
*/
const scrollTo = (y: number, time: number = 0) => {
if (maxLength < height.value) return;
const max = maxLength - height.value;
const target = clamp(y, 0, max);
contentTarget = target;
if (direction.value === ScrollDirection.Horizontal) {
scrollTarget =
(width.value - scrollLength) * (contentTarget / max);
} else {
scrollTarget =
(height.value - scrollLength) * (contentTarget / max);
}
if (isNaN(scrollTarget)) scrollTarget = 0;
transition.time(time).transition('scroll', scrollTarget);
transition.time(time).transition('showScroll', target);
};
/**
* 计算一个元素会在画面上显示的区域
*/
const getArea = (item: RenderItem, rect: DOMRectReadOnly) => {
if (direction.value === ScrollDirection.Horizontal) {
areaMap.set(item, [rect.left - width.value, rect.right]);
} else {
areaMap.set(item, [rect.top - height.value, rect.bottom]);
}
};
/**
* 检查一个元素是否需要显示,不需要则隐藏
*/
const checkItem = (item: RenderItem) => {
const area = areaMap.get(item);
if (!area) {
item.show();
return;
}
const [min, max] = area;
if (contentPos > min - 10 && contentPos < max + 10) {
item.show();
} else {
item.hide();
}
};
/**
* 对所有元素执行显示检查
*/
const checkAllItem = () => {
content.value?.children.forEach(v => checkItem(v));
};
/**
* 当一个元素的矩阵发生变换时执行,检查其显示区域
*/
const onTransform = (item: RenderItem) => {
const rect = item.getBoundingRect();
const pad = props.padEnd ?? 0;
if (item.parent === content.value) {
if (direction.value === ScrollDirection.Horizontal) {
if (rect.right > maxLength - pad) {
maxLength = rect.right + pad;
updatePosition();
}
} else {
if (rect.bottom > maxLength - pad) {
maxLength = rect.bottom + pad;
updatePosition();
}
}
} else {
item.off('transform', onTransform);
listenedChild.delete(item);
}
getArea(item, rect);
checkItem(item);
scroll.value?.update();
content.value?.update();
};
/**
* 更新滚动条位置
*/
const updatePosition = () => {
if (direction.value === ScrollDirection.Horizontal) {
scrollLength = clamp(
(height.value / maxLength) * width.value,
SCROLL_MIN_LENGTH,
width.value
);
const h = props.noscroll
? height.value
: height.value - SCROLL_WIDTH;
sp.value = [0, h, width.value, SCROLL_WIDTH];
} else {
scrollLength = clamp(
(height.value / maxLength) * height.value,
SCROLL_MIN_LENGTH,
height.value
);
const w = props.noscroll
? width.value
: width.value - SCROLL_WIDTH;
sp.value = [w, 0, SCROLL_WIDTH, height.value];
}
};
let updating = false;
const updateScroll = () => {
if (!content.value || updating) return;
updating = true;
nextTick(() => {
updating = false;
});
let max = 0;
listenedChild.forEach(v => v.off('transform', onTransform));
listenedChild.clear();
areaMap.clear();
content.value.children.forEach(v => {
if (v.isComment) return;
const rect = v.getBoundingRect();
if (direction.value === ScrollDirection.Horizontal) {
if (rect.right > max) {
max = rect.right;
}
} else {
if (rect.bottom > max) {
max = rect.bottom;
}
}
getArea(v, rect);
if (!listenedChild.has(v)) {
v.on('transform', onTransform);
listenedChild.add(v);
}
checkItem(v);
});
maxLength = Math.max(max + padEnd.value, 10);
updatePosition();
scroll.value?.update();
};
watch(() => props.loc, updateScroll);
onUpdated(updateScroll);
onMounted(updateScroll);
onUnmounted(() => {
listenedChild.forEach(v => v.off('transform', onTransform));
});
//#endregion
//#region 渲染滚动
const drawScroll = (canvas: MotaOffscreenCanvas2D) => {
if (props.noscroll) return;
const ctx = canvas.ctx;
ctx.lineCap = 'round';
ctx.lineWidth = 3;
ctx.strokeStyle = scrollColor.value;
ctx.beginPath();
const scroll = transition.value.scroll;
if (direction.value === ScrollDirection.Horizontal) {
ctx.moveTo(scroll + 5, 5);
ctx.lineTo(scroll + scrollLength - 5, 5);
} else {
ctx.moveTo(5, scroll + 5);
ctx.lineTo(5, scroll + scrollLength - 5);
}
ctx.stroke();
};
const renderContent = (
canvas: MotaOffscreenCanvas2D,
children: RenderItem[],
transform: Transform
) => {
const ctx = canvas.ctx;
ctx.save();
if (direction.value === ScrollDirection.Horizontal) {
ctx.translate(-contentPos, 0);
} else {
ctx.translate(0, -contentPos);
}
children.forEach(v => {
if (v.hidden) return;
v.renderContent(canvas, transform);
});
ctx.restore();
};
//#endregion
//#region 事件监听
const wheelScroll = (delta: number, max: number) => {
const sign = Math.sign(delta);
const dx = Math.abs(delta);
const movement = Math.min(max, dx) * sign;
scrollTo(contentTarget + movement, dx > 10 ? 300 : 0);
};
const wheel = (ev: IWheelEvent) => {
if (direction.value === ScrollDirection.Horizontal) {
if (ev.wheelX !== 0) {
wheelScroll(ev.wheelX, width.value / 5);
} else if (ev.wheelY !== 0) {
wheelScroll(ev.wheelY, width.value / 5);
}
} else {
wheelScroll(ev.wheelY, height.value / 5);
}
};
const getPos = (ev: IActionEvent, absolute: boolean = false) => {
if (absolute) {
if (direction.value === ScrollDirection.Horizontal) {
return ev.absoluteX;
} else {
return ev.absoluteY;
}
} else {
if (direction.value === ScrollDirection.Horizontal) {
return ev.offsetX;
} else {
return ev.offsetY;
}
}
};
let identifier = -2;
let downPos = 0;
/** 拖动内容时,内容原本所在的位置 */
let contentBefore = 0;
const down = (ev: IActionEvent) => {
identifier = ev.identifier;
downPos = getPos(ev, true);
contentBefore = contentTarget;
};
const move = (ev: IActionEvent) => {
if (ev.identifier !== identifier) return;
let pos = 0;
if (ev.touch) {
pos = getPos(ev);
} else {
if (ev.buttons & MouseType.Left) {
pos = getPos(ev);
} else {
return;
}
}
const movement = pos - downPos;
scrollTo(contentBefore - movement, 0);
};
/** 最初滚动条在哪 */
let scrollBefore = 0;
/** 本次拖动滚动条的操作标识符 */
let scrollIdentifier = -2;
/** 点击滚动条时,点击位置在平行于滚动条方向的位置 */
let scrollDownPos = 0;
/** 是否是点击了滚动条区域中滚动条之外的地方,这样视为类滚轮操作 */
let scrollMutate = false;
/** 点击滚动条时,点击位置垂直于滚动条方向的位置 */
let scrollPin = 0;
/**
* 获取点击滚动条时,垂直于滚动条方向的位置
*/
const getScrollPin = (ev: IActionEvent) => {
if (direction.value === ScrollDirection.Horizontal) {
return ev.absoluteY;
} else {
return ev.absoluteX;
}
};
const downScroll = (ev: IActionEvent) => {
scrollBefore = contentTarget;
scrollIdentifier = ev.identifier;
const pos = getPos(ev, true);
// 计算点击在了滚动条的哪个位置
const offsetPos = getPos(ev);
const sEnd = scrollPos + scrollLength;
if (offsetPos >= scrollPos && offsetPos <= sEnd) {
scrollDownPos = pos - scrollPos;
scrollMutate = false;
scrollPin = getScrollPin(ev);
} else {
scrollMutate = true;
}
scrollAlpha.set(0.9);
};
const moveScroll = (ev: IActionEvent) => {
if (ev.identifier !== scrollIdentifier || scrollMutate) return;
const pos = getPos(ev, true);
const scrollPos = pos - scrollDownPos;
let deltaPin = 0;
let threshold = 0;
if (ev.touch) {
const pin = getScrollPin(ev);
deltaPin = Math.abs(pin - scrollPin);
threshold = 200;
} else {
const pin = getScrollPin(ev);
deltaPin = Math.abs(pin - scrollPin);
threshold = 100;
}
if (deltaPin > threshold) {
scrollTo(scrollBefore, 0);
} else {
const pos = (scrollPos / height.value) * maxLength;
scrollTo(pos, 0);
}
};
const upScroll = (ev: IActionEvent) => {
scrollAlpha.set(0.7);
if (!scrollMutate) return;
const pos = getPos(ev);
if (pos < scrollPos) {
scrollTo(contentTarget - 50, 300);
} else {
scrollTo(contentTarget + 50, 300);
}
};
const enter = () => {
scrollAlpha.set(0.7);
};
const leave = () => {
scrollAlpha.set(0.5);
};
//#endregion
onMounted(() => {
scroll.value?.root?.on('move', move);
scroll.value?.root?.on('move', moveScroll);
});
onUnmounted(() => {
scroll.value?.root?.off('move', move);
scroll.value?.root?.off('move', moveScroll);
transition.ticker.destroy();
});
//#region expose 函数
const getScrollLength = () => {
return maxLength - height.value;
};
expose<ScrollExpose>({
scrollTo,
getScrollLength
});
//#endregion
return () => {
return (
<container loc={props.loc} onWheel={wheel}>
<container-custom
loc={[0, 0, props.loc[2], props.loc[3]]}
ref={content}
onDown={down}
render={renderContent}
zIndex={0}
>
{slots.default?.()}
</container-custom>
<sprite
nocache
hidden={props.noscroll}
loc={sp.value}
ref={scroll}
render={drawScroll}
onDown={downScroll}
onUp={upScroll}
zIndex={10}
onEnter={enter}
onLeave={leave}
></sprite>
</container>
);
};
},
scrollProps
);
@@ -0,0 +1,593 @@
import {
ElementLocator,
Font,
Sprite,
DefaultProps,
Text,
MotaOffscreenCanvas2D
} from '@motajs/render';
import {
computed,
defineComponent,
nextTick,
onMounted,
onUnmounted,
ref,
shallowReactive,
shallowRef,
SlotsType,
VNode,
watch
} from 'vue';
import { logger } from '@motajs/common';
import { isNil } from 'lodash-es';
import { SetupComponentOptions } from './types';
import EventEmitter from 'eventemitter3';
import {
ITextContentConfig,
TextContentTyper,
TyperRenderable,
TextContentType,
WordBreak,
TextAlign
} from './textboxTyper';
export interface TextContentProps
extends DefaultProps,
Partial<ITextContentConfig> {
/** 显示的文字 */
text?: string;
/** 是否填充 */
fill?: boolean;
/** 是否描边 */
stroke?: boolean;
/** 是否自适应高度 */
autoHeight?: boolean;
/** 文字的最大宽度 */
width: number;
}
export type TextContentEmits = {
typeEnd: () => void;
typeStart: () => void;
updateHeight: (height: number) => void;
};
export interface TextContentExpose {
/**
* 重新开始打字
*/
retype(): void;
/**
* 立刻显示所有文字
*/
showAll(): void;
/**
* 获取这段 TextContent 的总高度
*/
getHeight(): number;
}
const textContentOptions = {
props: [
'breakChars',
'font',
'ignoreLineEnd',
'ignoreLineStart',
'interval',
'keepLast',
'lineHeight',
'text',
'textAlign',
'wordBreak',
'fill',
'fillStyle',
'strokeStyle',
'strokeWidth',
'stroke',
'loc',
'width',
'autoHeight'
],
emits: ['typeEnd', 'typeStart', 'updateHeight']
} satisfies SetupComponentOptions<
TextContentProps,
TextContentEmits,
keyof TextContentEmits
>;
export const TextContent = defineComponent<
TextContentProps,
TextContentEmits,
keyof TextContentEmits
>((props, { emit, expose }) => {
const loc = ref<ElementLocator>(
(props.loc?.slice() as ElementLocator) ?? []
);
if (props.width < 0) {
logger.warn(41, String(props.width));
}
const typer = new TextContentTyper(props);
let renderable: TyperRenderable[] = [];
let needUpdate = false;
const retype = () => {
if (needUpdate) return;
needUpdate = true;
if (!spriteElement.value) {
needUpdate = false;
}
renderable = [];
spriteElement.value?.requestBeforeFrame(() => {
typer.setConfig(props);
typer.setText(props.text ?? '');
typer.type();
needUpdate = false;
updateLoc();
});
};
const showAll = () => {
typer.typeAll();
};
watch(props, () => {
typer.setConfig(props);
retype();
});
const getHeight = () => {
return typer.getHeight();
};
const updateLoc = () => {
const height = getHeight();
if (props.autoHeight) {
const [x = 0, y = 0, width = 200, , ax = 0, ay = 0] = loc.value;
loc.value = [x, y, width, height, ax, ay];
}
emit('updateHeight', height);
};
expose<TextContentExpose>({ retype, showAll, getHeight });
const spriteElement = shallowRef<Sprite>();
const renderContent = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
ctx.textBaseline = 'top';
renderable.forEach(v => {
switch (v.type) {
case TextContentType.Text: {
if (v.text.length === 0) return;
ctx.fillStyle = v.fillStyle;
ctx.strokeStyle = v.strokeStyle;
ctx.font = v.font;
const text = v.text.slice(0, v.pointer);
if (props.fill ?? true) {
ctx.fillText(text, v.x, v.y);
}
if (props.stroke) {
ctx.strokeText(text, v.x, v.y);
}
break;
}
case TextContentType.Icon: {
const { renderable: r, x: dx, y: dy, width, height } = v;
const render = r.render;
const [x, y, w, h] = render[0];
const icon = r.autotile ? r.image[0] : r.image;
ctx.drawImage(icon, x, y, w, h, dx, dy, width, height);
break;
}
}
});
};
const renderFunc = (data: TyperRenderable[]) => {
renderable = data;
spriteElement.value?.update();
};
typer.setRender(renderFunc);
typer.on('typeStart', () => {
emit('typeStart');
});
typer.on('typeEnd', () => {
emit('typeEnd');
});
onMounted(retype);
return () => {
return (
<sprite
loc={loc.value}
ref={spriteElement}
render={renderContent}
></sprite>
);
};
}, textContentOptions);
export interface TextboxProps extends TextContentProps, DefaultProps {
/** 背景颜色 */
backColor?: CanvasStyle;
/** 背景 winskin */
winskin?: ImageIds;
/** 边框与文字间的距离,默认为8 */
padding?: number;
/** 标题 */
title?: string;
/** 标题字体 */
titleFont?: Font;
/** 标题填充样式 */
titleFill?: CanvasStyle;
/** 标题描边样式 */
titleStroke?: CanvasStyle;
/** 标题文字与边框间的距离,默认为4 */
titlePadding?: number;
/** 最大宽度 */
width: number;
}
export interface TextboxExpose {
/**
* 显示这个文本框
*/
show(): void;
/**
* 隐藏这个文本框
*/
hide(): void;
/**
* 重新开始打字
*/
retype(): void;
/**
* 立刻显示所有文字
*/
showAll(): void;
}
type TextboxEmits = TextContentEmits;
type TextboxSlots = SlotsType<{
default: (data: TextboxProps) => VNode[];
title: (data: TextboxProps) => VNode[];
}>;
const textboxOptions = {
props: (textContentOptions.props as (keyof TextboxProps)[]).concat([
'backColor',
'winskin',
'padding',
'titleFill',
'titleStroke',
'titleFont',
'titlePadding',
'id',
'hidden',
'title'
]),
emits: textContentOptions.emits
} satisfies SetupComponentOptions<TextboxProps, {}, string, TextboxSlots>;
let id = 0;
function getNextTextboxId() {
return `@default-textbox-${id++}`;
}
export const Textbox = defineComponent<
TextboxProps,
TextboxEmits,
keyof TextboxEmits,
TextboxSlots
>((props, { slots, expose }) => {
const contentData = shallowReactive<TextContentProps>({ width: 200 });
const data = shallowReactive<TextboxProps>({ width: 200 });
const setContentData = () => {
contentData.breakChars = props.breakChars ?? '';
contentData.font = props.font ?? new Font();
contentData.ignoreLineEnd = props.ignoreLineEnd ?? '';
contentData.ignoreLineStart = props.ignoreLineStart ?? '';
contentData.interval = props.interval ?? 0;
contentData.keepLast = props.keepLast ?? false;
contentData.lineHeight = props.lineHeight ?? 0;
contentData.text = props.text ?? '';
contentData.textAlign = props.textAlign ?? TextAlign.Left;
contentData.wordBreak = props.wordBreak ?? WordBreak.Space;
contentData.fill = props.fill ?? true;
contentData.stroke = props.stroke ?? false;
contentData.fillStyle = props.fillStyle ?? '#fff';
contentData.strokeStyle = props.strokeStyle ?? '#000';
contentData.strokeWidth = props.strokeWidth ?? 2;
contentData.loc = props.loc;
contentData.width = props.width;
};
const setTextboxData = () => {
data.backColor = props.backColor ?? '#222';
data.winskin = props.winskin;
data.padding = props.padding ?? 8;
data.titleFill = props.titleFill ?? 'gold';
data.titleStroke = props.titleStroke ?? 'transparent';
data.titleFont = props.titleFont ?? new Font('Verdana', 18);
data.titlePadding = props.titlePadding ?? 8;
data.width = props.width ?? props.loc?.[2] ?? 200;
data.height = props.height ?? props.loc?.[3] ?? 200;
data.title = props.title ?? '';
};
setContentData();
setTextboxData();
watch(props, () => {
const needUpdateTitle = data.title !== props.title;
setTextboxData();
if (needUpdateTitle) {
onSetText();
}
});
const titleElement = ref<Text>();
const content = ref<TextContentExpose>();
const hidden = ref(props.hidden);
/** 标题宽度 */
const tw = ref(data.titlePadding! * 2);
/** 标题高度 */
const th = ref(data.titlePadding! * 2);
const contentY = computed(() => {
const height = th.value;
return data.title ? height : 0;
});
const backHeight = computed(() => data.height! - contentY.value);
const contentWidth = computed(() => data.width! - data.padding! * 2);
const contentHeight = computed(
() => data.height! - data.padding! * 2 - contentY.value
);
const onSetText = () => {
nextTick(() => {
titleElement.value?.requestBeforeFrame(() => {
if (titleElement.value) {
const { width, height } = titleElement.value;
tw.value = width + data.padding! * 2;
th.value = height + data.padding! * 2;
}
});
});
};
// ----- store
/** 结束打字机 */
const storeEmits: TextboxStoreEmits = {
endType() {
content.value?.showAll();
},
hide() {
hidden.value = true;
},
show() {
hidden.value = false;
},
update(value) {
if (data.title !== value.title) {
data.title = value.title;
onSetText();
}
},
setText(text) {
if (contentData.text === text) {
content.value?.retype();
} else {
contentData.text = text;
}
}
};
const store = TextboxStore.use(
props.id ?? getNextTextboxId(),
contentData,
storeEmits
);
const onTypeStart = () => {
store.emitTypeStart();
};
const onTypeEnd = () => {
store.emitTypeEnd();
};
expose<TextboxExpose>({
show() {
hidden.value = false;
},
hide() {
hidden.value = true;
},
retype() {
content.value?.retype();
},
showAll() {
content.value?.showAll();
}
});
return () => (
<container
id={props.id}
hidden={hidden.value}
alpha={data.alpha}
loc={props.loc}
>
{data.title && (
<container zIndex={10} loc={[0, 0, tw.value, th.value]}>
{slots.title ? (
slots.title(data)
) : props.winskin ? (
<winskin
image={props.winskin}
loc={[0, 0, tw.value, th.value]}
></winskin>
) : (
<g-rect loc={[0, 0, tw.value, th.value]}></g-rect>
)}
<text
ref={titleElement}
text={data.title}
loc={[data.titlePadding, data.titlePadding]}
fillStyle={data.titleFill}
strokeStyle={data.titleStroke}
font={data.titleFont}
></text>
</container>
)}
{slots.default ? (
slots.default(data)
) : props.winskin ? (
<winskin
image={props.winskin}
loc={[0, contentY.value, data.width!, backHeight.value]}
></winskin>
) : (
<g-rect
loc={[0, contentY.value, data.width!, backHeight.value]}
fill
fillStyle={data.backColor}
></g-rect>
)}
<TextContent
{...contentData}
ref={content}
x={data.padding!}
y={contentY.value + data.padding!}
width={contentWidth.value}
height={contentHeight.value}
onTypeEnd={onTypeEnd}
onTypeStart={onTypeStart}
></TextContent>
</container>
);
}, textboxOptions);
interface TextboxStoreEmits {
endType: () => void;
hide: () => void;
show: () => void;
update: (value: TextboxProps) => void;
setText: (text: string) => void;
}
interface TextboxStoreEvent {
update: [value: TextboxProps];
show: [];
hide: [];
typeStart: [];
typeEnd: [];
}
export class TextboxStore extends EventEmitter<TextboxStoreEvent> {
static list: Map<string, TextboxStore> = new Map();
typing: boolean = false;
private constructor(
private readonly data: TextboxProps,
private readonly emits: TextboxStoreEmits
) {
super();
}
/**
* 开始打字,由组件调用,而非组件外调用
*/
emitTypeStart() {
this.typing = true;
this.emit('typeStart');
}
/**
* 结束打字,由组件调用,而非组件外调用
*/
emitTypeEnd() {
this.typing = false;
this.emit('typeEnd');
}
/**
* 结束打字机的打字
*/
endType() {
this.emits.endType();
}
/**
* 修改渲染数据
*/
modify(data: Partial<TextboxProps>) {
for (const [key, value] of Object.entries(data)) {
// @ts-expect-error 无法推导
if (!isNil(value)) this.data[key] = value;
}
this.emits.update(this.data);
this.emit('update', this.data);
}
/**
* 设置显示的文本
* @param text 要显示的文本
*/
setText(text: string) {
this.emits.setText(text);
}
/**
* 显示文本框
*/
show() {
this.emits.show();
}
/**
* 隐藏文本框
*/
hide() {
this.emits.hide();
}
/**
* 获取文本框
* @param id 文本框id
*/
static get(id: string): TextboxStore | undefined {
return this.list.get(id);
}
/**
* 在当前作用域下生成文本框控制器
* @param id 文本框id
* @param props 文本框渲染数据
*/
static use(id: string, props: TextboxProps, emits: TextboxStoreEmits) {
const store = new TextboxStore(props, emits);
if (this.list.has(id)) {
logger.warn(42, id);
}
this.list.set(id, store);
onUnmounted(() => {
this.list.delete(id);
});
return store;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,169 @@
import { DefaultProps, ElementLocator, Font, texture } from '@motajs/render';
import { logger } from '@motajs/common';
import { computed, defineComponent, onUnmounted, ref } from 'vue';
import { SetupComponentOptions } from './types';
import { transitioned } from '../use';
import { hyper } from 'mutate-animate';
import { debounce } from 'lodash-es';
export interface TipProps extends DefaultProps {
loc: ElementLocator;
pad?: [number, number];
corner?: number;
id?: string;
}
export interface TipExpose {
/**
* 显示提示文本
* @param text 提示文字
* @param icon 显示的图标,不填则不显示
*/
drawTip(text: string, icon?: AllIds | AllNumbers): void;
}
const tipProps = {
props: ['loc', 'pad', 'corner', 'id']
} satisfies SetupComponentOptions<TipProps>;
let id = 0;
function getNextTipId() {
return `@default-tip-${id++}`;
}
export const Tip = defineComponent<TipProps>((props, { expose }) => {
const iconNum = ref<AllNumbers>(0);
const text = ref<string>('');
const textWidth = ref(0);
const font = new Font('normal');
const alpha = transitioned(0, 500, hyper('sin', 'in-out'))!;
const pad = computed(() => props.pad ?? [4, 4]);
const locHeight = computed(() => props.loc[3] ?? 200);
const hidden = computed(() => alpha.ref.value === 0);
const showIcon = computed(() => iconNum.value !== 0);
const iconSize = computed<[number, number]>(() => {
const renderable = texture.getRenderable(iconNum.value);
if (!renderable) return [1, 1];
const [, , width, height] = renderable.render[0];
return [width, height];
});
const iconLoc = computed<ElementLocator>(() => {
const [width, height] = iconSize.value;
const aspect = width / height;
const realHeight = locHeight.value - pad.value[1] * 2;
const realWidth = realHeight * aspect;
return [pad.value[0], pad.value[1], realWidth, realHeight];
});
const textLoc = computed<ElementLocator>(() => {
if (showIcon.value) {
const [, , width] = iconLoc.value;
const x = width! + pad.value[0] + pad.value[1];
return [x, locHeight.value / 2, void 0, void 0, 0, 0.5];
} else {
return [pad.value[0], locHeight.value / 2, void 0, void 0, 0, 0.5];
}
});
const containerLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , height = 200] = props.loc;
const iconWidth = iconLoc.value[2] ?? 32;
if (showIcon.value) {
const width =
textWidth.value + iconWidth + pad.value[0] * 2 + pad.value[1];
return [x, y, width, height];
} else {
const width = textWidth.value + pad.value[0] * 2;
return [x, y, width, height];
}
});
const rectLoc = computed<ElementLocator>(() => {
const [, , width = 200, height = 200] = containerLoc.value;
return [1, 1, width - 2, height - 2];
});
const hide = debounce(() => {
alpha.set(0);
}, 3000);
const drawTip = (tipText: string, iconId: AllIds | AllNumbers = 0) => {
if (typeof iconId === 'string') {
const num = texture.idNumberMap[iconId];
iconNum.value = num;
} else {
iconNum.value = iconId;
}
text.value = core.replaceText(tipText);
alpha.set(0, 0);
alpha.set(1);
hide();
};
const onSetText = (_: string, width: number) => {
textWidth.value = width;
};
const ex: TipExpose = { drawTip };
TipStore.use(props.id ?? getNextTipId(), ex);
expose<TipExpose>(ex);
return () => (
<container
loc={containerLoc.value}
alpha={alpha.ref.value}
hidden={hidden.value}
noevent
>
<g-rectr
loc={rectLoc.value}
circle={[props.corner ?? 4]}
fill
fillStyle="rgba(40,40,40,0.8)"
/>
<icon
hidden={!showIcon.value}
icon={iconNum.value}
loc={iconLoc.value}
/>
<text
loc={textLoc.value}
text={text.value}
onSetText={onSetText}
font={font}
/>
</container>
);
}, tipProps);
export class TipStore {
static list: Map<string, TipStore> = new Map();
private constructor(private readonly data: TipExpose) {}
/**
* 显示提示文本
* @param text 提示文字
* @param icon 显示的图标,不填则不显示
*/
drawTip(text: string, icon: AllIds | AllNumbers = 0) {
this.data.drawTip(text, icon);
}
static get(id: string) {
return TipStore.list.get(id);
}
static use(id: string, data: TipExpose) {
const store = new TipStore(data);
if (this.list.has(id)) {
logger.warn(60, id);
}
this.list.set(id, store);
onUnmounted(() => {
this.list.delete(id);
});
return store;
}
}
@@ -0,0 +1,12 @@
import { ComponentOptions, EmitsOptions, SlotsType } from 'vue';
export type SetupComponentOptions<
Props extends Record<string, any>,
E extends EmitsOptions = {},
EE extends string = string,
S extends SlotsType = {}
> = Pick<ComponentOptions, 'name' | 'inheritAttrs'> & {
props?: (keyof Props)[];
emits?: E | EE[];
slots?: S;
};
@@ -0,0 +1,43 @@
import { MotaRenderer, createApp } from '@motajs/render';
import { defineComponent } from 'vue';
import { UIController } from '@motajs/system-ui';
import { mainSceneUI } from './ui/main';
import { MAIN_HEIGHT, MAIN_WIDTH } from './shared';
import { TextboxStore } from './components';
export function create() {
const main = new MotaRenderer();
main.size(MAIN_WIDTH, MAIN_HEIGHT);
const App = defineComponent(_props => {
const ui = new UIController('root-ui');
ui.open(mainSceneUI, {});
return () => (
<container width={MAIN_WIDTH} height={MAIN_HEIGHT}>
{ui.render()}
</container>
);
});
main.hide();
createApp(App).mount(main);
Mota.require('var', 'hook').on('reset', () => {
main.show();
});
Mota.require('var', 'hook').on('restart', () => {
main.hide();
});
console.log(main);
}
Mota.register('module', 'MainUI', {
TextboxStore
});
export * from './components';
export * from './ui';
export * from './use';
@@ -0,0 +1,10 @@
export const STATUS_BAR_WIDTH = 180;
export const STATUS_BAR_HEIGHT = 480;
export const ENABLE_RIGHT_STATUS_BAR = true;
export const MAP_WIDTH = 480;
export const MAP_HEIGHT = 480;
export const MAIN_WIDTH = 480 + 180 * 2;
export const MAIN_HEIGHT = 480;
@@ -0,0 +1,2 @@
export * from './main';
export * from './statusBar';
@@ -0,0 +1,238 @@
import { LayerShadowExtends } from '@/core/fx/shadow';
import {
ILayerGroupRenderExtends,
FloorDamageExtends,
LayerGroupAnimate,
FloorViewport,
ILayerRenderExtends,
HeroRenderer,
LayerDoorAnimate,
Props,
LayerGroup,
Font
} from '@motajs/render';
import { WeatherController } from '@/module/weather';
import { FloorChange } from '@/plugin/fallback';
import { LayerGroupFilter } from '@/plugin/fx/gameCanvas';
import { LayerGroupHalo } from '@/plugin/fx/halo';
import { FloorItemDetail } from '@/plugin/fx/itemDetail';
import { PopText } from '@/plugin/fx/pop';
import { LayerGroupPortal } from '@/plugin/fx/portal';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { Textbox, Tip } from '../components';
import { GameUI, UIController } from '@motajs/system-ui';
import {
MAIN_HEIGHT,
MAIN_WIDTH,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../shared';
import {
ILeftHeroStatus,
IRightHeroStatus,
LeftStatusBar,
RightStatusBar
} from './statusBar';
import { onLoaded } from '../use';
import { ReplayingStatus } from './toolbar';
const MainScene = defineComponent(() => {
const layerGroupExtends: ILayerGroupRenderExtends[] = [
new FloorDamageExtends(),
new FloorItemDetail(),
new LayerGroupFilter(),
new LayerGroupPortal(),
new LayerGroupHalo(),
new LayerGroupAnimate(),
new FloorViewport()
];
const eventExtends: ILayerRenderExtends[] = [
new HeroRenderer(),
new LayerDoorAnimate(),
new LayerShadowExtends()
];
const mapDrawProps: Props<'container'> = {
width: core._PX_,
height: core._PY_
};
const mainTextboxProps: Props<typeof Textbox> = {
text: '',
hidden: true,
loc: [0, 330, 480, 150],
zIndex: 30,
fillStyle: '#fff',
titleFill: 'gold',
font: new Font('normal'),
titleFont: new Font('normal', 20, 'px', 700),
winskin: 'winskin2.png',
interval: 100,
lineHeight: 4,
width: 480
};
const map = ref<LayerGroup>();
const hideStatus = ref(false);
const weather = new WeatherController('main');
onMounted(() => {
weather.bind(map.value);
});
const leftStatus: ILeftHeroStatus = reactive({
hp: 0,
atk: 0,
def: 0,
mdef: 0,
money: 0,
exp: 0,
yellowKey: 0,
blueKey: 0,
redKey: 0,
floor: 'MT0',
lv: '',
regen: 0,
exAtk: 0,
magicDef: 0
});
const replayStatus: ReplayingStatus = reactive({
playing: false,
speed: 1,
played: 0,
total: 0
});
const rightStatus: IRightHeroStatus = reactive({
autoSkill: false,
skillName: '',
skillDesc: '',
jumpCount: 0,
springCount: 0,
floor: 'MT0',
replaying: false,
replayStatus,
night: 0
});
const { getHeroStatusOn } = Mota.requireAll('fn');
const updateStatus = () => {
if (!core.status || !core.status.hero || !core.status.floorId) return;
hideStatus.value = core.getFlag('hideStatusBar', false);
const hero = core.status.hero;
const floor = core.status.floorId;
leftStatus.atk = getHeroStatusOn('atk');
leftStatus.hp = getHeroStatusOn('hp');
leftStatus.def = getHeroStatusOn('def');
leftStatus.mdef = getHeroStatusOn('mdef');
leftStatus.money = getHeroStatusOn('money');
leftStatus.exp = core.getNextLvUpNeed() ?? 0;
leftStatus.yellowKey = core.itemCount('yellowKey');
leftStatus.blueKey = core.itemCount('blueKey');
leftStatus.redKey = core.itemCount('redKey');
leftStatus.floor = core.status.floorId;
leftStatus.lv = core.getLvName(hero.lv);
leftStatus.regen = getHeroStatusOn('hpmax');
leftStatus.exAtk = getHeroStatusOn('mana');
leftStatus.magicDef = getHeroStatusOn('magicDef');
const { HeroSkill, NightSpecial } = Mota.require('module', 'Mechanism');
rightStatus.autoSkill = HeroSkill.getAutoSkill();
rightStatus.skillName = HeroSkill.getSkillName();
rightStatus.skillDesc = HeroSkill.getSkillDesc();
rightStatus.night = NightSpecial.getNight(floor);
rightStatus.floor = floor;
rightStatus.replaying = core.isReplaying();
const { pausing, speed, toReplay, totalList } = core.status.replay;
replayStatus.playing = !pausing;
replayStatus.speed = speed;
replayStatus.played = totalList.length - toReplay.length;
replayStatus.total = totalList.length;
if (HeroSkill.learnedSkill(HeroSkill.Jump)) {
if (Mota.Plugin.require('skill_g').jumpIgnoreFloor.has(floor)) {
rightStatus.jumpCount = -2;
} else {
rightStatus.jumpCount = 3 - (flags[`jump_${floor}`] ?? 0);
}
} else {
rightStatus.jumpCount = -1;
}
if (core.hasFlag('spring')) {
rightStatus.springCount = 50 - (flags.springCount ?? 0);
} else {
rightStatus.springCount = -1;
}
};
const loaded = ref(false);
onLoaded(() => {
loaded.value = true;
});
Mota.require('var', 'hook').on('statusBarUpdate', updateStatus);
return () => (
<container id="main-scene" width={MAIN_WIDTH} height={MAIN_HEIGHT}>
{loaded.value && (
<LeftStatusBar
loc={[0, 0, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT]}
status={leftStatus}
hidden={hideStatus.value}
></LeftStatusBar>
)}
<g-line line={[180, 0, 180, 480]} lineWidth={1} />
<container id="map-draw" {...mapDrawProps} x={180} zIndex={10}>
<layer-group id="layer-main" ex={layerGroupExtends} ref={map}>
<layer layer="bg" zIndex={10}></layer>
<layer layer="bg2" zIndex={20}></layer>
<layer layer="event" zIndex={30} ex={eventExtends}></layer>
<layer layer="fg" zIndex={40}></layer>
<layer layer="fg2" zIndex={50}></layer>
<PopText id="pop-main" zIndex={80}></PopText>
</layer-group>
<Textbox id="main-textbox" {...mainTextboxProps}></Textbox>
<FloorChange id="floor-change" zIndex={50}></FloorChange>
<Tip
id="main-tip"
zIndex={80}
loc={[8, 8, 200, 32]}
pad={[12, 6]}
corner={16}
/>
</container>
<g-line line={[180 + 480, 0, 180 + 480, 480]} lineWidth={1} />
{loaded.value && (
<RightStatusBar
loc={[480 + 180, 0, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT]}
status={rightStatus}
hidden={hideStatus.value}
></RightStatusBar>
)}
<container
loc={[0, 0, MAIN_WIDTH, MAIN_HEIGHT]}
hidden={mainUIController.showBack.value}
>
{mainUIController.render()}
</container>
<g-rect
loc={[0, 0, MAIN_WIDTH, MAIN_HEIGHT]}
hidden={hideStatus.value}
zIndex={100}
stroke
noevent
></g-rect>
<g-line
line={[180, 0, 480 + 180, 0]}
hidden={!hideStatus.value}
zIndex={100}
/>
<g-line
line={[180, 480, 480 + 180, 480]}
hidden={!hideStatus.value}
zIndex={100}
/>
</container>
);
});
export const mainSceneUI = new GameUI('main-scene', MainScene);
export const mainUIController = new UIController('main-ui');
@@ -0,0 +1,579 @@
import { ElementLocator } from '@motajs/render';
import { GameUI, UIComponentProps } from '@motajs/system-ui';
import { defineComponent } from 'vue';
import {
ChoiceItem,
ChoiceKey,
Choices,
ChoicesProps,
getConfirm,
SetupComponentOptions,
waitbox
} from '../components';
import { mainUi } from '@motajs/legacy-ui';
import { gameKey } from '@motajs/system-action';
import { generateKeyboardEvent } from '@motajs/system-action';
import { getVitualKeyOnce } from '@motajs/legacy-ui';
import { getAllSavesData, getSaveData } from '@/module/utils';
export interface SettingsProps extends Partial<ChoicesProps>, UIComponentProps {
loc: ElementLocator;
}
const settingsProps = {
props: ['loc', 'controller', 'instance']
} satisfies SetupComponentOptions<SettingsProps>;
const enum MainChoice {
SystemSetting,
VirtualKey,
ViewMap,
/** @see {@link ReplaySettings} */
Replay,
/** @see {@link SyncSave} */
SyncSave,
/** @see {@link GameInfo} */
GameInfo,
Restart,
Back
}
export const MainSettings = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[MainChoice.SystemSetting, '系统设置'],
[MainChoice.VirtualKey, '虚拟键盘'],
[MainChoice.ViewMap, '浏览地图'],
[MainChoice.Replay, '录像回放'],
[MainChoice.SyncSave, '同步存档'],
[MainChoice.GameInfo, '游戏信息'],
[MainChoice.Restart, '返回标题'],
[MainChoice.Back, '返回游戏']
];
const choose = (key: ChoiceKey) => {
switch (key) {
case MainChoice.SystemSetting: {
mainUi.open('settings');
break;
}
case MainChoice.VirtualKey: {
getVitualKeyOnce().then(value => {
gameKey.emitKey(
value.key,
value.assist,
'up',
generateKeyboardEvent(value.key, value.assist)
);
});
break;
}
case MainChoice.ViewMap: {
// todo
break;
}
case MainChoice.Replay: {
props.controller.open(ReplaySettingsUI, { loc: props.loc });
break;
}
case MainChoice.SyncSave: {
props.controller.open(SyncSaveUI, { loc: props.loc });
break;
}
case MainChoice.GameInfo: {
props.controller.open(GameInfoUI, { loc: props.loc });
break;
}
case MainChoice.Restart: {
props.controller.closeAll();
core.restart();
break;
}
case MainChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
choices={choices}
width={240}
onChoose={choose}
/>
);
}, settingsProps);
const enum ReplayChoice {
Start,
StartFromSave,
ResumeReplay,
ReplayRest,
ChooseReplay,
Download,
Back
}
export const ReplaySettings = defineComponent<SettingsProps>(props => {
const choice: ChoiceItem[] = [
[ReplayChoice.Start, '从头回放录像'],
[ReplayChoice.StartFromSave, '从存档开始回放'],
[ReplayChoice.ResumeReplay, '接续播放剩余录像'],
[ReplayChoice.ReplayRest, '播放存档剩余录像'],
[ReplayChoice.ChooseReplay, '选择录像文件'],
[ReplayChoice.Download, '下载当前录像'],
[ReplayChoice.Back, '返回游戏']
];
const choose = (key: ChoiceKey) => {
switch (key) {
case ReplayChoice.Start: {
props.controller.closeAll();
core.ui.closePanel();
const route = core.status.route.slice();
const seed = core.getFlag<number>('__seed__');
core.startGame(core.status.hard, seed, route);
break;
}
case ReplayChoice.StartFromSave: {
// todo
break;
}
case ReplayChoice.ResumeReplay: {
// todo
break;
}
case ReplayChoice.ReplayRest: {
// todo
break;
}
case ReplayChoice.ChooseReplay: {
props.controller.closeAll();
core.chooseReplayFile();
break;
}
case ReplayChoice.Download: {
core.download(
core.firstData.name + '_' + core.formatDate2() + '.h5route',
// @ts-expect-error 暂时无法推导
LZString.compressToBase64(
JSON.stringify({
name: core.firstData.name,
hard: core.status.hard,
seed: core.getFlag('__seed__'),
route: core.encodeRoute(core.status.route)
})
)
);
break;
}
case ReplayChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
choices={choice}
width={240}
onChoose={choose}
/>
);
}, settingsProps);
const enum GameInfoChoice {
Statistics,
Project,
Tower,
Help,
Download,
Back
}
export const GameInfo = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[GameInfoChoice.Statistics, '数据统计'],
[GameInfoChoice.Project, '查看工程'],
[GameInfoChoice.Tower, '游戏主页'],
[GameInfoChoice.Help, '操作帮助'],
[GameInfoChoice.Download, '下载离线版本'],
[GameInfoChoice.Back, '返回主菜单']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case GameInfoChoice.Statistics: {
// todo
break;
}
case GameInfoChoice.Project: {
if (core.platform.isPC) window.open('editor.html', '_blank');
else {
const confirm = await getConfirm(
props.controller,
'即将离开本游戏,跳转至工程页面,确认跳转?',
props.loc,
240
);
if (confirm) {
window.location.href = 'editor-mobile.html';
}
}
break;
}
case GameInfoChoice.Tower: {
const name = core.firstData.name;
const href = `/tower/?name=${name}`;
if (core.platform.isPC) {
window.open(href, '_blank');
} else {
const confirm = await getConfirm(
props.controller,
'即将离开本游戏,跳转至评论页面,确认跳转?',
props.loc,
240
);
if (confirm) {
window.location.href = href;
}
}
break;
}
case GameInfoChoice.Download: {
const name = core.firstData.name;
const href = `/games/${name}/${name}.zip`;
if (core.platform.isPC) window.open(href);
else window.location.href = href;
break;
}
case GameInfoChoice.Help: {
// todo
break;
}
case GameInfoChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
choices={choices}
width={240}
onChoose={choose}
/>
);
});
const enum SyncSaveChoice {
// ----- 主菜单
ToServer,
FromServer,
ToLocal,
FromLocal,
ClearLocal,
Back,
// ----- 子菜单
AllSaves,
NowSave
}
export const SyncSave = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.ToServer, '同步存档至服务器'],
[SyncSaveChoice.FromServer, '从服务器加载存档'],
[SyncSaveChoice.ToLocal, '存档至本地文件'],
[SyncSaveChoice.FromLocal, '存本地文件读档'],
[SyncSaveChoice.ClearLocal, '清空本地存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.ToServer: {
props.controller.open(SyncSaveSelectUI, { loc: props.loc });
break;
}
case SyncSaveChoice.FromServer: {
// todo
break;
}
case SyncSaveChoice.ToLocal: {
props.controller.open(DownloadSaveSelectUI, { loc: props.loc });
break;
}
case SyncSaveChoice.FromLocal: {
// todo
break;
}
case SyncSaveChoice.ClearLocal: {
props.controller.open(ClearSaveSelectUI, { loc: props.loc });
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
export const SyncSaveSelect = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.AllSaves, '同步全部存档'],
[SyncSaveChoice.NowSave, '同步当前存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.AllSaves: {
core.playSound('confirm.opus');
const confirm = await getConfirm(
props.controller,
'你确定要同步全部存档么?这可能在存档较多的时候比较慢。',
props.loc,
240
);
if (confirm) {
core.syncSave('all');
}
break;
}
case SyncSaveChoice.NowSave: {
core.playSound('confirm.opus');
const confirm = await getConfirm(
props.controller,
'确定要同步当前存档吗?',
props.loc,
240
);
if (confirm) {
core.syncSave();
}
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
export const DownloadSaveSelect = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.AllSaves, '下载全部存档'],
[SyncSaveChoice.NowSave, '下载当前存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.AllSaves: {
const confirm = await getConfirm(
props.controller,
'确认要下载所有存档吗?',
props.loc,
240
);
if (confirm) {
const data = await waitbox(
props.controller,
props.loc,
240,
getAllSavesData(),
{ text: '请等待处理完毕' }
);
core.download(
`${core.firstData.name}_${core.formatDate2(new Date())}.h5save`,
data
);
}
break;
}
case SyncSaveChoice.NowSave: {
const confirm = await getConfirm(
props.controller,
'确认要下载当前存档吗?',
props.loc,
240
);
if (confirm) {
const data = await getSaveData(core.saves.saveIndex);
core.download(
`${core.firstData.name}_${core.formatDate2(new Date())}.h5save`,
data
);
}
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
export const ClearSaveSelect = defineComponent<SettingsProps>(props => {
const choices: ChoiceItem[] = [
[SyncSaveChoice.AllSaves, '清空全部塔存档'],
[SyncSaveChoice.NowSave, '清空当前塔存档'],
[SyncSaveChoice.Back, '返回上一级']
];
const choose = async (key: ChoiceKey) => {
switch (key) {
case SyncSaveChoice.AllSaves: {
const confirm = await getConfirm(
props.controller,
'你确定要清除【全部游戏】的所有本地存档?此行为不可逆!!!',
props.loc,
240
);
if (confirm) {
await waitbox(
props.controller,
props.loc,
240,
new Promise<void>(res => {
core.clearLocalForage(() => {
core.saves.ids = {};
core.saves.autosave.data = null;
core.saves.autosave.updated = false;
core.saves.autosave.now = 0;
// @ts-expect-error 沙比样板
core.saves.cache = {};
core.saves.saveIndex = 1;
core.saves.favorite = [];
core.saves.favoriteName = {};
// @ts-expect-error 沙比样板
core.control._updateFavoriteSaves();
core.removeLocalStorage('saveIndex');
res();
});
}),
{ text: '正在情况,请稍后...' }
);
await getConfirm(
props.controller,
'所有塔的存档已经全部清空',
props.loc,
240
);
}
break;
}
case SyncSaveChoice.NowSave: {
const confirm = await getConfirm(
props.controller,
'你确定要清除【当前游戏】的所有本地存档?此行为不可逆!!!',
props.loc,
240
);
if (confirm) {
await waitbox(
props.controller,
props.loc,
240,
new Promise<void>(res => {
Object.keys(core.saves.ids).forEach(function (v) {
core.removeLocalForage('save' + v);
});
core.removeLocalForage('autoSave', () => {
core.saves.ids = {};
core.saves.autosave.data = null;
core.saves.autosave.updated = false;
core.saves.autosave.now = 0;
core.ui.closePanel();
core.saves.saveIndex = 1;
core.saves.favorite = [];
core.saves.favoriteName = {};
// @ts-expect-error 沙比样板
core.control._updateFavoriteSaves();
core.removeLocalStorage('saveIndex');
res();
});
}),
{ text: '正在情况,请稍后...' }
);
await getConfirm(
props.controller,
'当前塔的存档已被清空',
props.loc,
240
);
}
break;
}
case SyncSaveChoice.Back: {
props.controller.close(props.instance);
break;
}
}
};
return () => (
<Choices
loc={props.loc}
width={240}
choices={choices}
onChoose={choose}
/>
);
});
/** @see {@link MainSettings} */
export const MainSettingsUI = new GameUI('main-settings', MainSettings);
/** @see {@link ReplaySettings} */
export const ReplaySettingsUI = new GameUI('replay-settings', ReplaySettings);
/** @see {@link GameInfo} */
export const GameInfoUI = new GameUI('game-info', GameInfo);
/** @see {@link SyncSave} */
export const SyncSaveUI = new GameUI('sync-save', SyncSave);
/** @see {@link SyncSaveSelect} */
export const SyncSaveSelectUI = new GameUI('sync-save-select', SyncSaveSelect);
/** @see {@link DownloadSaveSelect} */
export const DownloadSaveSelectUI = new GameUI(
'download-save-select',
DownloadSaveSelect
);
/** @see {@link ClearSaveSelect} */
export const ClearSaveSelectUI = new GameUI(
'clear-save-select',
ClearSaveSelect
);
@@ -0,0 +1,419 @@
import { GameUI, UIComponentProps } from '@motajs/system-ui';
import { computed, defineComponent, ref, watch } from 'vue';
import { SetupComponentOptions, TextContent } from '../components';
import {
DefaultProps,
ElementLocator,
Sprite,
Font,
MotaOffscreenCanvas2D
} from '@motajs/render';
import { transitionedColor } from '../use';
import { linear } from 'mutate-animate';
import { Scroll } from '../components/scroll';
import { getArea, MinimapDrawer } from '@motajs/legacy-ui';
import {
NumpadToolbar,
PlayingToolbar,
ReplayingStatus,
ReplayingToolbar
} from './toolbar';
export interface ILeftHeroStatus {
hp: number;
atk: number;
def: number;
mdef: number;
money: number;
exp: number;
yellowKey: number;
blueKey: number;
redKey: number;
floor: FloorIds;
lv: string;
/** 生命回复 */
regen: number;
/** 额外攻击 */
exAtk: number;
/** 魔法防御 */
magicDef: number;
}
interface StatusBarProps<T> extends DefaultProps, UIComponentProps {
loc: ElementLocator;
status: T;
hidden: boolean;
}
const statusBarProps = {
props: ['loc', 'status', 'hidden']
} satisfies SetupComponentOptions<StatusBarProps<unknown>>;
export const LeftStatusBar = defineComponent<StatusBarProps<ILeftHeroStatus>>(
p => {
const hpIcon = core.material.images.images['hp.png'];
const atkIcon = core.material.images.images['atk.png'];
const defIcon = core.material.images.images['def.png'];
const mdefIcon = core.material.images.images['IQ.png'];
const moneyIcon = core.material.images.images['money.png'];
const expIcon = core.material.images.images['exp.png'];
const s = p.status;
const f = core.formatBigNumber;
const floorName = computed(() => core.floors[s.floor]?.title ?? '');
const key = (num: number) => {
return num.toString().padStart(2, '0');
};
const font1 = new Font('normal', 18);
const font2 = new Font('normal', 18, 'px', 700);
const font3 = new Font('normal', 14, 'px', 700);
const iconLoc = (n: number): ElementLocator => {
return [16, 76 + 44 * n, 32, 32];
};
const textLoc = (n: number): ElementLocator => {
return [60, 92 + 44 * n, void 0, void 0, 0, 0.5];
};
const central = (y: number): ElementLocator => {
const width = p.loc[2] ?? 200;
return [width / 2, y, void 0, void 0, 0.5, 0.5];
};
const right = (y: number): ElementLocator => {
const width = p.loc[2] ?? 200;
return [width - 16, y, void 0, void 0, 1, 0.5];
};
const keyCount = 3;
const keyY = 92 + 44 * 6;
const keyLoc = (n: number): ElementLocator => {
const width = p.loc[2] ?? 200;
const per = width / (keyCount + 1);
return [per * (n + 1), keyY, void 0, void 0, 0.5, 0.5];
};
return () => {
return (
<container loc={p.loc} hidden={p.hidden}>
<text
text={floorName.value}
loc={central(24)}
font={font1}
cursor="pointer"
></text>
<text text={s.lv} loc={central(54)} font={font1}></text>
<image image={hpIcon} loc={iconLoc(0)}></image>
<text text={f(s.hp)} loc={textLoc(0)} font={font1}></text>
<text
text={`+${f(s.regen)}/t`}
loc={right(110)}
font={font3}
fillStyle="#a7ffa7"
></text>
<image image={atkIcon} loc={iconLoc(1)}></image>
<text text={f(s.atk)} loc={textLoc(1)} font={font1}></text>
<text
text={`+${f(s.exAtk)}`}
loc={right(154)}
font={font3}
fillStyle="#ffd3d3"
></text>
<image image={defIcon} loc={iconLoc(2)}></image>
<text text={f(s.def)} loc={textLoc(2)} font={font1}></text>
{s.magicDef > 0 && (
<text
text={`+${f(s.magicDef)}`}
loc={right(198)}
font={font3}
fillStyle="#b0bdff"
></text>
)}
<image image={mdefIcon} loc={iconLoc(3)}></image>
<text text={f(s.mdef)} loc={textLoc(3)} font={font1}></text>
<image image={moneyIcon} loc={iconLoc(4)}></image>
<text text={f(s.money)} loc={textLoc(4)} font={font1} />
<image image={expIcon} loc={iconLoc(5)}></image>
<text text={f(s.exp)} loc={textLoc(5)} font={font1}></text>
<text
text={key(s.yellowKey)}
loc={keyLoc(0)}
font={font2}
fillStyle="#fca"
></text>
<text
text={key(s.blueKey)}
loc={keyLoc(1)}
font={font2}
fillStyle="#aad"
></text>
<text
text={key(s.redKey)}
loc={keyLoc(2)}
font={font2}
fillStyle="#f88"
></text>
<text
text="技能树"
loc={central(396)}
font={font1}
cursor="pointer"
></text>
<text
text="查看技能"
loc={central(428)}
font={font1}
cursor="pointer"
></text>
</container>
);
};
},
statusBarProps
);
interface RightStatusBarMisc {
name: string;
value: string;
nameColor: string;
valueColor: string;
}
export interface IRightHeroStatus {
/** 自动切换技能 */
autoSkill: boolean;
/** 当前开启的技能 */
skillName: string;
/** 技能描述 */
skillDesc: string;
/** 跳跃剩余次数,-1 表示未开启,-2表示当前楼层不能跳 */
jumpCount: number;
/** 治愈之泉剩余次数,-1 表示未开启 */
springCount: number;
/** 当前楼层 */
floor: FloorIds;
/** 是否正在录像播放 */
replaying: boolean;
/** 录像播放状态 */
replayStatus: ReplayingStatus;
/** 极昼永夜 */
night: number;
}
export const RightStatusBar = defineComponent<StatusBarProps<IRightHeroStatus>>(
p => {
const font1 = new Font('normal', 18);
const font2 = new Font('normal', 16);
const minimap = ref<Sprite>();
const inNumpad = ref(false);
const onNumpad = () => {
inNumpad.value = !inNumpad.value;
};
const s = p.status;
const skill = computed(() =>
s.autoSkill ? '已开启自动切换' : s.skillName
);
const skillDesc = computed(() =>
s.autoSkill ? '自动切换技能时,会自动选择最优技能' : s.skillDesc
);
const skillColor = transitionedColor('#284', 200, linear())!;
watch(
() => s.autoSkill,
value => {
skillColor.set(value ? '#284' : '#824');
}
);
const miscData = computed<RightStatusBarMisc[]>(() => {
const data: RightStatusBarMisc[] = [];
if (s.jumpCount !== -1) {
const text =
s.jumpCount === -2 ? '不可跳跃' : s.jumpCount.toString();
data.push({
name: '跳跃剩余',
nameColor: '#fff',
value: text,
valueColor: '#fff'
});
}
if (s.springCount >= 0) {
data.push({
name: '治愈之泉',
nameColor: '#a7ffa7',
value: s.springCount.toString(),
valueColor: '#a7ffa7'
});
}
if (s.night !== 0) {
const text = s.night.toString();
data.push({
name: '极昼永夜',
nameColor: '#a3f8ff',
value: s.night > 0 ? '+' + text : text,
valueColor: s.night > 0 ? '#a7ffa7' : '#ffa7a7'
});
}
return data;
});
const central = (y: number): ElementLocator => {
const width = p.loc[2] ?? 200;
return [width / 2, y, void 0, void 0, 0.5, 0.5];
};
const middle = (x: number, y: number): ElementLocator => {
return [x, y, void 0, void 0, 0, 0.5];
};
const changeAutoSkill = () => {
const { HeroSkill } = Mota.require('module', 'Mechanism');
const auto = !s.autoSkill;
HeroSkill.setAutoSkill(auto);
core.status.route.push(`set:autoSkill:${auto}`);
core.updateStatusBar();
};
const area = getArea();
const minimapDrawer = new MinimapDrawer(
document.createElement('canvas')
);
minimapDrawer.noBorder = true;
minimapDrawer.scale = 4;
minimapDrawer.showInfo = true;
let linked = false;
const drawMinimap = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
ctx.save();
ctx.scale(
1 / core.domStyle.scale / devicePixelRatio,
1 / core.domStyle.scale / devicePixelRatio
);
if (!linked) {
minimapDrawer.link(canvas.canvas);
linked = true;
}
if (minimapDrawer.nowFloor !== s.floor) {
minimapDrawer.drawedThumbnail = {};
} else {
minimapDrawer.drawToTarget();
ctx.restore();
return;
}
minimapDrawer.nowFloor = s.floor;
minimapDrawer.nowArea =
Object.keys(area).find(v =>
area[v].includes(core.status.floorId)
) ?? '';
minimapDrawer.locateMap(minimapDrawer.nowFloor);
minimapDrawer.drawMap();
ctx.restore();
};
watch(
() => s.floor,
() => {
minimap.value?.update();
}
);
return () => {
return (
<container loc={p.loc} hidden={p.hidden}>
<g-rectr
loc={[10, 10, 160, 24]}
circle={[6]}
fillStyle={skillColor.ref.value}
onClick={changeAutoSkill}
cursor="pointer"
></g-rectr>
<text
loc={central(22)}
text={skill.value}
font={font1}
onClick={changeAutoSkill}
cursor="pointer"
/>
<TextContent
loc={[10, 42, 160, 60]}
text={skillDesc.value}
font={new Font('normal', 14)}
width={160}
lineHeight={4}
></TextContent>
<g-line
line={[0, 107, 180, 107]}
strokeStyle="#888"
lineWidth={1}
zIndex={-20}
></g-line>
<Scroll loc={[0, 107, 180, 100]}>
{miscData.value
.map((v, i) => {
return [
<text
text={v.name}
loc={middle(10, 16 + i * 22)}
fillStyle={v.nameColor}
font={font2}
></text>,
<text
text={v.value}
loc={middle(100, 16 + i * 22)}
fillStyle={v.valueColor}
font={font2}
></text>
];
})
.flat()}
</Scroll>
<g-line
line={[0, 207, 180, 207]}
strokeStyle="#888"
lineWidth={1}
zIndex={-20}
></g-line>
<sprite
ref={minimap}
loc={[10, 207, 160, 160]}
render={drawMinimap}
></sprite>
<g-line
line={[0, 367, 180, 367]}
strokeStyle="#888"
lineWidth={1}
zIndex={-20}
></g-line>
{inNumpad.value ? (
<NumpadToolbar
loc={[0, 367, 180, 113]}
onNumpad={onNumpad}
/>
) : s.replaying ? (
<ReplayingToolbar
loc={[0, 367, 180, 113]}
status={s.replayStatus}
/>
) : (
<PlayingToolbar
loc={[0, 367, 180, 113]}
onNumpad={onNumpad}
/>
)}
</container>
);
};
},
statusBarProps
);
export const leftStatusBarUI = new GameUI('left-status-bar', LeftStatusBar);
export const rightStatusBarUI = new GameUI('right-status-bar', RightStatusBar);
@@ -0,0 +1,364 @@
import { DefaultProps, ElementLocator, Font } from '@motajs/render';
import { computed, defineComponent, ref } from 'vue';
import { SetupComponentOptions } from '../components';
import {
DanmakuIcon,
DoubleArrow,
NumpadIcon,
PauseIcon,
PlayIcon,
ReplayIcon,
RetweetIcon,
RollbackIcon,
StepForward,
ViewMapIcon
} from '../components/icons';
import {
generateBinary,
getVitualKeyOnce,
openDanmakuPoster
} from '@motajs/legacy-ui';
import { gameKey } from '@motajs/system-action';
import { generateKeyboardEvent } from '@motajs/system-action';
import { transitioned } from '../use';
import { linear } from 'mutate-animate';
import { KeyCode } from '@motajs/client-base';
import { Progress } from '../components/misc';
interface ToolbarProps extends DefaultProps {
loc?: ElementLocator;
}
type ToolbarEmits = {
numpad: () => void;
};
const toolbarProps = {
props: ['loc'],
emits: ['numpad']
} satisfies SetupComponentOptions<
ToolbarProps,
ToolbarEmits,
keyof ToolbarEmits
>;
const im = (col: number, row: number): ElementLocator => {
return [5 + 34 * col, 5 + 36 * row, 32, 32];
};
const ic = (col: number, row: number): ElementLocator => {
return [7 + 34 * col, 7 + 36 * row, 28, 28];
};
const ic2 = (col: number, row: number): ElementLocator => {
return [9 + 34 * col, 9 + 36 * row, 24, 24];
};
const middle = (col: number, row: number): ElementLocator => {
return [21 + 34 * col, 21 + 36 * row, void 0, void 0, 0.5, 0.5];
};
const middle2 = (
col: number,
row: number,
width: number,
height: number
): ElementLocator => {
return [21 + 34 * col, 21 + 36 * row, width, height, 0.5, 0.5];
};
export const PlayingToolbar = defineComponent<
ToolbarProps,
ToolbarEmits,
keyof ToolbarEmits
>((props, { emit }) => {
const bookIcon = core.statusBar.icons.book;
const flyIcon = core.statusBar.icons.fly;
const toolIcon = core.statusBar.icons.toolbox;
const equipIcon = core.statusBar.icons.equipbox;
const keyIcon = core.statusBar.icons.keyboard;
const shopIcon = core.statusBar.icons.shop;
const saveIcon = core.statusBar.icons.save;
const loadIcon = core.statusBar.icons.load;
const setIcon = core.statusBar.icons.settings;
const iconFont = new Font('Verdana', 12);
const book = () => core.openBook(true);
const tool = () => core.openEquipbox(true);
const fly = () => core.useFly(true);
const save = () => core.save(true);
const load = () => core.load(true);
const equip = () => core.openEquipbox(true);
const shop = () => core.openQuickShop(true);
const key = () => {
getVitualKeyOnce().then(value => {
gameKey.emitKey(
value.key,
value.assist,
'up',
generateKeyboardEvent(value.key, value.assist)
);
});
};
const undo = () => core.doSL('autoSave', 'load');
const redo = () => core.doSL('autoSave', 'reload');
const numpad = () => emit('numpad');
const view = () => {
if (core.isPlaying() && !core.isMoving() && !core.status.lockControl) {
core.ui._drawViewMaps();
}
};
const danmaku = () => requestAnimationFrame(openDanmakuPoster);
const replay = () => core.ui._drawReplay();
const settings = () => core.openSettings(true);
return () => (
<container loc={props.loc} cursor="pointer">
<image image={bookIcon} loc={im(0, 0)} noanti onClick={book} />
<image image={toolIcon} loc={im(1, 0)} noanti onClick={tool} />
<image image={flyIcon} loc={im(2, 0)} noanti onClick={fly} />
<image image={saveIcon} loc={im(3, 0)} noanti onClick={save} />
<image image={loadIcon} loc={im(4, 0)} noanti onClick={load} />
<image image={equipIcon} loc={im(0, 1)} noanti onClick={equip} />
<image image={shopIcon} loc={im(1, 1)} noanti onClick={shop} />
<image image={keyIcon} loc={im(2, 1)} noanti onClick={key} />
<RollbackIcon loc={ic(3, 1)} strokeStyle="#eee" onClick={undo} />
<RetweetIcon loc={ic(4, 1)} strokeStyle="#eee" onClick={redo} />
<NumpadIcon loc={ic(0, 2)} strokeStyle="#eee" onClick={numpad} />
<ViewMapIcon loc={ic(1, 2)} strokeStyle="#eee" onClick={view} />
<DanmakuIcon loc={ic(2, 2)} strokeStyle="#eee" onClick={danmaku} />
<ReplayIcon loc={ic(3, 2)} strokeStyle="#eee" onClick={replay} />
<text text="R" loc={middle(3, 2)} font={iconFont} noevent />
<image image={setIcon} loc={im(4, 2)} noanti onClick={settings} />
</container>
);
}, toolbarProps);
export interface ReplayingStatus {
/** 是否正在播放 */
playing: boolean;
/** 录像播放速度 */
speed: number;
/** 已播放的长度 */
played: number;
/** 总长度 */
total: number;
}
export interface ReplayingProps extends ToolbarProps {
/** 录像播放状态 */
status: ReplayingStatus;
}
const replayingProps = {
props: ['status', 'loc']
} satisfies SetupComponentOptions<ReplayingProps>;
export const ReplayingToolbar = defineComponent<ReplayingProps>(props => {
const status = props.status;
const bookIcon = core.statusBar.icons.book;
const saveIcon = core.statusBar.icons.save;
const font1 = new Font('normal', 16);
const font2 = new Font('Verdana', 12);
const speedText = computed(() => `${status.speed}速`);
const progress = computed(() => status.played / status.total);
const progressText1 = computed(() => `${status.played}/${status.total}`);
const progressText2 = computed(
() => `${(progress.value * 100).toFixed(2)}%`
);
const play = () => core.resumeReplay();
const pause = () => core.pauseReplay();
const stop = () => core.stopReplay(true);
const speedDown = () => core.speedDownReplay();
const speedUp = () => core.speedUpReplay();
const book = () => core.openBook(true);
const save = () => core.save(true);
const view = () => {
if (core.isPlaying() && !core.isMoving() && !core.status.lockControl) {
core.ui._drawViewMaps();
}
};
const rewind = () => core.rewindReplay();
const step = () => core.stepReplay();
return () => {
return (
<container loc={props.loc} cursor="pointer">
{status.playing ? (
<PauseIcon loc={ic(0, 0)} onClick={pause} />
) : (
<PlayIcon loc={ic(0, 0)} onClick={play} />
)}
<g-rectr loc={[47, 13, 16, 16]} circle={[2]} onClick={stop} />
<DoubleArrow
loc={middle2(2, 0, 28, 28)}
scale={[-1, 1]}
onClick={speedDown}
/>
<text text={speedText.value} loc={middle(3, 0)} font={font1} />
<DoubleArrow loc={ic(4, 0)} onClick={speedUp} />
<image image={bookIcon} loc={im(0, 1)} noanti onClick={book} />
<image image={saveIcon} loc={im(1, 1)} noanti onClick={save} />
<ViewMapIcon loc={ic(2, 1)} onClick={view} />
<StepForward
loc={middle2(3, 1, 28, 28)}
scale={[-1, 1]}
onClick={rewind}
/>
<StepForward loc={ic(4, 1)} onClick={step} />
<text
text={progressText1.value}
loc={[12, 98, void 0, void 0, 0, 1]}
font={font2}
/>
<text
text={progressText2.value}
loc={[168, 98, void 0, void 0, 1, 1]}
font={font2}
/>
<Progress
loc={[12, 101, 156, 4]}
progress={progress.value}
success="lightgreen"
/>
</container>
);
};
}, replayingProps);
export const NumpadToolbar = defineComponent<
ToolbarProps,
ToolbarEmits,
keyof ToolbarEmits
>((props, { emit }) => {
const numpad = () => emit('numpad');
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const ctrlEnabled = ref(false);
const shiftEnabled = ref(false);
const altEnabled = ref(false);
const ctrlAlpha = transitioned(0, 100, linear())!;
const shiftAlpha = transitioned(0, 100, linear())!;
const altAlpha = transitioned(0, 100, linear())!;
const ctrlColor = computed(
() => `rgba(221,221,221,${ctrlAlpha.ref.value})`
);
const ctrlTextColor = computed(() => {
const rgb = Math.floor(255 - ctrlAlpha.ref.value * 255);
return `rgba(${rgb},${rgb},${rgb},1)`;
});
const shiftColor = computed(
() => `rgba(221,221,221,${shiftAlpha.ref.value})`
);
const shiftTextColor = computed(() => {
const rgb = Math.floor(255 - shiftAlpha.ref.value * 255);
return `rgba(${rgb},${rgb},${rgb},1)`;
});
const altColor = computed(() => `rgba(221,221,221,${altAlpha.ref.value})`);
const altTextColor = computed(() => {
const rgb = Math.floor(255 - altAlpha.ref.value * 255);
return `rgba(${rgb},${rgb},${rgb},1)`;
});
const clickCtrl = () => {
ctrlEnabled.value = !ctrlEnabled.value;
ctrlAlpha.set(ctrlEnabled.value ? 1 : 0);
};
const clickShift = () => {
shiftEnabled.value = !shiftEnabled.value;
shiftAlpha.set(shiftEnabled.value ? 1 : 0);
};
const clickAlt = () => {
altEnabled.value = !altEnabled.value;
altAlpha.set(altEnabled.value ? 1 : 0);
};
const clickNum = (num: number) => {
const bin = generateBinary([
ctrlEnabled.value,
shiftEnabled.value,
altEnabled.value
]);
const code = (KeyCode.Digit0 + num) as KeyCode;
gameKey.emitKey(code, bin, 'up', generateKeyboardEvent(code, bin));
};
return () => (
<container loc={props.loc} cursor="pointer">
<container loc={[0, 0, 180, 81]}>
{nums
.map((v, i) => {
const col = i % 5;
const row = Math.floor(i / 5);
return [
<g-rectr
loc={ic2(col, row)}
circle={[4]}
stroke
onClick={() => clickNum(v)}
/>,
<text
text={v.toString()}
loc={middle(col, row)}
noevent
/>
];
})
.flat()}
</container>
<g-rectr
loc={[41, 81, 36, 24]}
circle={[4]}
stroke
fill
fillStyle={ctrlColor.value}
onClick={clickCtrl}
></g-rectr>
<text
text="Ctrl"
loc={[59, 93, void 0, void 0, 0.5, 0.5]}
fillStyle={ctrlTextColor.value}
noevent
/>
<g-rectr
loc={[86, 81, 44, 24]}
circle={[4]}
stroke
fill
fillStyle={shiftColor.value}
onClick={clickShift}
></g-rectr>
<text
text="Shift"
loc={[108, 93, void 0, void 0, 0.5, 0.5]}
fillStyle={shiftTextColor.value}
noevent
/>
<g-rectr
loc={[139, 81, 30, 24]}
circle={[4]}
stroke
fill
fillStyle={altColor.value}
onClick={clickAlt}
></g-rectr>
<text
text="Alt"
loc={[154, 93, void 0, void 0, 0.5, 0.5]}
fillStyle={altTextColor.value}
noevent
/>
<NumpadIcon loc={ic(0, 2)} strokeStyle="gold" onClick={numpad} />
</container>
);
}, toolbarProps);
@@ -0,0 +1,293 @@
import { TimingFn, Transition } from 'mutate-animate';
import {
ComponentInternalInstance,
getCurrentInstance,
onMounted,
onUnmounted,
ref,
Ref
} from 'vue';
export const enum Orientation {
/** 横屏 */
Landscape,
/** 竖屏 */
Portrait
}
export type OrientationHook = (
orientation: Orientation,
width: number,
height: number
) => void;
let nowOrientation = Orientation.Landscape;
const orientationHooks = new Set<OrientationHook>();
function checkOrientation() {
const before = nowOrientation;
// 只要宽度大于高度,那么就视为横屏
if (window.innerWidth >= window.innerHeight) {
nowOrientation = Orientation.Landscape;
} else {
nowOrientation = Orientation.Portrait;
}
if (nowOrientation === before) return;
orientationHooks.forEach(v => {
v(nowOrientation, window.innerWidth, window.innerHeight);
});
}
window.addEventListener('resize', checkOrientation);
/**
* 当屏幕方向改变时执行函数
* @param hook 当屏幕方向改变时执行的函数
*/
export function onOrientationChange(hook: OrientationHook) {
onMounted(() => {
orientationHooks.add(hook);
hook(nowOrientation, window.innerWidth, window.innerHeight);
});
onUnmounted(() => {
orientationHooks.delete(hook);
});
}
/**
* 当游戏加载完成时执行函数,如果调用此函数时游戏已经加载,那么会立刻调用传入的钩子函数
* @param hook 当游戏加载完成时执行的函数
*/
export function onLoaded(hook: () => void) {
const loading = Mota.require('var', 'loading');
if (!loading.loaded) {
loading.once('loaded', hook);
} else {
hook();
}
}
export interface ITransitionedController<T> {
readonly ref: Ref<T>;
readonly value: T;
set(value: T, time?: number): void;
}
class RenderTransition implements ITransitionedController<number> {
private static key: number = 0;
private readonly key: string = `$${RenderTransition.key++}`;
public readonly ref: Ref<number>;
set value(v: number) {
this.transition.transition(this.key, v);
}
get value() {
return this.transition.value[this.key];
}
constructor(
value: number,
public readonly transition: Transition,
public readonly time: number,
public readonly curve: TimingFn
) {
this.ref = ref(value);
transition.value[this.key] = value;
transition.ticker.add(() => {
this.ref.value = transition.value[this.key];
});
}
set(value: number, time: number = this.time): void {
this.transition.time(time).mode(this.curve).transition(this.key, value);
}
}
type ColorRGBA = [number, number, number, number];
class RenderColorTransition implements ITransitionedController<string> {
private static key: number = 0;
private readonly keyR: string = `$colorR${RenderColorTransition.key++}`;
private readonly keyG: string = `$colorG${RenderColorTransition.key++}`;
private readonly keyB: string = `$colorB${RenderColorTransition.key++}`;
private readonly keyA: string = `$colorA${RenderColorTransition.key++}`;
public readonly ref: Ref<string>;
set value(v: string) {
this.set(v);
}
get value() {
return this.encodeColor();
}
constructor(
value: string,
public readonly transition: Transition,
public readonly time: number,
public readonly curve: TimingFn
) {
this.ref = ref(value);
const [r, g, b, a] = this.decodeColor(value);
transition.value[this.keyR] = r;
transition.value[this.keyG] = g;
transition.value[this.keyB] = b;
transition.value[this.keyA] = a;
transition.ticker.add(() => {
this.ref.value = this.encodeColor();
});
}
set(value: string, time: number = this.time): void {
this.transitionColor(this.decodeColor(value), time);
}
private transitionColor([r, g, b, a]: ColorRGBA, time: number) {
this.transition
.mode(this.curve)
.time(time)
.transition(this.keyR, r)
.transition(this.keyG, g)
.transition(this.keyB, b)
.transition(this.keyA, a);
}
private decodeColor(color: string): ColorRGBA {
if (color.startsWith('#')) {
return this.decodeHash(color);
} else if (color.startsWith('rgba')) {
return this.decodeRGBA(color);
} else if (color.startsWith('rgb')) {
return this.decodeRGB(color);
}
return [0, 0, 0, 1];
}
private decodeHash(color: string): ColorRGBA {
switch (color.length) {
case 4:
return [
Number(`0x${color.slice(1, 2).repeat(2)}`),
Number(`0x${color.slice(2, 3).repeat(2)}`),
Number(`0x${color.slice(3, 4).repeat(2)}`),
1
];
case 5:
return [
Number(`0x${color.slice(1, 2).repeat(2)}`),
Number(`0x${color.slice(2, 3).repeat(2)}`),
Number(`0x${color.slice(3, 4).repeat(2)}`),
Number(`0x${color.slice(4, 5).repeat(2)}`)
];
case 7:
return [
Number(`0x${color.slice(1, 3)}`),
Number(`0x${color.slice(3, 5)}`),
Number(`0x${color.slice(5, 7)}`),
1
];
case 9:
return [
Number(`0x${color.slice(1, 3)}`),
Number(`0x${color.slice(3, 5)}`),
Number(`0x${color.slice(5, 7)}`),
Number(`0x${color.slice(7, 9)}`)
];
}
return [0, 0, 0, 0];
}
private decodeRGBA(color: string): ColorRGBA {
const data = color.slice(color.indexOf('(') + 1, color.indexOf(')'));
const [r, g, b, a] = data.split(',');
return [Number(r), Number(g), Number(b), Number(a)];
}
private decodeRGB(color: string): ColorRGBA {
const data = color.slice(color.indexOf('(') + 1, color.indexOf(')'));
const [r, g, b] = data.split(',');
return [Number(r), Number(g), Number(b), 1];
}
private encodeColor() {
const r = this.transition.value[this.keyR];
const g = this.transition.value[this.keyG];
const b = this.transition.value[this.keyB];
const a = this.transition.value[this.keyA];
return `rgba(${r},${g},${b},${a})`;
}
}
const transitionMap = new Map<ComponentInternalInstance, Transition>();
function checkTransition() {
const instance = getCurrentInstance();
if (!instance) return null;
if (instance.isUnmounted) {
const tran = transitionMap.get(instance);
tran?.ticker.destroy();
transitionMap.delete(instance);
return null;
}
if (!transitionMap.has(instance)) {
const tran = new Transition();
transitionMap.set(instance, tran);
onUnmounted(() => {
transitionMap.delete(instance);
tran.ticker.destroy();
});
}
const tran = transitionMap.get(instance);
if (!tran) return null;
return tran;
}
/**
* 创建一个渐变数值,当数值发生变化时会缓慢变化值目标值而非突变,只可以用于组件内,不可用于组件外
* ```tsx
* const value = transitioned(10, 300, linear()); // 创建渐变,初始值为 10,渐变时长 300ms,线性变化
* value.set(100); // 渐变至 100
*
* // 直接在元素上使用
* <text text={value.ref.value} />
* ```
* @param value 初始值
* @param time 渐变时长
* @param curve 渐变的速率曲线
*/
export function transitioned(
value: number,
time: number,
curve: TimingFn
): ITransitionedController<number> | null {
const tran = checkTransition();
if (!tran) return null;
return new RenderTransition(value, tran, time, curve);
}
/**
* 创建一个渐变颜色,当颜色发生变化时会缓慢变化值目标值而非突变,自动判断颜色字符串类型,只可用于组件内,不可用于组件外
* ```tsx
* // 创建渐变,初始值为 '#fff'(白色),渐变时长 300ms,线性变化
* const color = transitionedColor('#fff', 300, linear());
* color.set('rgba(129, 30, 40, 0.7)'); // 渐变至这个颜色
*
* // 直接在元素上使用
* <text text='文本' fillStyle={color.ref.value} />
* ```
* @param color 颜色的初始值
* @param time 渐变时长
* @param curve 渐变的速率曲线
*/
export function transitionedColor(
color: string,
time: number,
curve: TimingFn
): ITransitionedController<string> | null {
const tran = checkTransition();
if (!tran) return null;
return new RenderColorTransition(color, tran, time, curve);
}
@@ -0,0 +1 @@
export * from './saves';
@@ -0,0 +1,35 @@
export function getAllSavesData() {
return new Promise<string>(res => {
core.getAllSaves(saves => {
if (!saves) {
res('');
return;
}
const content = {
name: core.firstData.name,
version: core.firstData.version,
data: saves
};
// @ts-expect-error 暂时无法推导
res(LZString.compressToBase64(JSON.stringify(content)));
});
});
}
export function getSaveData(index: number) {
return new Promise<string>(res => {
core.getSave(index, data => {
if (!data) {
res('');
return;
}
const content = {
name: core.firstData.name,
version: core.firstData.version,
data: data
};
// @ts-expect-error 暂时无法推导
res(LZString.compressToBase64(JSON.stringify(content)));
});
});
}
Whitespace-only changes.
@@ -0,0 +1,11 @@
import { RainWeather } from './rain';
import { SnowWeather } from './snow';
import { SunWeather } from './sun';
import { WeatherController } from './weather';
WeatherController.register('rain', RainWeather);
WeatherController.register('sun', SunWeather);
WeatherController.register('snow', SnowWeather);
export * from './weather';
export * from './rain';
@@ -0,0 +1,212 @@
import {
Shader,
ShaderProgram,
MotaRenderer,
Container,
IShaderUniform,
UniformType
} from '@motajs/render';
import { IWeather } from './weather';
const rainVs = /* glsl */ `
in vec2 a_rainVertex;
in vec2 a_offset; // 雨滴的中心位置
in vec4 a_data; // x: 雨滴宽度; y: 雨滴长度; z: 雨滴旋转角度,0表示向下,逆时针为正;
// w: 属于哪一种雨,需要两种雨反复循环,一种无法实现循环,0表示第一种,1表示第二种
uniform float u_progress; // 下雨进度,从最上落到最下是0.5个进度,以保证不会出现奇怪的问题
out vec2 v_center;
out vec2 v_data; // 雨滴宽度与高度
out vec2 v_pos;
mat2 createScaleMatrix(float x, float y) {
return mat2(
x, 0,
0, y
);
}
vec2 getOffsetByProgress(vec2 offset) {
if (a_data.w == 0.0) {
if (u_progress < 0.5) {
return offset * u_progress * 2.0;
} else {
return offset * (u_progress - 1.0) * 2.0;
}
} else {
return offset * u_progress * 2.0;
}
}
void main() {
float cosTheta = cos(a_data.z);
float sinTheta = sin(a_data.z);
mat2 rotate = mat2(
cosTheta, -sinTheta,
sinTheta, cosTheta
);
vec2 offset = getOffsetByProgress(vec2(-sinTheta * 2.0, -cosTheta * 2.0));
mat2 scale = createScaleMatrix(a_data.x, a_data.y);
vec2 off = a_offset + offset;
vec2 pos = rotate * scale * a_rainVertex + off;
v_center = off;
v_pos = pos;
gl_Position = vec4(pos, 0.0, 1.0);
}
`;
const rainFs = /* glsl */ `
in vec2 v_center;
in vec2 v_data; // 雨滴的宽度与长度
in vec2 v_pos;
uniform vec4 u_color; // 雨滴的颜色
out vec4 outColor;
float random(vec2 uv) {
return fract(sin(dot(uv, vec2(12.9898, 78.233))) * 43758.5453);
}
void main() {
float ran = random(v_pos);
vec2 pos = vec2(v_pos.x + ran * 0.01, v_pos.y);
vec2 texPos = (pos + 1.0) / 2.0;
texPos.y = 1.0 - texPos.y;
vec4 tex = texture(u_sampler, texPos);
outColor = mix(u_color, tex, 0.9);
}
`;
/** 雨滴顶点坐标 */
const vertex = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
export class RainWeather implements IWeather {
readonly shader: RainShader;
readonly program: ShaderProgram;
private progress: IShaderUniform<UniformType.Uniform1f> | null = null;
constructor(readonly level: number = 5) {
const shader = new RainShader();
const gl = shader.gl;
shader.size(480, 480);
shader.setHD(true);
shader.setZIndex(100);
const program = shader.createProgram(ShaderProgram);
program.fs(rainFs);
program.vs(rainVs);
program.requestCompile();
const pos = program.defineAttribArray('a_rainVertex');
program.defineAttribArray('a_offset');
program.defineAttribArray('a_data');
program.defineUniform('u_progress', shader.UNIFORM_1f);
program.defineUniform('u_color', shader.UNIFORM_4f);
program.mode(shader.DRAW_ARRAYS_INSTANCED);
shader.useProgram(program);
if (pos) {
pos.buffer(vertex, gl.STATIC_DRAW);
pos.pointer(2, gl.FLOAT, false, 0, 0);
pos.enable();
}
this.shader = shader;
this.program = program;
}
activate(): void {
const render = MotaRenderer.get('render-main');
const draw = render?.getElementById('map-draw') as Container;
if (!draw) return;
const shader = this.shader;
shader.append(draw);
const gl = shader.gl;
const program = this.program;
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, 100 * this.level);
this.progress = program.getUniform<UniformType.Uniform1f>('u_progress');
shader.useProgram(program);
shader.generateRainPath(
this.level * 100,
(((Math.random() - 0.5) * Math.PI) / 30) * this.level,
(Math.PI / 180) * (12 - this.level),
program
);
}
frame(): void {
this.shader.update(this.shader);
const time = 5000 - 400 * this.level;
const progress = (Date.now() % time) / time;
this.shader.useProgram(this.program);
this.progress?.set(progress);
}
deactivate(): void {
const render = MotaRenderer.get('render-main');
const draw = render?.getElementById('map-draw') as Container;
const layer = draw.children;
if (!layer || !draw) return;
const shader = this.shader;
draw.appendChild(...layer);
shader.remove();
}
}
class RainShader extends Shader {
/**
* 生成雨滴
* @param num 雨滴数量
*/
generateRainPath(
num: number,
angle: number,
deviation: number,
program: ShaderProgram
) {
const aOffset = program.getAttribArray('a_offset');
const aData = program.getAttribArray('a_data');
const color = program.getUniform<UniformType.Uniform4f>('u_color');
const gl = this.gl;
if (!aOffset || !aData) return;
const tan = Math.tan(angle);
const offset = new Float32Array(num * 2);
const data = new Float32Array(num * 4);
const half = num / 2;
for (let i = 0; i < half; i++) {
const ox = Math.random() * 3 - 1.5;
const oy = Math.random() * 2 - 1;
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
const length = Math.random() * 0.05 + 0.03;
const width = Math.random() * 0.002 + 0.002;
offset.set([ox, oy], i * 2);
data.set([width, length, rad, 0], i * 4);
}
for (let i = half; i < num; i++) {
const ox = Math.random() * 3 - 1.5 + tan * 2;
const oy = Math.random() * 2 + 1;
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
const length = Math.random() * 0.1 + 0.05;
const width = Math.random() * 0.002 + 0.002;
offset.set([ox, oy], i * 2);
data.set([width, length, rad, 1], i * 4);
}
aOffset.buffer(offset, gl.STATIC_DRAW);
aData.buffer(data, gl.STATIC_DRAW);
aOffset.pointer(2, gl.FLOAT, false, 0, 0);
aOffset.divisor(1);
aOffset.enable();
aData.pointer(4, gl.FLOAT, false, 0, 0);
aData.divisor(1);
aData.enable();
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, num);
color?.set(1, 1, 1, 0.1);
}
}
@@ -0,0 +1,250 @@
import {
Shader,
ShaderProgram,
MotaRenderer,
Container,
GL2Program,
IShaderUniform,
UniformType,
Transform,
MotaOffscreenCanvas2D
} from '@motajs/render';
import { IWeather } from './weather';
const snowVs = /* glsl */ `
in vec2 a_snowVertex;
in vec2 a_offset; // 雨滴的中心位置
in vec4 a_data; // x: 雨滴宽度; y: 雨滴长度; z: 雨滴旋转角度,0表示向下,逆时针为正;
// w: 属于哪一种雨,需要两种雨反复循环,一种无法实现循环,0表示第一种,1表示第二种
uniform float u_progress; // 下雨进度,从最上落到最下是0.5个进度,以保证不会出现奇怪的问题
out vec2 v_center;
out vec2 v_data; // 雨滴宽度与高度
out vec2 v_pos;
mat2 createScaleMatrix(float x, float y) {
return mat2(
x, 0,
0, y
);
}
vec2 getOffsetByProgress(vec2 offset) {
if (a_data.w == 0.0) {
if (u_progress < 0.5) {
return offset * u_progress * 2.0;
} else {
return offset * (u_progress - 1.0) * 2.0;
}
} else {
return offset * u_progress * 2.0;
}
}
void main() {
float cosTheta = cos(a_data.z);
float sinTheta = sin(a_data.z);
mat2 rotate = mat2(
cosTheta, -sinTheta,
sinTheta, cosTheta
);
vec2 offset = getOffsetByProgress(vec2(-sinTheta * 2.0, -cosTheta * 2.0));
mat2 scale = createScaleMatrix(a_data.x, a_data.y);
vec2 off = a_offset + offset;
// const int segments = 32; // 圆的分段数
// float angleIncrement = 2.0 * 3.14159265359 / float(segments);
// vec2 a_roundVertex[segments];
// for (int i = 0; i < segments; i++) {
// float angle = float(i) * angleIncrement;
// a_roundVertex[i] = vec2(cos(angle), sin(angle)); // 生成单位圆的顶点
// }
// vec2 pos = rotate * scale * a_roundVertex + off;
vec2 pos = rotate * scale * a_snowVertex + off;
v_center = off;
v_pos = pos;
gl_Position = vec4(pos, 0.0, 1.0);
}
`;
const snowFs = /* glsl */ `
in vec2 v_center;
in vec2 v_data; // 雨滴的宽度与长度
in vec2 v_pos;
uniform vec4 u_color; // 雨滴的颜色
out vec4 outColor;
float random(vec2 uv) {
return fract(sin(dot(uv, vec2(12.9898, 78.233))) * 43758.5453);
}
void main() {
float distanceFromCenter = length(v_pos - v_center);
if (distanceFromCenter < 0.05) {
outColor = u_color; // 雪花颜色
} else {
// outColor = vec4(0.0, 0.0, 0.0, 0.2);
discard; // 不绘制超出圆的部分
}
// float ran = random(v_pos);
// vec2 pos = vec2(v_pos.x + ran * 0.01, v_pos.y);
// vec2 texPos = (pos + 1.0) / 2.0;
// texPos.y = 1.0 - texPos.y;
// vec4 tex = texture(u_sampler, texPos);
// // outColor = mix(u_color, tex, 0.9);
// outColor = u_color;
}
`;
/** 雨滴顶点坐标 */
const vertex = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
Mota.require('var', 'loading').once('coreInit', () => {
const shader = new SnowShader();
const gl = shader.gl;
shader.size(480, 480);
shader.setHD(true);
SnowWeather.shader = shader;
const program = shader.createProgram(ShaderProgram);
program.fs(snowFs);
program.vs(snowVs);
program.requestCompile();
const pos = program.defineAttribArray('a_snowVertex');
program.defineAttribArray('a_offset');
program.defineAttribArray('a_data');
program.defineUniform('u_progress', shader.UNIFORM_1f);
program.defineUniform('u_color', shader.UNIFORM_4f);
program.mode(shader.DRAW_ARRAYS_INSTANCED);
SnowShader.snowProgram = program;
shader.useProgram(program);
if (pos) {
pos.buffer(vertex, gl.STATIC_DRAW);
pos.pointer(2, gl.FLOAT, false, 0, 0);
pos.enable();
}
});
export class SnowWeather implements IWeather {
static id: string = 'snow';
static shader: SnowShader;
private progress: IShaderUniform<UniformType.Uniform1f> | null = null;
constructor(readonly level: number = 5) {}
activate(): void {
const render = MotaRenderer.get('render-main');
const draw = render?.getElementById('map-draw') as Container;
if (!draw) return;
const shader = SnowWeather.shader;
shader.append(draw);
const gl = shader.gl;
const program = SnowShader.snowProgram;
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, 100 * this.level);
this.progress = program.getUniform<UniformType.Uniform1f>('u_progress');
shader.generateSnowPath(
this.level * 100,
(((Math.random() - 0.5) * Math.PI) / 30) * this.level,
(Math.PI / 180) * (12 - this.level)
);
}
frame(): void {
SnowWeather.shader.update(SnowWeather.shader);
const time = 5000 - 400 * this.level;
const progress = (Date.now() % time) / time;
SnowWeather.shader.useProgram(SnowShader.snowProgram);
this.progress?.set(progress);
}
deactivate(): void {
const render = MotaRenderer.get('render-main');
const layer = render?.getElementById('layer-main');
const draw = render?.getElementById('map-draw') as Container;
if (!layer || !draw) return;
const shader = SnowWeather.shader;
layer.append(draw);
shader.remove();
}
}
class SnowShader extends Shader {
static snowProgram: ShaderProgram;
static backProgram: ShaderProgram;
/**
* 生成雨滴
* @param num 雨滴数量
*/
generateSnowPath(num: number, angle: number, deviation: number) {
const program = SnowShader.snowProgram;
SnowWeather.shader.useProgram(program);
const aOffset = program.getAttribArray('a_offset');
const aData = program.getAttribArray('a_data');
const color = program.getUniform<UniformType.Uniform4f>('u_color');
const gl = this.gl;
if (!aOffset || !aData) return;
const tan = Math.tan(angle);
const offset = new Float32Array(num * 2);
const data = new Float32Array(num * 4);
const half = num / 2;
for (let i = 0; i < half; i++) {
const ox = Math.random() * 3 - 1.5;
const oy = Math.random() * 2 - 1;
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
const length = Math.random() * 0.05 + 0.03;
const width = Math.random() * 0.05 + 0.03;
offset.set([ox, oy], i * 2);
data.set([width, length, rad, 0], i * 4);
}
for (let i = half; i < num; i++) {
const ox = Math.random() * 3 - 1.5 + tan * 2;
const oy = Math.random() * 2 + 1;
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
const length = Math.random() * 0.1 + 0.05;
const width = Math.random() * 0.1 + 0.05;
offset.set([ox, oy], i * 2);
data.set([width, length, rad, 1], i * 4);
}
aOffset.buffer(offset, gl.STATIC_DRAW);
aData.buffer(data, gl.STATIC_DRAW);
aOffset.pointer(2, gl.FLOAT, false, 0, 0);
aOffset.divisor(1);
aOffset.enable();
aData.pointer(4, gl.FLOAT, false, 0, 0);
aData.divisor(1);
aData.enable();
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, num);
color?.set(1, 1, 1, 0.1);
}
protected preDraw(
canvas: MotaOffscreenCanvas2D,
transform: Transform,
gl: WebGL2RenderingContext,
program: GL2Program
): boolean {
const snow = SnowShader.snowProgram;
const snowParam = snow.getDrawParams(this.DRAW_ARRAYS_INSTANCED);
if (!snowParam) return false;
this.useProgram(snow);
if (!snow.ready()) return false;
this.draw(gl, snow);
return false;
}
}
@@ -0,0 +1,11 @@
import { IWeather } from './weather';
export class SunWeather implements IWeather {
static id: string = 'sun';
activate(): void {}
frame(): void {}
deactivate(): void {}
}
@@ -0,0 +1,129 @@
import { logger } from '@motajs/common';
import { RenderItem } from '@motajs/render';
import { Ticker } from 'mutate-animate';
export interface IWeather {
/**
* 初始化天气,当天气被添加时会被立刻调用
*/
activate(item: RenderItem): void;
/**
* 每帧执行的函数
*/
frame(): void;
/**
* 摧毁这个天气,当天气被删除时会执行
*/
deactivate(item: RenderItem): void;
}
type Weather = new (level?: number) => IWeather;
export class WeatherController {
static list: Map<string, Weather> = new Map();
static map: Map<string, WeatherController> = new Map();
/** 当前的所有天气 */
active: Set<IWeather> = new Set();
ticker: Ticker = new Ticker();
private binded?: RenderItem;
constructor(public readonly id: string) {
WeatherController.map.set(id, this);
}
private tick = () => {
this.active.forEach(v => {
v.frame();
});
};
/**
* 清空所有天气
*/
clearWeather() {
if (this.binded) {
this.active.forEach(v => {
v.deactivate(this.binded!);
});
}
this.active.clear();
}
/**
* 获取一个天气
* @param weather 要获取的天气
*/
getWeather<T extends IWeather = IWeather>(weather: Weather): T | null {
return ([...this.active].find(v => v instanceof weather) as T) ?? null;
}
/**
* 添加一个天气,如果天气不存在则抛出警告。注意虽然原则上不允许天气重复。
* @param id 天气的id
* @param level 天气的等级
* @returns 天气实例,可以操作天气的效果,也可以用来删除
*/
activate(id: string, level?: number) {
const Weather = WeatherController.list.get(id);
if (!Weather) {
logger.warn(25, id);
return;
}
const weather = new Weather(level);
this.active.add(weather);
if (this.binded) {
weather.activate(this.binded);
}
if (!this.ticker.funcs.has(this.tick)) {
this.ticker.add(this.tick);
}
return weather;
}
/**
* 删除一个天气
* @param weather 要删除的天气
*/
deactivate(weather: IWeather) {
this.active.delete(weather);
if (this.active.size === 0) {
this.ticker.remove(this.tick);
}
if (this.binded) {
weather.deactivate(this.binded);
}
}
/**
* 将这个天气控制器绑定至一个渲染元素上
* @param item 要绑定的元素,不填表示取消绑定
*/
bind(item?: RenderItem) {
if (this.binded) {
this.active.forEach(v => v.deactivate(this.binded!));
}
this.binded = item;
if (item) {
this.active.forEach(v => v.activate(item));
}
}
/**
* 摧毁这个天气控制器
*/
destroy() {
WeatherController.map.delete(this.id);
}
static get(id: string) {
return this.map.get(id);
}
static register(id: string, weather: Weather) {
this.list.set(id, weather);
}
}