refactor: 渲染端结构

This commit is contained in:
AncTe committed 2026-04-19 22:52:32 +08:00
1 parent ebae685a4e
commit 51e9d758d8
38 files changed
+290 -138

No files matched your search

+151
View File
@@ -0,0 +1,151 @@
import { ICoreState } from '@user/data-state';
import { IClientCore } from './types';
import {
IMotaAudioContext,
ISoundPlayer,
IBGMPlayer,
MotaAudioContext,
SoundPlayer,
BGMPlayer
} from '@motajs/audio';
import { IRenderTreeRoot, MotaRenderer } from '@motajs/render';
import {
IMotaAssetsLoader,
IMaterialManager,
IAutotileProcessor,
MotaAssetsLoader,
MaterialManager,
AutotileProcessor
} from '@user/client-base';
import {
IMapRenderer,
IMapExtensionManager,
MapRenderer,
MapExtensionManager
} from './render/map';
import {
ExcitationDivider,
ExcitationVariator,
IExcitation,
IExcitationDivider,
RafExcitation
} from '@motajs/animate';
import {
DEBUG_DIVIDER,
DEBUG_VARIATOR,
DIVIDER_DEBUG_DIVIDER,
MAIN_HEIGHT,
MAIN_WIDTH,
VARIATOR_DEBUG_SPEED
} from './shared';
import { loading } from '@user/data-base';
import { fallbackLoad } from './fallback/load';
export class ClientCore implements IClientCore {
readonly loader: IMotaAssetsLoader;
readonly materials: IMaterialManager;
readonly autotile: IAutotileProcessor;
readonly rafExcitation: IExcitation<number>;
readonly excitationDivider: IExcitationDivider<number>;
readonly renderer: IRenderTreeRoot;
readonly mainMapRenderer: IMapRenderer;
readonly mainMapExtension: IMapExtensionManager;
readonly audioContext: IMotaAudioContext;
readonly soundPlayer: ISoundPlayer<SoundIds>;
readonly bgmPlayer: IBGMPlayer<BgmIds>;
constructor(public data: ICoreState) {
//#region 音频系统
this.audioContext = new MotaAudioContext();
this.soundPlayer = new SoundPlayer(this.audioContext);
this.bgmPlayer = new BGMPlayer(this.audioContext);
//#endregion
//#region 素材系统
this.materials = new MaterialManager();
this.autotile = new AutotileProcessor(this.materials);
//#endregion
this.loader = new MotaAssetsLoader(
data.loadProgress,
data.dataLoader,
this.audioContext,
this.soundPlayer,
this.materials
);
// 兼容层
loading.once('loaded', () => {
fallbackLoad(this.materials);
loading.emit('assetBuilt');
});
//#region 渲染系统
const rafExcitation = new RafExcitation();
const excitationDivider = new ExcitationDivider<number>();
if (DEBUG_VARIATOR) {
const variator = new ExcitationVariator();
variator.bindExcitation(rafExcitation);
variator.setSpeed(VARIATOR_DEBUG_SPEED);
excitationDivider.bindExcitation(variator);
} else {
excitationDivider.bindExcitation(rafExcitation);
}
if (DEBUG_DIVIDER) {
excitationDivider.setDivider(DIVIDER_DEBUG_DIVIDER);
}
this.rafExcitation = rafExcitation;
this.excitationDivider = excitationDivider;
this.renderer = new MotaRenderer({
canvas: '#render-main',
width: MAIN_WIDTH,
height: MAIN_HEIGHT,
// 使用分频器,用户可以在设置中调整,如果设备性能较差调高分频有助于提高性能表现
excitaion: excitationDivider
});
this.mainMapRenderer = new MapRenderer(this.materials, data.layer);
this.mainMapExtension = new MapExtensionManager(this.mainMapRenderer);
// 兼容层
loading.once('assetBuilt', () => {
this.createMainExtension();
});
//#endregion
}
/**
* 进行地图渲染拓展初始化
*/
private async createMainExtension() {
// 算是一种妥协吧,等之后加载系统重构之后应该会清晰很多
await this.materials.trackedAsset.then();
this.mainMapRenderer.useAsset(this.materials.trackedAsset);
const layer = this.data.layer.getLayerByAlias('event');
if (layer) {
this.mainMapExtension.addHero(this.data.hero.mover, layer);
this.mainMapExtension.addDoor(layer);
}
this.mainMapExtension.addText();
}
bindDataState(state: ICoreState): void {
this.data = state;
}
getDataState(): ICoreState {
return this.data;
}
}
+5
View File
@@ -0,0 +1,5 @@
import { state } from '@user/data-state';
import { ClientCore } from './client';
/** 客户端实例 */
export const client = new ClientCore(state);
@@ -1,13 +1,14 @@
import { Patch, PatchClass } from '@motajs/legacy-common';
import { audioContext, bgmPlayer, soundPlayer } from '@user/client-base';
import { mainSetting } from '@motajs/legacy-ui';
import { sleep } from '@motajs/common';
import { isNil } from 'lodash-es';
import { client } from '../core';
// todo: 添加弃用警告 logger.warn(56)
export function patchAudio() {
const patch = new Patch(PatchClass.Control);
const { bgmPlayer, soundPlayer, audioContext } = client;
const play = (bgm: BgmIds, when?: number) => {
bgmPlayer.play(bgm, when);
@@ -28,8 +29,8 @@ export function patchAudio() {
patch.add('checkBgm', function () {
if (bgmPlayer.playing) return;
if (mainSetting.getValue('audio.bgmEnabled')) {
if (bgmPlayer.playingBgm) {
bgmPlayer.play(bgmPlayer.playingBgm);
if (bgmPlayer.playingBGM) {
bgmPlayer.play(bgmPlayer.playingBGM);
} else {
play(main.startBgm, 0);
}
@@ -0,0 +1,137 @@
import { ITexture } from '@motajs/render';
import {
IBlockIdentifier,
IMaterialManager,
IIndexedIdentifier
} from '@user/client-base';
import { isNil } from 'lodash-es';
function extractClsBlocks<C extends Exclude<Cls, 'tileset'>>(
cls: C,
map: Record<string, number>,
icons: Record<string, number>
): IBlockIdentifier[] {
const max = Math.max(...Object.values(icons));
const arr = Array(max).fill(void 0);
for (const [key, value] of Object.entries(icons)) {
// 样板编辑器 bug 可能会导致多个 id 使用一个偏移,因此要判断下
if (!(key in map) || !isNil(arr[value])) continue;
const id = key as AllIdsOf<C>;
const num = map[id] as keyof NumberToId;
const identifier: IBlockIdentifier = {
id: id as string,
cls,
num
};
arr[value] = identifier;
}
return arr;
}
function addTileset(set: Set<number>, map?: readonly (readonly number[])[]) {
if (!map) return;
map.forEach(line => {
line.forEach(v => {
if (v >= 10000) set.add(v);
});
});
}
function addAutotile(set: Set<number>, map?: readonly (readonly number[])[]) {
if (!map) return;
map.forEach(line => {
line.forEach(v => {
const id = core.maps.blocksInfo[v as keyof NumberToId];
if (id?.cls === 'autotile') set.add(v);
});
});
}
/**
* 兼容旧版加载
*/
export function fallbackLoad(materials: IMaterialManager) {
// 基本素材
const icons = core.icons.icons;
const images = core.material.images;
const idNumMap: Record<string, number> = {};
for (const [key, value] of Object.entries(core.maps.blocksInfo)) {
const num = Number(key);
idNumMap[value.id] = Number(num);
if (!isNil(value.animate)) {
materials.setDefaultFrame(num, value.animate - 1);
}
}
const terrains = extractClsBlocks('terrains', idNumMap, icons.terrains);
const animates = extractClsBlocks('animates', idNumMap, icons.animates);
const items = extractClsBlocks('items', idNumMap, icons.items);
const enemys = extractClsBlocks('enemys', idNumMap, icons.enemys);
const npcs = extractClsBlocks('npcs', idNumMap, icons.npcs);
const enemy48 = extractClsBlocks('enemy48', idNumMap, icons.enemy48);
const npc48 = extractClsBlocks('npc48', idNumMap, icons.npc48);
// Grid
materials.addGrid(images.terrains, terrains);
materials.addGrid(images.items, items);
// Row Animates
materials.addRowAnimate(images.animates, animates, 32);
materials.addRowAnimate(images.enemys, enemys, 32);
materials.addRowAnimate(images.npcs, npcs, 32);
materials.addRowAnimate(images.enemy48, enemy48, 48);
materials.addRowAnimate(images.npc48, npc48, 48);
// Autotile
for (const key of Object.keys(icons.autotile)) {
const id = key as AllIdsOf<'autotile'>;
const img = images.autotile[id];
const identifier: IBlockIdentifier = {
id,
num: idNumMap[id],
cls: 'autotile'
};
materials.addAutotile(img, identifier);
}
// Tilesets
core.tilesets.forEach((v, i) => {
const img = images.tilesets[v];
const identifier: IIndexedIdentifier = {
index: i,
alias: v
};
materials.addTileset(img, identifier);
});
// 地图上出现过的 tileset
const tilesetSet = new Set<number>();
const autotileSet = new Set<number>();
core.floorIds.forEach(v => {
const floor = core.floors[v];
addTileset(tilesetSet, floor.bgmap);
addTileset(tilesetSet, floor.bg2map);
addTileset(tilesetSet, floor.map);
addTileset(tilesetSet, floor.fgmap);
addTileset(tilesetSet, floor.fg2map);
addAutotile(autotileSet, floor.bgmap);
addAutotile(autotileSet, floor.bg2map);
addAutotile(autotileSet, floor.map);
addAutotile(autotileSet, floor.fgmap);
addAutotile(autotileSet, floor.fg2map);
});
const heroTextures: ITexture[] = [];
data_a1e2fb4a_e986_4524_b0da_9b7ba7c0874d.main.heroImages.forEach(v => {
const tex = materials.getImageByAlias(v);
if (tex) heroTextures.push(tex);
});
materials.buildAssets();
materials.cacheAutotileList(autotileSet);
materials.cacheTilesetList(tilesetSet);
materials.buildListToAsset(heroTextures);
}
@@ -13,3 +13,8 @@ export function create() {
export * from './action';
export * from './fallback';
export * from './render';
export * from './client';
export * from './core';
export * from './shared';
export * from './types';
@@ -1,5 +1,5 @@
import { gameKey } from '@motajs/system';
import { POP_BOX_WIDTH, CENTER_LOC, FULL_LOC } from './shared';
import { POP_BOX_WIDTH, CENTER_LOC, FULL_LOC } from '../shared';
import {
saveSave,
mainUIController,
@@ -1,23 +0,0 @@
import { state } from '@user/data-state';
import { materials } from '@user/client-base';
import { MapRenderer, MapExtensionManager } from './map';
/** 主地图渲染器,用于渲染游戏画面 */
export const mainMapRenderer = new MapRenderer(materials, state.layer);
/** 主地图渲染器拓展 */
export const mainMapExtension = new MapExtensionManager(mainMapRenderer);
/** 副地图渲染器,用于渲染缩略图、浏览地图等 */
// export const expandMapRenderer = new MapRenderer(materials, state.layer);
export async function createMainExtension() {
// 算是一种妥协吧,等之后加载系统重构之后应该会清晰很多
await materials.trackedAsset.then();
mainMapRenderer.useAsset(materials.trackedAsset);
const layer = state.layer.getLayerByAlias('event');
if (layer) {
mainMapExtension.addHero(state.hero.mover, layer);
mainMapExtension.addDoor(layer);
}
mainMapExtension.addText();
}
@@ -8,7 +8,7 @@ import {
HALF_STATUS_WIDTH,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../shared';
} from '../../shared';
const SCROLL_HEIGHT = STATUS_BAR_HEIGHT - 280;
const HALF_HEIGHT = SCROLL_HEIGHT / 2;
@@ -1,7 +1,7 @@
import { Font } from '@motajs/render';
import { defineComponent } from 'vue';
import { DEFAULT_FONT, MAIN_HEIGHT, MAIN_WIDTH } from './shared';
import { hook, loading } from '@user/data-base';
import { DEFAULT_FONT, MAIN_HEIGHT, MAIN_WIDTH } from '../shared';
import { hook } from '@user/data-base';
import { createElements } from './elements';
import { mainRenderer } from './renderer';
import { createUI } from './ui';
@@ -9,7 +9,6 @@ import { createAction } from './action';
import { sceneController } from './scene';
import { GameTitleUI } from './ui/title';
import { createWeather } from './weather';
import { createMainExtension } from './commonIns';
import { createApp } from './renderer';
import { LoadSceneUI } from './ui/load';
@@ -35,10 +34,6 @@ export function createRender() {
createAction();
createWeather();
loading.once('assetBuilt', () => {
createMainExtension();
});
hook.on('restart', () => {
sceneController.closeAll();
sceneController.open(GameTitleUI, {});
@@ -47,7 +42,6 @@ export function createRender() {
Font.setDefaults(DEFAULT_FONT);
}
export * from './commonIns';
export * from './components';
export * from './elements';
export * from './fx';
@@ -56,5 +50,5 @@ export * from './utils';
export * from './weather';
export * from './renderer';
export * from './scene';
export * from './shared';
export * from '../shared';
export * from './use';
@@ -2,7 +2,7 @@ import { MotaOffscreenCanvas2D, RenderItem } from '@motajs/render';
import { ILayerState } from '@user/data-state';
import { IMapRenderer } from './types';
import { ElementNamespace, ComponentInternalInstance } from 'vue';
import { CELL_HEIGHT, CELL_WIDTH, MAP_HEIGHT, MAP_WIDTH } from '../shared';
import { CELL_HEIGHT, CELL_WIDTH, MAP_HEIGHT, MAP_WIDTH } from '../../shared';
import { IMapExtensionManager } from './extension';
export class MapRenderItem extends RenderItem {
@@ -6,7 +6,7 @@ import {
import { IMapDoorRenderer } from './types';
import { IMapRenderer } from '../types';
import { sleep } from 'mutate-animate';
import { DOOR_ANIMATE_INTERVAL } from '../../shared';
import { DOOR_ANIMATE_INTERVAL } from '../../../shared';
export class MapDoorRenderer implements IMapDoorRenderer {
/** 钩子控制器 */
@@ -45,7 +45,7 @@ import {
CELL_WIDTH,
DYNAMIC_RESERVE,
MOVING_TOLERANCE
} from '../shared';
} from '../../shared';
import { MapViewport } from './viewport';
import { INSTANCED_COUNT } from './constant';
import { StaticBlockStatus } from './status';
@@ -17,7 +17,11 @@ import {
MapTileSizeTestMode
} from './types';
import { logger, PrivateBooleanDirtyTracker } from '@motajs/common';
import { DYNAMIC_RESERVE, MAP_BLOCK_HEIGHT, MAP_BLOCK_WIDTH } from '../shared';
import {
DYNAMIC_RESERVE,
MAP_BLOCK_HEIGHT,
MAP_BLOCK_WIDTH
} from '../../shared';
import { BlockSplitter } from './block';
import { clamp, isNil } from 'lodash-es';
import { BlockCls, IMaterialFramedData } from '@user/client-base';
@@ -6,7 +6,7 @@ import {
VARIATOR_DEBUG_SPEED,
DEBUG_DIVIDER,
DIVIDER_DEBUG_DIVIDER
} from './shared';
} from '../shared';
import { createRendererFor, RendererUsing } from '@motajs/render-vue';
import {
ExcitationDivider,
@@ -6,7 +6,7 @@ import {
UIController
} from '@motajs/system';
import { defineComponent } from 'vue';
import { MAIN_HEIGHT, MAIN_WIDTH } from '../shared';
import { MAIN_HEIGHT, MAIN_WIDTH } from '../../shared';
export const mainUIController = new UIController('main-ui');
@@ -17,15 +17,15 @@ import {
LOAD_TASK_RADIUS,
LOAD_UNLOADED_COLOR,
MAIN_WIDTH
} from '../shared';
} from '../../shared';
import { ElementLocator, Font, MotaOffscreenCanvas2D } from '@motajs/render';
import { transitioned } from '../use';
import { cosh, CurveMode, linear } from '@motajs/animate';
import { loader } from '@user/client-base';
import { clamp } from 'lodash-es';
import { sleep } from '@motajs/common';
import { loading } from '@user/data-base';
import { GameTitleUI } from './title';
import { client } from '../../core';
export interface ILoadProps extends UIComponentProps, DefaultProps {}
@@ -34,6 +34,7 @@ const loadSceneProps = {
} satisfies SetupComponentOptions<ILoadProps>;
export const LoadScene = defineComponent<ILoadProps>(props => {
const loader = client.loader;
const taskFont = new Font('Verdana', 24);
const byteFont = new Font('Verdana', 12);
@@ -17,7 +17,7 @@ import {
RIGHT_STATUS_POS,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../shared';
} from '../../shared';
import {
ILeftHeroStatus,
IRightHeroStatus,
@@ -29,11 +29,14 @@ import { getHeroStatusOn, state } from '@user/data-state';
import { hook } from '@user/data-base';
import { mainUIController } from './controller';
import { isNil } from 'lodash-es';
import { mainMapExtension, mainMapRenderer } from '../commonIns';
import { using } from '../renderer';
import { client } from '../../core';
const MainScene = defineComponent(() => {
const { mainMapRenderer, mainMapExtension } = client;
//#region 基本定义
const mainTextboxProps: TextboxProps = {
text: '',
hidden: true,
@@ -27,7 +27,7 @@ import {
SAVE_ITEM_SIZE,
SAVE_ITEM_TOP,
SAVE_PAGES
} from '../shared';
} from '../../shared';
import { getSave, SaveData, adjustGrid, IGridLayoutData } from '../utils';
export const enum SaveMode {
@@ -23,7 +23,7 @@ import { openStatistics } from './statistics';
import { saveWithExist } from './save';
import { compressToBase64 } from 'lz-string';
import { ViewMapUI } from './viewmap';
import { CENTER_LOC, FULL_LOC, MAIN_HEIGHT, POP_BOX_WIDTH } from '../shared';
import { CENTER_LOC, FULL_LOC, MAIN_HEIGHT, POP_BOX_WIDTH } from '../../shared';
import { useKey } from '../use';
export interface MainSettingsProps
@@ -10,9 +10,9 @@ import {
MAIN_WIDTH,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../shared';
} from '../../shared';
import { DefaultProps } from '@motajs/render-vue';
import { materials } from '@user/client-base';
import { client } from '../../core';
export interface ILeftHeroStatus {
/** 楼层 id */
@@ -116,6 +116,8 @@ export const LeftStatusBar = defineComponent<StatusBarProps<ILeftHeroStatus>>(
/** 状态属性的开始纵坐标 */
const STATUS_Y = TITLE_HEIGHT + STATUS_PAD;
const materials = client.materials;
// 可以换成 materials.getImageByAlias('xxx.png') 来使用全塔属性注册的图片
const hpIcon = materials.getImageByAlias('icon-hp');
const atkIcon = materials.getImageByAlias('icon-atk');
@@ -20,7 +20,7 @@ import {
TITLE_STROKE_WIDTH,
TITLE_X,
TITLE_Y
} from '../shared';
} from '../../shared';
import { ElementLocator, Font } from '@motajs/render';
import {
ITransitionedController,
@@ -35,7 +35,7 @@ import { MainSceneUI } from './main';
import { adjustCover } from '../utils';
import { cosh, CurveMode, linear } from '@motajs/animate';
import { sleep } from '@motajs/common';
import { materials } from '@user/client-base';
import { client } from '../../core';
const enum TitleButton {
StartGame,
@@ -64,6 +64,7 @@ const gameTitleProps = {
} satisfies SetupComponentOptions<GameTitleProps>;
export const GameTitle = defineComponent<GameTitleProps>(props => {
const materials = client.materials;
const bg = materials.getImageByAlias(TITLE_BACKGROUND_IMAGE);
//#region 计算背景图
@@ -21,11 +21,11 @@ import { generateBinary } from '@motajs/legacy-common';
import { SetupComponentOptions } from '@motajs/system';
import { saveSave, saveLoad } from './save';
import { mainUIController } from './controller';
import { MAIN_HEIGHT, FULL_LOC, POP_BOX_WIDTH, CENTER_LOC } from '../shared';
import { MAIN_HEIGHT, FULL_LOC, POP_BOX_WIDTH, CENTER_LOC } from '../../shared';
import { openReplay, openSettings } from './settings';
import { openViewMap } from './viewmap';
import { DefaultProps } from '@motajs/render-vue';
import { materials } from '@user/client-base';
import { client } from '../../core';
interface ToolbarProps extends DefaultProps {
loc?: ElementLocator;
@@ -74,6 +74,7 @@ export const PlayingToolbar = defineComponent<
ToolbarEmits,
keyof ToolbarEmits
>((props, { emit }) => {
const materials = client.materials;
const bookIcon = materials.getImageByAlias('icon-book');
const flyIcon = materials.getImageByAlias('icon-fly');
const toolIcon = materials.getImageByAlias('icon-toolbox');
@@ -171,6 +172,7 @@ const replayingProps = {
export const ReplayingToolbar = defineComponent<ReplayingProps>(props => {
const status = props.status;
const materials = client.materials;
const bookIcon = materials.getImageByAlias('icon-book');
const saveIcon = materials.getImageByAlias('icon-save');
const font1 = Font.defaults({ size: 16 });
@@ -39,7 +39,7 @@ import {
RIGHT_STATUS_POS,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../shared';
} from '../../shared';
export interface ViewMapProps extends UIComponentProps, BaseProps {
loc: ElementLocator;
@@ -2,7 +2,7 @@ import { compressToBase64, decompressFromBase64 } from 'lz-string';
import { getConfirm, waitbox } from '../components';
import { IUIMountable } from '@motajs/system';
import { SyncSaveFromServerResponse } from '@motajs/client-base';
import { CENTER_LOC, POP_BOX_WIDTH } from '../shared';
import { CENTER_LOC, POP_BOX_WIDTH } from '../../shared';
export interface SaveData {
name: string;
@@ -16,7 +16,7 @@ export const VARIATOR_DEBUG_SPEED = 0.2;
* 降低画面刷新频率及每帧执行函数的执行频率,方便调试
*/
export const DEBUG_DIVIDER = false;
/** 当使用分频器调试时,分配比例 */
/** 当使用分频器调试时,分频比例 */
export const DIVIDER_DEBUG_DIVIDER = 60;
//#endregion
+53
View File
@@ -0,0 +1,53 @@
import { IRenderTreeRoot } from '@motajs/render';
import { ICoreState } from '@user/data-state';
import { IMapExtensionManager, IMapRenderer } from './render/map';
import { IBGMPlayer, IMotaAudioContext, ISoundPlayer } from '@motajs/audio';
import {
IAutotileProcessor,
IMaterialManager,
IMotaAssetsLoader
} from '@user/client-base';
import { IExcitation, IExcitationDivider } from '@motajs/animate';
export interface IClientCore {
/** 数据端状态对象 */
readonly data: ICoreState;
readonly loader: IMotaAssetsLoader;
/** 素材管理器 */
readonly materials: IMaterialManager;
/** 自动元件处理器 */
readonly autotile: IAutotileProcessor;
/** 用于渲染系统的 Raf 激励源 */
readonly rafExcitation: IExcitation<number>;
/** 用于渲染系统的激励源分频器 */
readonly excitationDivider: IExcitationDivider<number>;
/** 渲染画面的根元素 */
readonly renderer: IRenderTreeRoot;
/** 主地图渲染器,主要用于渲染游戏画面中的地图 */
readonly mainMapRenderer: IMapRenderer;
/** 副地图渲染器,主要用于渲染缩略图、浏览地图等内容 */
// readonly expandMapRenderer: IMapRenderer;
/** 主地图渲染器的拓展管理对象 */
readonly mainMapExtension: IMapExtensionManager;
/** 音频上下文 */
readonly audioContext: IMotaAudioContext;
/** 音效播放器 */
readonly soundPlayer: ISoundPlayer<SoundIds>;
/** BGM 播放器 */
readonly bgmPlayer: IBGMPlayer<BgmIds>;
/**
* 绑定数据端状态
* @param state 数据端状态
*/
bindDataState(state: ICoreState): void;
/**
* 获取当前绑定的数据端状态对象
*/
getDataState(): ICoreState;
}