mirror of
https://github.com/motajs/template.git
synced 2026-11-29 09:54:30 +08:00
refactor: 客户端加载
This commit is contained in:
1 parent
fdeee99d40
commit
4fc6db3e79
55 files changed
+1699
-1234
No files matched your search
@@ -1,9 +1,11 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { IAudioVolumeEffect, IMotaAudioContext } from './types';
|
||||
import { IAudioVolumeEffect, IMotaAudioContext, ISoundPlayer } from './types';
|
||||
|
||||
type LocationArray = [number, number, number];
|
||||
|
||||
export class SoundPlayer<T extends string = SoundIds> {
|
||||
export class SoundPlayer<
|
||||
T extends string = SoundIds
|
||||
> implements ISoundPlayer<T> {
|
||||
/** 每个音效的唯一标识符 */
|
||||
private num: number = 0;
|
||||
|
||||
@@ -50,13 +52,17 @@ export class SoundPlayer<T extends string = SoundIds> {
|
||||
* @param id 音效名称
|
||||
* @param data 音效的Uint8Array数据
|
||||
*/
|
||||
async add(id: T, data: Uint8Array) {
|
||||
const buffer = await this.ac.decodeToAudioBuffer(data);
|
||||
if (!buffer) {
|
||||
logger.warn(51, id);
|
||||
return;
|
||||
async add(id: T, data: Uint8Array | AudioBuffer) {
|
||||
if (data instanceof Uint8Array) {
|
||||
const buffer = await this.ac.decodeToAudioBuffer(data);
|
||||
if (!buffer) {
|
||||
logger.warn(51, id);
|
||||
return;
|
||||
}
|
||||
this.buffer.set(id, buffer);
|
||||
} else {
|
||||
this.buffer.set(id, data);
|
||||
}
|
||||
this.buffer.set(id, buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -123,6 +123,12 @@ export class AudioStreamSource
|
||||
this.controller = controller;
|
||||
}
|
||||
|
||||
unpiped(controller: IStreamController): void {
|
||||
if (this.controller === controller) {
|
||||
this.controller = null;
|
||||
}
|
||||
}
|
||||
|
||||
async pump(data: Uint8Array | undefined, done: boolean): Promise<void> {
|
||||
if (!data || this.errored) return;
|
||||
if (!this.headerRecieved) {
|
||||
|
||||
@@ -611,7 +611,7 @@ export interface ISoundPlayer<T extends string> {
|
||||
* @param id 音效名称
|
||||
* @param data 音效的Uint8Array数据
|
||||
*/
|
||||
add(id: T, data: Uint8Array): Promise<void>;
|
||||
add(id: T, data: Uint8Array | AudioBuffer): Promise<void>;
|
||||
|
||||
/**
|
||||
* 播放一个音效
|
||||
|
||||
@@ -149,6 +149,7 @@
|
||||
"92": "Followers can only be added when the last follower is not moving.",
|
||||
"93": "Followers can only be removed when the last follower is not moving.",
|
||||
"94": "Expecting an excitation binding when using '$1'",
|
||||
"95": "Task adding is required before start loading.",
|
||||
"1001": "Item-detail extension needs 'floor-binder' and 'floor-damage' extension as dependency."
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { EventEmitter } from 'eventemitter3';
|
||||
|
||||
interface DisposableEvent<T> {
|
||||
active: [value: T];
|
||||
dispose: [value: T];
|
||||
destroy: [];
|
||||
}
|
||||
|
||||
export class Disposable<T> extends EventEmitter<DisposableEvent<T>> {
|
||||
protected _data?: T;
|
||||
set data(value: T | null) {
|
||||
if (this.destroyed) {
|
||||
throw new Error(
|
||||
`Cannot set value of destroyed disposable variable.`
|
||||
);
|
||||
}
|
||||
if (value !== null) this._data = value;
|
||||
}
|
||||
get data(): T | null {
|
||||
if (this.destroyed) {
|
||||
throw new Error(
|
||||
`Cannot get value of destroyed disposable variable.`
|
||||
);
|
||||
}
|
||||
if (!this.activated) {
|
||||
return null;
|
||||
}
|
||||
return this._data!;
|
||||
}
|
||||
|
||||
protected activated: boolean = false;
|
||||
protected destroyed: boolean = false;
|
||||
|
||||
constructor(data: T) {
|
||||
super();
|
||||
this._data = data;
|
||||
}
|
||||
|
||||
active() {
|
||||
if (this.activated) return;
|
||||
this.activated = true;
|
||||
this.emit('active', this._data!);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
if (!this.activated) return;
|
||||
this.activated = false;
|
||||
this.emit('dispose', this._data!);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this.destroyed) return;
|
||||
this.destroyed = true;
|
||||
this.emit('destroy');
|
||||
delete this._data;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
export * from './patch';
|
||||
export * from './disposable';
|
||||
export * from './eventEmitter';
|
||||
export * from './resource';
|
||||
export * from './utils';
|
||||
@@ -1,712 +0,0 @@
|
||||
import axios, { AxiosRequestConfig, ResponseType } from 'axios';
|
||||
import { EventEmitter } from './eventEmitter';
|
||||
import { Disposable } from './disposable';
|
||||
import { logger } from '@motajs/common';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
type ProgressFn = (now: number, total: number) => void;
|
||||
|
||||
interface ResourceType {
|
||||
text: string;
|
||||
buffer: ArrayBuffer;
|
||||
image: HTMLImageElement;
|
||||
material: HTMLImageElement;
|
||||
audio: HTMLAudioElement;
|
||||
json: any;
|
||||
zip: JSZip;
|
||||
byte: Uint8Array;
|
||||
}
|
||||
|
||||
interface ResourceMap {
|
||||
text: TextResource;
|
||||
buffer: BufferResource;
|
||||
image: ImageResource;
|
||||
material: MaterialResource;
|
||||
audio: AudioResource;
|
||||
json: JSONResource;
|
||||
zip: ZipResource;
|
||||
byte: ByteResource;
|
||||
}
|
||||
|
||||
interface CompressedLoadListItem {
|
||||
type: keyof ResourceType;
|
||||
name: string;
|
||||
usage: string;
|
||||
}
|
||||
type CompressedLoadList = Record<string, CompressedLoadListItem[]>;
|
||||
|
||||
const types: Record<keyof ResourceType, JSZip.OutputType> = {
|
||||
text: 'string',
|
||||
buffer: 'arraybuffer',
|
||||
image: 'blob',
|
||||
material: 'blob',
|
||||
audio: 'arraybuffer',
|
||||
json: 'string',
|
||||
zip: 'arraybuffer',
|
||||
byte: 'uint8array'
|
||||
};
|
||||
|
||||
const base = import.meta.env.DEV ? '/' : '';
|
||||
|
||||
function toURL(uri: string) {
|
||||
return import.meta.env.DEV ? uri : `${import.meta.env.BASE_URL}${uri}`;
|
||||
}
|
||||
|
||||
export abstract class Resource<T = any> extends Disposable<string> {
|
||||
type = 'none';
|
||||
|
||||
uri: string = '';
|
||||
resource?: T;
|
||||
loaded: boolean = false;
|
||||
|
||||
/**
|
||||
* 创建一个资源
|
||||
* @param uri 资源的URI,格式为 type/file
|
||||
* @param type 资源类型,不填为none,并会抛出警告
|
||||
*/
|
||||
constructor(uri: string, type: string = 'none') {
|
||||
super(uri);
|
||||
this.type = type;
|
||||
this.uri = uri;
|
||||
|
||||
if (this.type === 'none') {
|
||||
logger.warn(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载这个资源,需要被子类override
|
||||
*/
|
||||
abstract load(onProgress?: ProgressFn): Promise<T>;
|
||||
|
||||
/**
|
||||
* 解析资源URI,解析为一个URL,可以直接由请求获取
|
||||
*/
|
||||
abstract resolveURI(): string;
|
||||
|
||||
/**
|
||||
* 获取资源数据,当数据未加载完毕或未启用时返回null
|
||||
*/
|
||||
getData(): T | null {
|
||||
if (!this.activated || !this.loaded) return null;
|
||||
if (this.resource === null || this.resource === void 0) return null;
|
||||
return this.resource;
|
||||
}
|
||||
}
|
||||
|
||||
export class ImageResource extends Resource<HTMLImageElement> {
|
||||
/**
|
||||
* 创建一个图片资源
|
||||
* @param uri 图片资源的URI,格式为 image/file,例如 'image/project/images/hero.png'
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'image');
|
||||
}
|
||||
|
||||
load(_onProgress?: ProgressFn): Promise<HTMLImageElement> {
|
||||
const img = new Image();
|
||||
img.src = this.resolveURI();
|
||||
this.resource = img;
|
||||
return new Promise<HTMLImageElement>(res => {
|
||||
img.loading = 'eager';
|
||||
img.addEventListener('load', () => {
|
||||
this.loaded = true;
|
||||
img.setAttribute('_width', img.width.toString());
|
||||
img.setAttribute('_height', img.height.toString());
|
||||
res(img);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class MaterialResource extends ImageResource {
|
||||
/**
|
||||
* 创建一个material资源
|
||||
* @param uri 资源的URI,格式为 material/file,例如 'material/enemys.png'
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri);
|
||||
this.type = 'material';
|
||||
}
|
||||
|
||||
override resolveURI(): string {
|
||||
return toURL(`${base}project/materials/${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class TextResource extends Resource<string> {
|
||||
/**
|
||||
* 创建一个文字资源
|
||||
* @param uri 文字资源的URI,格式为 text/file,例如 'text/myText.txt'
|
||||
* 这样的话会加载塔根目录下的 myText.txt 文件
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'text');
|
||||
}
|
||||
|
||||
load(onProgress?: ProgressFn): Promise<string> {
|
||||
return new Promise(res => {
|
||||
createAxiosLoader<string>(
|
||||
this.resolveURI(),
|
||||
'text',
|
||||
onProgress
|
||||
).then(value => {
|
||||
this.resource = value.data;
|
||||
this.loaded = true;
|
||||
res(value.data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class BufferResource extends Resource<ArrayBuffer> {
|
||||
/**
|
||||
* 创建一个二进制缓冲区资源
|
||||
* @param uri 资源的URI,格式为 buffer/file,例如 'buffer/myBuffer.mp3'
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'buffer');
|
||||
}
|
||||
|
||||
load(onProgress?: ProgressFn): Promise<ArrayBuffer> {
|
||||
return new Promise(res => {
|
||||
createAxiosLoader<ArrayBuffer>(
|
||||
this.resolveURI(),
|
||||
'arraybuffer',
|
||||
onProgress
|
||||
).then(value => {
|
||||
this.resource = value.data;
|
||||
this.loaded = true;
|
||||
res(value.data);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class ByteResource extends Resource<Uint8Array> {
|
||||
/**
|
||||
* 创建一个二进制缓冲区资源
|
||||
* @param uri 资源的URI,格式为 byte/file,例如 'byte/myBuffer.mp3'
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'buffer');
|
||||
}
|
||||
|
||||
async load(_onProgress?: ProgressFn): Promise<Uint8Array> {
|
||||
const response = await fetch(this.resolveURI());
|
||||
const data = await response.arrayBuffer();
|
||||
this.resource = new Uint8Array(data);
|
||||
return this.resource;
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class JSONResource<T = any> extends Resource<T> {
|
||||
/**
|
||||
* 创建一个JSON对象资源
|
||||
* @param uri 资源的URI,格式为 json/file,例如 'buffer/myJSON.json'
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'json');
|
||||
}
|
||||
|
||||
load(onProgress?: ProgressFn): Promise<any> {
|
||||
return new Promise(res => {
|
||||
createAxiosLoader<any>(this.resolveURI(), 'json', onProgress).then(
|
||||
value => {
|
||||
this.resource = value.data;
|
||||
this.loaded = true;
|
||||
res(value.data);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioResource extends Resource<HTMLAudioElement> {
|
||||
/**
|
||||
* 创建一个音乐资源
|
||||
* @param uri 音乐资源的URI,格式为 audio/file,例如 'audio/bgm.mp3'
|
||||
* 注意这个资源类型为 bgm 等只在播放时才开始流式加载的音乐资源类型,
|
||||
* 对于需要一次性加载完毕的需要使用 BufferResource 进行加载,
|
||||
* 并可以通过 AudioPlayer 类进行解析播放
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'audio');
|
||||
}
|
||||
|
||||
load(_onProgress?: ProgressFn): Promise<HTMLAudioElement> {
|
||||
const audio = new Audio();
|
||||
audio.src = this.resolveURI();
|
||||
audio.preload = 'none';
|
||||
this.resource = audio;
|
||||
return new Promise<HTMLAudioElement>(res => {
|
||||
this.loaded = true;
|
||||
res(audio);
|
||||
});
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}project/bgms/${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class ZipResource extends Resource<JSZip> {
|
||||
/**
|
||||
* 创建一个zip压缩资源
|
||||
* @param uri 资源的URI,格式为 zip/file,例如 'zip/myZip.h5data'
|
||||
* 注意后缀名不要是zip,不然有的浏览器会触发下载,而不是加载
|
||||
*/
|
||||
constructor(uri: string) {
|
||||
super(uri, 'zip');
|
||||
this.type = 'zip';
|
||||
}
|
||||
|
||||
async load(onProgress?: ProgressFn): Promise<JSZip> {
|
||||
const data = await new Promise<ArrayBuffer>(res => {
|
||||
createAxiosLoader<ArrayBuffer>(
|
||||
this.resolveURI(),
|
||||
'arraybuffer',
|
||||
onProgress
|
||||
).then(value => {
|
||||
res(value.data);
|
||||
});
|
||||
});
|
||||
const unzipped = await JSZip.loadAsync(data);
|
||||
this.resource = unzipped;
|
||||
this.loaded = true;
|
||||
return unzipped;
|
||||
}
|
||||
|
||||
resolveURI(): string {
|
||||
return toURL(`${base}${findURL(this.uri)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function createAxiosLoader<T = any>(
|
||||
url: string,
|
||||
responseType: ResponseType,
|
||||
onProgress?: (now: number, total: number) => void
|
||||
) {
|
||||
const config: AxiosRequestConfig<T> = {};
|
||||
config.responseType = responseType;
|
||||
if (onProgress) {
|
||||
config.onDownloadProgress = e => {
|
||||
onProgress(e.loaded, e.total ?? 0);
|
||||
};
|
||||
}
|
||||
return axios.get<T>(url, config);
|
||||
}
|
||||
|
||||
function findURL(uri: string) {
|
||||
return uri.slice(uri.indexOf('/') + 1);
|
||||
}
|
||||
|
||||
export const resourceTypeMap = {
|
||||
text: TextResource,
|
||||
buffer: BufferResource,
|
||||
image: ImageResource,
|
||||
material: MaterialResource,
|
||||
audio: AudioResource,
|
||||
json: JSONResource,
|
||||
zip: ZipResource,
|
||||
byte: ByteResource
|
||||
};
|
||||
|
||||
interface LoadEvent<T extends keyof ResourceType> {
|
||||
progress: (
|
||||
type: keyof ResourceType,
|
||||
uri: string,
|
||||
now: number,
|
||||
total: number
|
||||
) => void;
|
||||
load: (resource: ResourceMap[T]) => void | Promise<any>;
|
||||
loadStart: (resource: ResourceMap[T]) => void;
|
||||
}
|
||||
|
||||
type TaskProgressFn = (
|
||||
loadedByte: number,
|
||||
totalByte: number,
|
||||
loadedTask: number,
|
||||
totalTask: number
|
||||
) => void;
|
||||
|
||||
export class LoadTask<
|
||||
T extends keyof ResourceType = keyof ResourceType
|
||||
> extends EventEmitter<LoadEvent<T>> {
|
||||
static totalByte: number = 0;
|
||||
static loadedByte: number = 0;
|
||||
static totalTask: number = 0;
|
||||
static loadedTask: number = 0;
|
||||
static errorTask: number = 0;
|
||||
|
||||
/** 所有的资源,包括没有添加到加载任务里面的 */
|
||||
static store: Map<string, Resource> = new Map();
|
||||
static taskList: Set<LoadTask> = new Set();
|
||||
static loadedTaskList: Set<LoadTask> = new Set();
|
||||
|
||||
private static progress: TaskProgressFn;
|
||||
private static caledTask: Set<string> = new Set();
|
||||
|
||||
resource: Resource;
|
||||
type: T;
|
||||
uri: string;
|
||||
|
||||
private loadingStarted: boolean = false;
|
||||
loading: boolean = false;
|
||||
loaded: number = 0;
|
||||
|
||||
/**
|
||||
* 新建一个加载任务
|
||||
* @param type 任务类型
|
||||
* @param uri 加载内容的URL
|
||||
*/
|
||||
constructor(type: T, uri: string) {
|
||||
super();
|
||||
this.resource = new resourceTypeMap[type](uri);
|
||||
this.type = type;
|
||||
this.uri = uri;
|
||||
LoadTask.store.set(uri, this.resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行加载过程,当加载完毕后,返回的Promise将会被resolve
|
||||
* @returns 加载的Promise
|
||||
*/
|
||||
async load(): Promise<ResourceType[T]> {
|
||||
if (this.loadingStarted) {
|
||||
logger.warn(2, this.resource.type, this.resource.uri);
|
||||
return new Promise<void>(res => res());
|
||||
}
|
||||
this.loadingStarted = true;
|
||||
let totalByte = 0;
|
||||
const load = this.resource
|
||||
.load((now, total) => {
|
||||
this.loading = true;
|
||||
this.emit('progress', this.type, this.uri, now, total);
|
||||
if (!LoadTask.caledTask.has(this.uri) && total !== 0) {
|
||||
LoadTask.totalByte += total;
|
||||
totalByte = total;
|
||||
LoadTask.caledTask.add(this.uri);
|
||||
}
|
||||
this.loaded = now;
|
||||
})
|
||||
.catch(() => {
|
||||
LoadTask.errorTask++;
|
||||
logger.error(2, this.resource.type, this.resource.uri);
|
||||
});
|
||||
this.emit('loadStart', this.resource);
|
||||
const value = await load;
|
||||
LoadTask.loadedTaskList.add(this);
|
||||
this.loaded = totalByte;
|
||||
LoadTask.loadedTask++;
|
||||
await Promise.all(this.emit('load', this.resource));
|
||||
return await value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建一个加载任务,同时将任务加入加载列表
|
||||
* @param type 任务类型
|
||||
* @param uri 加载内容的URI
|
||||
*/
|
||||
static add<T extends keyof ResourceType>(
|
||||
type: T,
|
||||
uri: string
|
||||
): LoadTask<T> {
|
||||
const task = new LoadTask(type, uri);
|
||||
this.taskList.add(task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一个加载任务加入加载列表
|
||||
* @param task 要加入列表的任务
|
||||
*/
|
||||
static addTask(task: LoadTask) {
|
||||
this.taskList.add(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行所有加载
|
||||
*/
|
||||
static async load() {
|
||||
this.totalTask = this.taskList.size;
|
||||
const fn = () => {
|
||||
this.loadedByte = [...this.taskList].reduce((prev, curr) => {
|
||||
return prev + curr.loaded;
|
||||
}, 0);
|
||||
this.progress?.(
|
||||
this.loadedByte,
|
||||
this.totalByte,
|
||||
this.loadedTask,
|
||||
this.totalTask
|
||||
);
|
||||
};
|
||||
fn();
|
||||
const interval = window.setInterval(fn, 100);
|
||||
const data = await Promise.all([...this.taskList].map(v => v.load()));
|
||||
window.clearInterval(interval);
|
||||
this.loadedByte = this.totalByte;
|
||||
fn();
|
||||
this.progress?.(
|
||||
this.totalByte,
|
||||
this.totalByte,
|
||||
this.totalTask,
|
||||
this.totalTask
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当加载进度改变时执行的函数
|
||||
*/
|
||||
static onProgress(progress: TaskProgressFn) {
|
||||
this.progress = progress;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置加载设置
|
||||
*/
|
||||
static reset() {
|
||||
this.loadedByte = 0;
|
||||
this.loadedTask = 0;
|
||||
this.totalByte = 0;
|
||||
this.totalTask = 0;
|
||||
this.errorTask = 0;
|
||||
this.caledTask.clear();
|
||||
this.taskList.clear();
|
||||
}
|
||||
}
|
||||
|
||||
export function loadDefaultResource() {
|
||||
const data = data_a1e2fb4a_e986_4524_b0da_9b7ba7c0874d;
|
||||
const icon = icons_4665ee12_3a1f_44a4_bea3_0fccba634dc1;
|
||||
// bgm
|
||||
// data.main.bgms.forEach(v => {
|
||||
// const res = LoadTask.add('audio', `audio/${v}`);
|
||||
// Mota.r(() => {
|
||||
// res.once('loadStart', res => {
|
||||
// Mota.require('var', 'bgm').add(`bgms.${v}`, res.resource!);
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
// fonts
|
||||
data.main.fonts.forEach(v => {
|
||||
const res = LoadTask.add('buffer', `buffer/project/fonts/${v}.ttf`);
|
||||
Mota.r(() => {
|
||||
res.once('load', res => {
|
||||
document.fonts.add(new FontFace(v, res.resource!));
|
||||
});
|
||||
});
|
||||
});
|
||||
// image
|
||||
data.main.images.forEach(v => {
|
||||
const res = LoadTask.add('image', `image/project/images/${v}`);
|
||||
res.once('load', res => {
|
||||
core.material.images.images[v] = res.resource!;
|
||||
});
|
||||
});
|
||||
// sound
|
||||
data.main.sounds.forEach(v => {
|
||||
const res = LoadTask.add('byte', `byte/project/sounds/${v}`);
|
||||
Mota.r(() => {
|
||||
res.once('load', res => {
|
||||
const { soundPlayer } = Mota.require('@user/client-base');
|
||||
soundPlayer.add(v, res.resource!);
|
||||
});
|
||||
});
|
||||
});
|
||||
// tileset
|
||||
data.main.tilesets.forEach(v => {
|
||||
const res = LoadTask.add('image', `image/project/tilesets/${v}`);
|
||||
res.once('load', res => {
|
||||
core.material.images.tilesets[v] = res.resource!;
|
||||
});
|
||||
});
|
||||
// autotile
|
||||
const autotiles: Partial<Record<AllIdsOf<'autotile'>, HTMLImageElement>> =
|
||||
{};
|
||||
Object.keys(icon.autotile).forEach(v => {
|
||||
const res = LoadTask.add('image', `image/project/autotiles/${v}.png`);
|
||||
res.once('load', res => {
|
||||
autotiles[v as AllIdsOf<'autotile'>] = res.resource;
|
||||
const { loading } = Mota.require('@user/data-base');
|
||||
loading.addAutotileLoaded();
|
||||
loading.onAutotileLoaded(autotiles);
|
||||
core.material.images.autotile[v as AllIdsOf<'autotile'>] =
|
||||
res.resource!;
|
||||
});
|
||||
});
|
||||
// materials
|
||||
const imgs = core.materials.slice() as SelectKey<
|
||||
MaterialImages,
|
||||
HTMLImageElement
|
||||
>[];
|
||||
imgs.push('keyboard');
|
||||
core.materials
|
||||
.map(v => `${v}.png`)
|
||||
.forEach(v => {
|
||||
const res = LoadTask.add('material', `material/${v}`);
|
||||
res.once('load', res => {
|
||||
// @ts-expect-error 不能推导
|
||||
core.material.images[
|
||||
v.slice(0, -4) as SelectKey<
|
||||
MaterialImages,
|
||||
HTMLImageElement
|
||||
>
|
||||
] = res.resource;
|
||||
});
|
||||
});
|
||||
// animates
|
||||
{
|
||||
const res = LoadTask.add(
|
||||
'text',
|
||||
`text/all/__all_animates__?v=${
|
||||
main.version
|
||||
}&id=${data.main.animates.join(',')}`
|
||||
);
|
||||
res.once('load', res => {
|
||||
const data = res.resource!.split('@@@~~~###~~~@@@');
|
||||
data.forEach((v, i) => {
|
||||
const id = main.animates[i];
|
||||
if (v === '') {
|
||||
throw new Error(`Cannot find animate: '${id}'`);
|
||||
}
|
||||
core.material.animates[id] = core.loader._loadAnimate(v);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadCompressedResource() {
|
||||
const data = await axios.get(toURL('loadList.json'), {
|
||||
responseType: 'text'
|
||||
});
|
||||
const list: CompressedLoadList = JSON.parse(data.data);
|
||||
|
||||
// 对于区域内容,按照zip格式进行加载,然后解压处理
|
||||
const autotiles: Partial<Record<AllIdsOf<'autotile'>, HTMLImageElement>> =
|
||||
{};
|
||||
const materialImages = core.materials.slice() as SelectKey<
|
||||
MaterialImages,
|
||||
HTMLImageElement
|
||||
>[];
|
||||
materialImages.push('keyboard');
|
||||
|
||||
Object.entries(list).forEach(v => {
|
||||
const [uri, list] = v;
|
||||
const res = LoadTask.add('zip', `zip/${uri}`);
|
||||
|
||||
res.once('load', resource => {
|
||||
const res = resource.resource;
|
||||
if (!res) return;
|
||||
return Promise.all(
|
||||
list.map(async v => {
|
||||
const { type, name, usage } = v;
|
||||
const asyncType = types[type];
|
||||
const value = await res
|
||||
.file(`${type}/${name}`)
|
||||
?.async(asyncType);
|
||||
|
||||
if (!value) return;
|
||||
|
||||
// 图片类型的资源
|
||||
if (type === 'image') {
|
||||
const img = value as Blob;
|
||||
const image = new Image();
|
||||
image.src = URL.createObjectURL(img);
|
||||
image.addEventListener('load', () => {
|
||||
image.setAttribute(
|
||||
'_width',
|
||||
image.width.toString()
|
||||
);
|
||||
image.setAttribute(
|
||||
'_height',
|
||||
image.height.toString()
|
||||
);
|
||||
});
|
||||
|
||||
// 图片
|
||||
if (usage === 'image') {
|
||||
core.material.images.images[name as ImageIds] =
|
||||
image;
|
||||
} else if (usage === 'tileset') {
|
||||
// 额外素材
|
||||
core.material.images.tilesets[name] = image;
|
||||
} else if (usage === 'autotile') {
|
||||
// 自动元件
|
||||
autotiles[
|
||||
name.slice(0, -4) as AllIdsOf<'autotile'>
|
||||
] = image;
|
||||
const { loading } = Mota.require('@user/data-base');
|
||||
loading.addAutotileLoaded();
|
||||
loading.onAutotileLoaded(autotiles);
|
||||
core.material.images.autotile[
|
||||
name.slice(0, -4) as AllIdsOf<'autotile'>
|
||||
] = image;
|
||||
}
|
||||
} else if (type === 'material') {
|
||||
const img = value as Blob;
|
||||
const image = new Image();
|
||||
image.src = URL.createObjectURL(img);
|
||||
image.addEventListener('load', () => {
|
||||
image.setAttribute(
|
||||
'_width',
|
||||
image.width.toString()
|
||||
);
|
||||
image.setAttribute(
|
||||
'_height',
|
||||
image.height.toString()
|
||||
);
|
||||
});
|
||||
|
||||
// material
|
||||
if (materialImages.some(v => name === v + '.png')) {
|
||||
core.material.images[
|
||||
name.slice(0, -4) as SelectKey<
|
||||
MaterialImages,
|
||||
HTMLImageElement
|
||||
>
|
||||
] = image;
|
||||
}
|
||||
}
|
||||
|
||||
if (usage === 'font') {
|
||||
const font = value as ArrayBuffer;
|
||||
document.fonts.add(
|
||||
new FontFace(name.slice(0, -4), font)
|
||||
);
|
||||
} else if (usage === 'sound' && main.mode === 'play') {
|
||||
const { soundPlayer } =
|
||||
Mota.require('@user/client-base');
|
||||
soundPlayer.add(name as SoundIds, value as Uint8Array);
|
||||
} else if (usage === 'animate') {
|
||||
const ani = value as string;
|
||||
core.material.animates[
|
||||
name.slice(0, -8) as AnimationIds
|
||||
] = core.loader._loadAnimate(ani);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { isMobile } from '../use';
|
||||
import { MotaSetting } from '../setting';
|
||||
import { triggerFullscreen } from '../utils';
|
||||
import settingsText from '../data/settings.json';
|
||||
import { fixedUi, mainUi } from './uiIns';
|
||||
import { mainUi } from './uiIns';
|
||||
import { mainSetting } from './settingIns';
|
||||
|
||||
//#region legacy-ui
|
||||
@@ -13,8 +13,6 @@ export function createUI() {
|
||||
const { hook } = Mota.require('@user/data-base');
|
||||
hook.once('mounted', () => {
|
||||
const ui = document.getElementById('ui-main')!;
|
||||
const fixed = document.getElementById('ui-fixed')!;
|
||||
|
||||
const blur = mainSetting.getSetting('screen.blur');
|
||||
|
||||
mainUi.on('start', () => {
|
||||
@@ -34,12 +32,6 @@ export function createUI() {
|
||||
core.closePanel();
|
||||
}
|
||||
});
|
||||
fixedUi.on('start', () => {
|
||||
fixed.style.display = 'block';
|
||||
});
|
||||
fixedUi.on('end', () => {
|
||||
fixed.style.display = 'none';
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -123,21 +115,11 @@ function handleAudioSetting<T extends number | boolean>(
|
||||
}
|
||||
}
|
||||
|
||||
function handleUiSetting<T extends number | boolean>(key: string, n: T, _o: T) {
|
||||
if (key === 'danmaku') {
|
||||
if (n) {
|
||||
fixedUi.open('danmaku');
|
||||
} else {
|
||||
fixedUi.closeByName('danmaku');
|
||||
}
|
||||
} else if (key === 'tips') {
|
||||
if (n && core.isPlaying()) {
|
||||
fixedUi.open('tips');
|
||||
} else {
|
||||
fixedUi.closeByName('tips');
|
||||
}
|
||||
}
|
||||
}
|
||||
function handleUiSetting<T extends number | boolean>(
|
||||
_key: string,
|
||||
_n: T,
|
||||
_o: T
|
||||
) {}
|
||||
|
||||
// ----- 游戏的所有设置项
|
||||
mainSetting
|
||||
|
||||
@@ -14,7 +14,3 @@ mainUi.register(
|
||||
new GameUi('virtualKey', VirtualKey)
|
||||
);
|
||||
mainUi.showAll();
|
||||
|
||||
export const fixedUi = new UiController(true);
|
||||
fixedUi.register(new GameUi('load', UI.Load));
|
||||
fixedUi.showAll();
|
||||
@@ -6,4 +6,3 @@ export { default as Settings } from './settings.vue';
|
||||
export { default as Shop } from './shop.vue';
|
||||
export { default as Toolbox } from './toolbox.vue';
|
||||
export { default as Hotkey } from './hotkey.vue';
|
||||
export { default as Load } from './load.vue';
|
||||
@@ -1,106 +0,0 @@
|
||||
<template>
|
||||
<div id="load">
|
||||
<Progress
|
||||
class="task-progress"
|
||||
type="circle"
|
||||
:percent="(loading / totalTask) * 100"
|
||||
:success="{ percent: (loaded / totalTask) * 100 }"
|
||||
>
|
||||
<template #format>
|
||||
<span>{{ loaded }} / {{ totalTask }}</span>
|
||||
</template>
|
||||
</Progress>
|
||||
<div class="byte-div">
|
||||
<span class="byte-progress-tip"
|
||||
>{{ formatSize(loadedByte) }} /
|
||||
{{ formatSize(totalByte) }}</span
|
||||
>
|
||||
<Progress
|
||||
class="byte-progress"
|
||||
type="line"
|
||||
:percent="loadedPercent"
|
||||
></Progress>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, ref } from 'vue';
|
||||
import {
|
||||
loadCompressedResource,
|
||||
loadDefaultResource,
|
||||
LoadTask
|
||||
} from '@motajs/legacy-common';
|
||||
import { formatSize } from '../utils';
|
||||
import { logger } from '@motajs/common';
|
||||
import { sleep } from 'mutate-animate';
|
||||
import { IMountedVBind } from '../interface';
|
||||
import { Progress } from 'ant-design-vue';
|
||||
|
||||
const props = defineProps<IMountedVBind>();
|
||||
|
||||
const loading = ref(0);
|
||||
const loaded = ref(0);
|
||||
const loadedByte = ref(0);
|
||||
const loadedPercent = ref(0);
|
||||
const totalByte = ref(0);
|
||||
const totalTask = ref(0);
|
||||
|
||||
let loadDiv: HTMLDivElement;
|
||||
|
||||
onMounted(async () => {
|
||||
if (import.meta.env.DEV) loadDefaultResource();
|
||||
else await loadCompressedResource();
|
||||
|
||||
LoadTask.onProgress(() => {
|
||||
const loadingNum = [...LoadTask.taskList].filter(v => v.loading).length;
|
||||
|
||||
loadedByte.value = LoadTask.loadedByte;
|
||||
loadedPercent.value = parseFloat(
|
||||
((LoadTask.loadedByte / LoadTask.totalByte) * 100).toFixed(2)
|
||||
);
|
||||
loading.value = loadingNum;
|
||||
loaded.value = LoadTask.loadedTask;
|
||||
totalByte.value = LoadTask.totalByte;
|
||||
totalTask.value = LoadTask.totalTask;
|
||||
});
|
||||
|
||||
LoadTask.load().then(async () => {
|
||||
core.loader._loadMaterials_afterLoad();
|
||||
core._afterLoadResources(props.callback);
|
||||
logger.log(`Resource load end.`);
|
||||
loadDiv.style.opacity = '0';
|
||||
await sleep(500);
|
||||
Mota.require('@user/data-base').loading.emit('loaded');
|
||||
await sleep(500);
|
||||
props.controller.close(props.num);
|
||||
});
|
||||
loadDiv = document.getElementById('load') as HTMLDivElement;
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
#load {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
font-family: 'Arial';
|
||||
transition: opacity 1s linear;
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
background-color: black;
|
||||
}
|
||||
|
||||
.byte-div {
|
||||
width: 50%;
|
||||
margin-top: 10vh;
|
||||
}
|
||||
|
||||
.byte-progress {
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -1 +1,4 @@
|
||||
export * from './progress';
|
||||
export * from './stream';
|
||||
export * from './task';
|
||||
export * from './types';
|
||||
@@ -0,0 +1,91 @@
|
||||
import { clamp } from 'lodash-es';
|
||||
import { ILoadProgressTotal, ILoadTask, LoadDataType } from './types';
|
||||
import { logger } from '@motajs/common';
|
||||
|
||||
export class LoadProgressTotal<
|
||||
T extends LoadDataType = LoadDataType,
|
||||
R = any
|
||||
> implements ILoadProgressTotal<T, R> {
|
||||
/** 当前已经附着的加载任务 */
|
||||
private readonly attached: Map<ILoadTask<T, R>, number> = new Map();
|
||||
/** 当前已经加载完毕的任务 */
|
||||
readonly loadedTasks: Set<ILoadTask<T, R>> = new Set();
|
||||
/** 当前已经添加的任务 */
|
||||
readonly addedTasks: Set<ILoadTask<T, R>> = new Set();
|
||||
|
||||
/** 总加载量 */
|
||||
private total: number = 0;
|
||||
/** 当前已经加载的字节数 */
|
||||
private loaded: number = 0;
|
||||
|
||||
/** 下一次触发 `onProgress` 时兑现 */
|
||||
private nextPromise: Promise<void>;
|
||||
/** 兑现当前的 `nextPromise` */
|
||||
private nextResolve: () => void;
|
||||
|
||||
async *[Symbol.asyncIterator]() {
|
||||
while (true) {
|
||||
if (this.loadedTasks.size === this.addedTasks.size) {
|
||||
return;
|
||||
}
|
||||
yield this.nextPromise;
|
||||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
this.nextPromise = promise;
|
||||
this.nextResolve = resolve;
|
||||
}
|
||||
|
||||
addTask(task: ILoadTask<T, R>) {
|
||||
this.addedTasks.add(task);
|
||||
}
|
||||
|
||||
onProgress(task: ILoadTask<T, R>, loaded: number, total: number): void {
|
||||
if (!this.addedTasks.has(task)) {
|
||||
logger.warn(95);
|
||||
return;
|
||||
}
|
||||
if (!this.attached.has(task)) {
|
||||
this.total += total;
|
||||
}
|
||||
if (task.contentLoaded) {
|
||||
this.loadedTasks.add(task);
|
||||
}
|
||||
const before = this.attached.getOrInsert(task, 0);
|
||||
if (total !== 0) {
|
||||
this.loaded += loaded - before;
|
||||
}
|
||||
this.attached.set(task, loaded);
|
||||
this.nextResolve();
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
this.nextPromise = promise;
|
||||
this.nextResolve = resolve;
|
||||
}
|
||||
|
||||
getLoadedByte(): number {
|
||||
return this.loaded;
|
||||
}
|
||||
|
||||
getTotalByte(): number {
|
||||
return this.loaded;
|
||||
}
|
||||
|
||||
getLoadedTasks(): number {
|
||||
return this.loadedTasks.size;
|
||||
}
|
||||
|
||||
getAddedTasks(): number {
|
||||
return this.addedTasks.size;
|
||||
}
|
||||
|
||||
getTaskRatio(): number {
|
||||
return this.loadedTasks.size / this.addedTasks.size;
|
||||
}
|
||||
|
||||
getByteRatio(): number {
|
||||
if (this.total === 0) return 0;
|
||||
return clamp(this.loaded / this.total, 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -1,76 +1,15 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { IStreamLoader, IStreamReader } from './types';
|
||||
|
||||
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>
|
||||
{
|
||||
export class StreamLoader implements IStreamLoader {
|
||||
/** 传输目标 */
|
||||
private target: Set<IStreamReader> = new Set();
|
||||
/** 读取流对象 */
|
||||
private stream?: ReadableStream;
|
||||
private stream: ReadableStream | null = null;
|
||||
|
||||
loading: boolean = false;
|
||||
|
||||
constructor(public readonly url: string) {
|
||||
super();
|
||||
}
|
||||
constructor(public readonly url: string) {}
|
||||
|
||||
/**
|
||||
* 将加载流传递给字节流读取对象
|
||||
@@ -83,7 +22,14 @@ export class StreamLoader
|
||||
}
|
||||
this.target.add(reader);
|
||||
reader.piped(this);
|
||||
return this;
|
||||
}
|
||||
|
||||
unpipe(reader: IStreamReader): void {
|
||||
if (this.loading) {
|
||||
logger.warn(46);
|
||||
return;
|
||||
}
|
||||
this.target.delete(reader);
|
||||
}
|
||||
|
||||
async start() {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { sumBy } from 'lodash-es';
|
||||
import {
|
||||
ILoadDataTypeMap,
|
||||
ILoadTask,
|
||||
ILoadTaskInit,
|
||||
ILoadTaskProcessor,
|
||||
ILoadTaskProgress,
|
||||
LoadDataType,
|
||||
RequestMethod
|
||||
} from './types';
|
||||
|
||||
/** 文字解码 */
|
||||
const loadTextDecoder = new TextDecoder();
|
||||
|
||||
export class LoadTask<T extends LoadDataType, R> implements ILoadTask<T, R> {
|
||||
readonly dataType: T;
|
||||
readonly identifier: string;
|
||||
readonly url: string | URL;
|
||||
readonly processor: ILoadTaskProcessor<T, R>;
|
||||
readonly progress: ILoadTaskProgress<T, R>;
|
||||
readonly method?: RequestMethod;
|
||||
readonly body?: BodyInit;
|
||||
readonly headers?: HeadersInit;
|
||||
|
||||
contentLoaded: boolean = false;
|
||||
loadedByte: number = 0;
|
||||
totalByte: number = 0;
|
||||
|
||||
/** 加载的 `Promise` */
|
||||
private readonly loadPromise: Promise<R>;
|
||||
/** 兑现加载对象 */
|
||||
private readonly loadResolve: (data: R) => void;
|
||||
|
||||
/** 加载结果 */
|
||||
private loadedData: R | null = null;
|
||||
|
||||
constructor(init: ILoadTaskInit<T, R>) {
|
||||
this.dataType = init.dataType;
|
||||
this.identifier = init.identifier;
|
||||
this.url = this.resolveURL(init.url);
|
||||
this.processor = init.processor;
|
||||
this.progress = init.progress;
|
||||
this.method = init.method;
|
||||
this.body = init.body;
|
||||
this.headers = init.headers;
|
||||
|
||||
const { promise, resolve } = Promise.withResolvers<R>();
|
||||
this.loadPromise = promise;
|
||||
this.loadResolve = resolve;
|
||||
}
|
||||
|
||||
private resolveURL(url: string | URL) {
|
||||
if (typeof url === 'string') {
|
||||
return `${import.meta.env.BASE_URL}${url}`;
|
||||
} else {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
private processUnstreamableResponse(
|
||||
response: Response
|
||||
): Promise<ILoadDataTypeMap[T]> {
|
||||
switch (this.dataType) {
|
||||
case LoadDataType.ArrayBuffer:
|
||||
return response.arrayBuffer();
|
||||
case LoadDataType.Blob:
|
||||
return response.blob();
|
||||
case LoadDataType.JSON:
|
||||
return response.json();
|
||||
case LoadDataType.Text:
|
||||
return response.text();
|
||||
case LoadDataType.Uint8Array:
|
||||
return response.bytes();
|
||||
}
|
||||
}
|
||||
|
||||
private processStreamChunkResponse(
|
||||
chunks: Uint8Array<ArrayBuffer>[]
|
||||
): ILoadDataTypeMap[T] {
|
||||
if (this.dataType === LoadDataType.Blob) {
|
||||
return new Blob(chunks);
|
||||
}
|
||||
const totalLength = sumBy(chunks, value => value.length);
|
||||
const stacked: Uint8Array<ArrayBuffer> = new Uint8Array(totalLength);
|
||||
let offset = 0;
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
stacked.set(chunks[i], offset);
|
||||
offset += chunks[i].length;
|
||||
}
|
||||
switch (this.dataType) {
|
||||
case LoadDataType.ArrayBuffer:
|
||||
return stacked.buffer;
|
||||
case LoadDataType.Uint8Array:
|
||||
return stacked;
|
||||
}
|
||||
const text = loadTextDecoder.decode(stacked);
|
||||
switch (this.dataType) {
|
||||
case LoadDataType.Text:
|
||||
return text;
|
||||
case LoadDataType.JSON:
|
||||
return JSON.parse(text);
|
||||
}
|
||||
}
|
||||
|
||||
private async processResponse(response: Response) {
|
||||
const reader = response.body?.getReader();
|
||||
const contentLength = response.headers.get('Content-Length') ?? '0';
|
||||
const total = parseInt(contentLength, 10);
|
||||
this.loadedByte = 0;
|
||||
this.totalByte = total;
|
||||
this.progress.onProgress(this, 0, total);
|
||||
if (!reader) {
|
||||
const data = await this.processUnstreamableResponse(response);
|
||||
this.loadedByte = this.totalByte;
|
||||
this.contentLoaded = true;
|
||||
this.progress.onProgress(this, this.loadedByte, this.totalByte);
|
||||
const processed = await this.processor.process(data, this);
|
||||
this.loadedData = processed;
|
||||
this.loadResolve(processed);
|
||||
return;
|
||||
}
|
||||
let received = 0;
|
||||
const chunks: Uint8Array<ArrayBuffer>[] = [];
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
received += value.byteLength;
|
||||
}
|
||||
if (done) this.contentLoaded = true;
|
||||
this.loadedByte = received;
|
||||
this.progress.onProgress(this, received, total);
|
||||
if (done) break;
|
||||
}
|
||||
const data = this.processStreamChunkResponse(chunks);
|
||||
const processed = await this.processor.process(data, this);
|
||||
this.loadedData = processed;
|
||||
this.loadResolve(processed);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const response = await fetch(this.url, {
|
||||
method: this.method,
|
||||
body: this.body,
|
||||
headers: this.headers
|
||||
});
|
||||
this.processResponse(response);
|
||||
return;
|
||||
}
|
||||
|
||||
loaded(): Promise<R> {
|
||||
return this.loadPromise;
|
||||
}
|
||||
|
||||
getLoadedData(): R | null {
|
||||
return this.loadedData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//#region 流传输
|
||||
|
||||
export interface IStreamController {
|
||||
/** 当前是否正在加载 */
|
||||
readonly loading: boolean;
|
||||
|
||||
/**
|
||||
* 开始流传输
|
||||
*/
|
||||
start(): Promise<void>;
|
||||
|
||||
/**
|
||||
* 主动终止流传输
|
||||
* @param reason 终止原因
|
||||
*/
|
||||
cancel(reason?: string): void;
|
||||
}
|
||||
|
||||
export interface IStreamReader {
|
||||
/**
|
||||
* 接受字节流流传输的数据
|
||||
* @param data 传入的字节流数据,只包含本分块的内容
|
||||
* @param done 是否传输完成
|
||||
*/
|
||||
pump(
|
||||
data: Uint8Array | undefined,
|
||||
done: boolean,
|
||||
response: Response
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* 当前对象被传递给加载流时执行的函数
|
||||
* @param controller 传输流控制对象
|
||||
*/
|
||||
piped(controller: IStreamController): void;
|
||||
|
||||
/**
|
||||
* 当前对象取消指定加载流传输时执行的函数
|
||||
* @param controller 传输流控制对象
|
||||
*/
|
||||
unpiped(controller: IStreamController): void;
|
||||
|
||||
/**
|
||||
* 开始流传输
|
||||
* @param stream 传输流对象
|
||||
* @param controller 传输流控制对象
|
||||
*/
|
||||
start(
|
||||
stream: ReadableStream,
|
||||
controller: IStreamController,
|
||||
response: Response
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* 结束流传输
|
||||
* @param done 是否传输完成,如果为 false 的话,说明可能是由于出现错误导致的终止
|
||||
* @param reason 如果没有传输完成,那么表示失败的原因
|
||||
*/
|
||||
end(done: boolean, reason?: string): void;
|
||||
}
|
||||
|
||||
export interface IStreamLoader extends IStreamController {
|
||||
/**
|
||||
* 将加载流传递给字节流读取对象
|
||||
* @param reader 字节流读取对象
|
||||
*/
|
||||
pipe(reader: IStreamReader): void;
|
||||
|
||||
/**
|
||||
* 取消一个字节流读取对象的绑定
|
||||
* @param reader 字节流读取对象
|
||||
*/
|
||||
unpipe(reader: IStreamReader): void;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
|
||||
//#region 加载任务
|
||||
|
||||
export const enum LoadDataType {
|
||||
ArrayBuffer,
|
||||
Uint8Array,
|
||||
Blob,
|
||||
Text,
|
||||
JSON
|
||||
}
|
||||
|
||||
export interface ILoadDataTypeMap {
|
||||
[LoadDataType.ArrayBuffer]: ArrayBuffer;
|
||||
[LoadDataType.Uint8Array]: Uint8Array<ArrayBuffer>;
|
||||
[LoadDataType.Blob]: Blob;
|
||||
[LoadDataType.Text]: string;
|
||||
[LoadDataType.JSON]: any;
|
||||
}
|
||||
|
||||
export interface ILoadTaskProcessor<T extends LoadDataType, R> {
|
||||
/**
|
||||
* 处理加载内容
|
||||
* @param response 处理前加载结果
|
||||
* @param task 加载任务对象
|
||||
*/
|
||||
process(response: ILoadDataTypeMap[T], task: ILoadTask<T, R>): Promise<R>;
|
||||
}
|
||||
|
||||
export interface ILoadTaskProgress<T extends LoadDataType, R> {
|
||||
/**
|
||||
* 更新加载进度
|
||||
* @param task 加载任务对象
|
||||
* @param loaded 已加载的字节数
|
||||
* @param total 文件总计字节数,如果此值为零说明无法读取到 `Content-Length`
|
||||
*/
|
||||
onProgress(task: ILoadTask<T, R>, loaded: number, total: number): void;
|
||||
}
|
||||
|
||||
export const enum RequestMethod {
|
||||
GET = 'GET',
|
||||
POST = 'POST',
|
||||
HEAD = 'HEAD',
|
||||
PUT = 'PUT',
|
||||
DELETE = 'DELETE',
|
||||
CONNECT = 'CONNECT',
|
||||
OPTIONS = 'OPTIONS',
|
||||
TRACE = 'TRACE',
|
||||
PATCH = 'PATCH'
|
||||
}
|
||||
|
||||
export interface ILoadTaskInit<T extends LoadDataType, R> {
|
||||
/** 请求响应格式 */
|
||||
readonly dataType: T;
|
||||
/** 加载任务标识符 */
|
||||
readonly identifier: string;
|
||||
/** 加载目标 URL */
|
||||
readonly url: string | URL;
|
||||
/** 加载的处理对象,用于处理加载结果等 */
|
||||
readonly processor: ILoadTaskProcessor<T, R>;
|
||||
/** 加载进度对象,用于监控加载进度 */
|
||||
readonly progress: ILoadTaskProgress<T, R>;
|
||||
/** 请求模式 */
|
||||
readonly method?: RequestMethod;
|
||||
/** 请求体 */
|
||||
readonly body?: BodyInit;
|
||||
/** 请求头 */
|
||||
readonly headers?: HeadersInit;
|
||||
}
|
||||
|
||||
export interface ILoadTask<T extends LoadDataType, R> extends ILoadTaskInit<
|
||||
T,
|
||||
R
|
||||
> {
|
||||
/** 当前是否加载完毕 */
|
||||
readonly contentLoaded: boolean;
|
||||
/** 已经加载的字节数 */
|
||||
readonly loadedByte: number;
|
||||
/** 该加载任务的总体字节数 */
|
||||
readonly totalByte: number;
|
||||
|
||||
/**
|
||||
* 开始此加载计划,返回一个 `Promise`,当得到服务器的响应后兑现
|
||||
*/
|
||||
start(): Promise<void>;
|
||||
|
||||
/**
|
||||
* 返回一个 `Promise`,当本计划加载完毕后兑现,兑现结果是加载结果
|
||||
*/
|
||||
loaded(): Promise<R>;
|
||||
|
||||
/**
|
||||
* 获取加载完成后的加载结果
|
||||
*/
|
||||
getLoadedData(): R | null;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
|
||||
//#region 内置组件
|
||||
|
||||
export interface ILoadProgressTotal<
|
||||
T extends LoadDataType = LoadDataType,
|
||||
R = any
|
||||
> extends ILoadTaskProgress<T, R> {
|
||||
/** 已经添加的加载任务对象 */
|
||||
readonly addedTasks: Set<ILoadTask<T, R>>;
|
||||
/** 当前已经加载完毕的任务对象 */
|
||||
readonly loadedTasks: Set<ILoadTask<T, R>>;
|
||||
|
||||
/**
|
||||
* 迭代加载进度,当 `yield` 的值被兑现时,说明加载进度更新
|
||||
*/
|
||||
[Symbol.asyncIterator](): AsyncGenerator<void, void, void>;
|
||||
|
||||
/**
|
||||
* 向该进度监听器添加加载任务对象
|
||||
* @param task 加载任务对象
|
||||
*/
|
||||
addTask(task: ILoadTask<T, R>): void;
|
||||
|
||||
/**
|
||||
* 获取总体已加载的字节数
|
||||
*/
|
||||
getLoadedByte(): number;
|
||||
|
||||
/**
|
||||
* 获取总体需要加载的字节数
|
||||
*/
|
||||
getTotalByte(): number;
|
||||
|
||||
/**
|
||||
* 获取已经加载的字节数与总体需要加载的字节数之比
|
||||
*/
|
||||
getByteRatio(): number;
|
||||
|
||||
/**
|
||||
* 获取已经加载完毕的加载任务数量
|
||||
*/
|
||||
getLoadedTasks(): number;
|
||||
|
||||
/**
|
||||
* 获取此进度监听器已经添加的加载任务对象
|
||||
*/
|
||||
getAddedTasks(): number;
|
||||
|
||||
/**
|
||||
* 获取已经加载完毕的任务数量与已添加的加载任务数量之比
|
||||
*/
|
||||
getTaskRatio(): number;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
@@ -16,8 +16,10 @@ import {
|
||||
LineParams,
|
||||
QuadParams,
|
||||
RectRCircleParams,
|
||||
RectREllipseParams
|
||||
RectREllipseParams,
|
||||
ITexture
|
||||
} from '@motajs/render';
|
||||
import { Ref } from 'vue';
|
||||
|
||||
export interface BaseProps {
|
||||
/** 元素的横坐标 */
|
||||
@@ -81,6 +83,8 @@ export interface BaseProps {
|
||||
export interface CustomProps extends BaseProps {
|
||||
/** 自定义的渲染函数 */
|
||||
render?: CustomRenderFunction;
|
||||
/** 更新绑定,当数组中的任意一项更新时将会自动更新此元素的渲染 */
|
||||
bindings?: Ref<any>[];
|
||||
}
|
||||
|
||||
export interface ContainerProps extends BaseProps {}
|
||||
@@ -111,7 +115,7 @@ export interface TextProps extends BaseProps {
|
||||
|
||||
export interface ImageProps extends BaseProps {
|
||||
/** 图片对象 */
|
||||
image: CanvasImageSource;
|
||||
image?: ITexture | null;
|
||||
}
|
||||
|
||||
export interface CommentProps extends BaseProps {
|
||||
|
||||
@@ -9,13 +9,15 @@ import {
|
||||
Image,
|
||||
IRenderItem,
|
||||
IRenderTreeRoot,
|
||||
ITexture,
|
||||
Line,
|
||||
Path,
|
||||
QuadraticCurve,
|
||||
Rect,
|
||||
RectR,
|
||||
Shader,
|
||||
Text
|
||||
Text,
|
||||
Texture
|
||||
} from '@motajs/render';
|
||||
import { IRenderTagInfo, IRenderTagManager, TagCreateFunction } from './types';
|
||||
import { logger } from '@motajs/common';
|
||||
@@ -24,13 +26,13 @@ export class RenderTagManager implements IRenderTagManager {
|
||||
/** 标签注册映射 */
|
||||
private readonly tagRegistry: Map<string, IRenderTagInfo> = new Map();
|
||||
/** 空图片 */
|
||||
private readonly emptyImg: HTMLCanvasElement;
|
||||
private readonly emptyImg: ITexture;
|
||||
|
||||
constructor(readonly renderer: IRenderTreeRoot) {
|
||||
const emptyImage = document.createElement('canvas');
|
||||
emptyImage.width = 1;
|
||||
emptyImage.height = 1;
|
||||
this.emptyImg = emptyImage;
|
||||
this.emptyImg = new Texture(emptyImage);
|
||||
|
||||
this.resgiterIntrinsicTags();
|
||||
}
|
||||
@@ -52,17 +54,7 @@ export class RenderTagManager implements IRenderTagManager {
|
||||
const { text = '', nocache = true, cache = false } = props;
|
||||
return this.renderer.createElement(Text, text, cache && !nocache);
|
||||
});
|
||||
this.registerTag('image', props => {
|
||||
if (!props) {
|
||||
return this.renderer.createElement(Image, this.emptyImg, false);
|
||||
}
|
||||
const {
|
||||
image = this.emptyImg,
|
||||
nocache = true,
|
||||
cache = false
|
||||
} = props;
|
||||
return this.renderer.createElement(Image, image, cache && !nocache);
|
||||
});
|
||||
this.registerTag('image', this.createStandardElement(false, Image));
|
||||
this.registerTag('shader', this.createNoParamElement(Shader));
|
||||
this.registerTag('comment', props => {
|
||||
if (!props) return this.renderer.createElement(Comment);
|
||||
|
||||
@@ -2,9 +2,9 @@ import { isNil } from 'lodash-es';
|
||||
import { ITexture, ITextureStore } from './types';
|
||||
import { logger } from '@motajs/common';
|
||||
|
||||
export class TextureStore<T extends ITexture = ITexture>
|
||||
implements ITextureStore<T>
|
||||
{
|
||||
export class TextureStore<
|
||||
T extends ITexture = ITexture
|
||||
> implements ITextureStore<T> {
|
||||
private readonly texMap: Map<number, T> = new Map();
|
||||
private readonly invMap: Map<T, number> = new Map();
|
||||
private readonly aliasMap: Map<string, number> = new Map();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { RenderItem, Transform, MotaOffscreenCanvas2D } from '.';
|
||||
import { CanvasStyle } from '../types';
|
||||
import { Font } from '../style';
|
||||
import { IRenderImage, IRenderText } from './types';
|
||||
import { ITexture } from '../assets';
|
||||
|
||||
/** 文字的安全填充,会填充在文字的上侧和下侧,防止削顶和削底 */
|
||||
const SAFE_PAD = 1;
|
||||
@@ -147,31 +148,31 @@ export class Text extends RenderItem implements IRenderText {
|
||||
}
|
||||
|
||||
export class Image extends RenderItem implements IRenderImage {
|
||||
image: CanvasImageSource;
|
||||
image: ITexture | null;
|
||||
|
||||
constructor(image: CanvasImageSource, enableCache: boolean = false) {
|
||||
constructor(enableCache: boolean = false) {
|
||||
super(enableCache);
|
||||
this.image = image;
|
||||
if (image instanceof VideoFrame || image instanceof SVGElement) {
|
||||
this.size(200, 200);
|
||||
} else {
|
||||
this.size(image.width, image.height);
|
||||
}
|
||||
this.image = null;
|
||||
}
|
||||
|
||||
protected render(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
_transform: Transform
|
||||
): void {
|
||||
if (!this.image) return;
|
||||
const ctx = canvas.ctx;
|
||||
ctx.drawImage(this.image, 0, 0, this.width, this.height);
|
||||
const {
|
||||
source,
|
||||
rect: { x, y, w, h }
|
||||
} = this.image.render();
|
||||
ctx.drawImage(source, x, y, w, h, 0, 0, this.width, this.height);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置图片资源
|
||||
* @param image 图片资源
|
||||
*/
|
||||
setImage(image: CanvasImageSource) {
|
||||
setImage(image: ITexture | null) {
|
||||
this.image = image;
|
||||
this.update();
|
||||
}
|
||||
@@ -183,7 +184,8 @@ export class Image extends RenderItem implements IRenderImage {
|
||||
): boolean {
|
||||
switch (key) {
|
||||
case 'image':
|
||||
this.setImage(nextValue);
|
||||
if (!nextValue) this.setImage(null);
|
||||
else this.setImage(nextValue);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -12,6 +12,7 @@ import { DefineComponent, DefineSetupFnComponent } from 'vue';
|
||||
import { JSX } from 'vue/jsx-runtime';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { SizedCanvasImageSource } from '../types';
|
||||
import { ITexture } from '../assets';
|
||||
|
||||
//#region 功能类型
|
||||
|
||||
@@ -572,13 +573,13 @@ export interface IRenderText extends IRenderItem {
|
||||
|
||||
export interface IRenderImage extends IRenderItem {
|
||||
/** 当前元素的图片内容 */
|
||||
readonly image: CanvasImageSource;
|
||||
readonly image: ITexture | null;
|
||||
|
||||
/**
|
||||
* 设置图片资源
|
||||
* @param image 图片资源
|
||||
*/
|
||||
setImage(image: CanvasImageSource): void;
|
||||
setImage(image: ITexture): void;
|
||||
}
|
||||
|
||||
//#endregion
|
||||
|
||||
Reference in new issue
Block a user