import { PixiGameScene } from '../common/types'; import { GameConfig, GameObject, GameSceneLifecycle, GameTransitionOpts, JSAPIInterface, GameTransitionOptsDefalt, GameObjectEventParams, DisplayAssetType, GameObjectBaseType, } from '@gedit/render-engine'; import TweenOne from 'tween-one'; // import { Disposable } from '@gedit/utils'; import type { PixiGameDirectorImpl, PixiGameWorldImpl, LoadEventProps, } from './pixi-game'; import { getBackgroundConfig, addTexture } from './utils'; import { SceneSchema } from './game-objects'; import TouchScrollEvent, { XYProps } from './utils/touch-scroll-event'; export class PixiSceneManager { readonly scenesMap: Map = new Map(); public currentScene?: PixiGameSceneImpl; constructor(protected world: PixiGameWorldImpl) {} addScene(id: string, scene: PixiGameSceneImpl): void { this.scenesMap.set(id, scene); } clearScene(): void { this.scenesMap.forEach(c => { c.destroy(); }); this.scenesMap.clear(); } getSceneById(sceneId: string): PixiGameSceneImpl | undefined { return this.scenesMap.get(sceneId); } goto(targetSceneId: string, opts?: GameTransitionOpts): void { const newOpts = { ...GameTransitionOptsDefalt, ...opts }; const prevScene = this.currentScene; let currentScene: PixiGameSceneImpl | undefined; for (const item of this.scenesMap.values()) { if (item.id === targetSceneId) { currentScene = item; } } if (!currentScene) { throw new Error( `Unknown scene id: ${targetSceneId}, current scene ids(${Array.from( this.scenesMap.values() ).map(c => c.id)})` ); } // currentScene.load(); if (newOpts.effect === 'fadeIn') { if (prevScene && prevScene !== currentScene) { TweenOne(prevScene?.container as any, { animation: { alpha: 0, duration: newOpts?.duration }, onChangeTimeline: e => { if (e.mode === 'onTimelineComplete') { if (prevScene) { prevScene?.destroy(); // this.scenesMap.delete(prevScene.id); } } }, }); } if (!currentScene.isLoadScene) { TweenOne(currentScene.container, { animation: { alpha: 1, startAt: { alpha: 0 }, duration: newOpts?.duration, }, }); } } this.currentScene = currentScene; } } interface PixiGameSceneLifecycle { init: () => void; preload: () => void; create: () => void; // update: () => void; } export class PixiGameSceneImpl implements PixiGameScene { id: string; container: PIXI.Container; background: PIXI.Graphics; game: PIXI.Application; world: PixiGameWorldImpl; root: GameObject; config: GameConfig; gameObjectStore = new Map(); director: PixiGameDirectorImpl; name: string = ''; api?: JSAPIInterface; rootTextureCanvas: HTMLCanvasElement = document.createElement('canvas'); videoView: HTMLDivElement | undefined; touchScrollEvent?: TouchScrollEvent; isLoadScene = false; sceneManager?: PixiSceneManager; scale: number; protected isLoaded = false; protected lifecycle: PixiGameSceneLifecycle; protected scrollScaleObjects: GameObject[] = []; constructor( world: PixiGameWorldImpl, director: PixiGameDirectorImpl, sceneId: string, lifecycle: GameSceneLifecycle ) { this.world = world; this.videoView = this.world.videoView; this.initContainer(); this.game = world.game; this.director = director; this.id = sceneId; this.config = world.config; this.lifecycle = { init: () => {}, preload: () => { lifecycle.onPreload && lifecycle.onPreload(this); }, create: () => { lifecycle.onStart?.(this); const dispatchParams: GameObjectEventParams = { api: this.api!, gameObject: this.root!, }; this.onCreate(); this.director.dispatch?.(`${sceneId}_create`, dispatchParams); }, }; this.container.visible = false; world.sceneManager.addScene(sceneId, this); this.sceneManager = world.sceneManager; this.scale = this.getScale(); } initContainer(): void { const { world } = this; this.container = new PIXI.Container(); const g = (this.background = new PIXI.Graphics()); const color = getBackgroundConfig(world.config.backgroundColor); g.rect(0, 0, world.config.width, world.config.height); g.fill(color.backgroundColor); g.alpha = color.backgroundAlpha; this.container.addChild(g); } onLoadEvent(v: LoadEventProps): void { Object.keys(v).forEach( (k: 'onStart' | 'onError' | 'onProgress' | 'onComplete') => { if (this.world.loadingEvent[k].some(c => c === v[k])) { return; } this.world.loadingEvent[k].push(v[k] as any); } ); } setIsLoadScene(): void { this.isLoadScene = true; } async startLoad(nextSceneId?: string): Promise { // 本场景加载在 await this.load(); if (nextSceneId) { // 等待场景加载完成 const scene = this.sceneManager?.getSceneById(nextSceneId); if (scene) { scene.container.alpha = 0; await scene.load(); scene.container.alpha = 1; this.sceneManager?.goto(nextSceneId); } } } public onScroll?(v: XYProps, scale: number): void; protected onCreate(): void { const gameObjects = this.getAllGameObjects(this.root); // 取出所有有 scrollScale 的 obj for (const obj of gameObjects) { if ( obj.data.displayType !== GameObjectBaseType.SCENE && typeof obj.data.scrollScale === 'number' && obj.data.scrollScale !== 1 ) { this.scrollScaleObjects.push(obj); } if (obj.onSceneCreated) { obj.onSceneCreated(); } } } /** * 获取所有节点,包括子组件 * @param parent * @param result */ getAllGameObjects( parent: GameObject, result: GameObject[] = [] ): GameObject[] { if (!parent) { return result; } result.push(parent); if (parent && parent.children && parent.children.length > 0) { parent.children.forEach(child => this.getAllGameObjects(child, result)); } return result; } getScale(): number { const { game, config } = this; /** * @scaleMode * 缩放模式,自适应屏幕 * @param NONE * 不做缩放,保持原始尺寸 * @param WIDTH_CONTROLS_HEIGHT, * 高度根据宽度自动调整。 * @param HEIGHT_CONTROLS_WIDTH * 宽度根据高度自动调整。 * @param FIT * 自动调整宽度和高度以适合给定目标区域内, * 同时保持纵横比。根据纵横比,可能有一些留白 * 在未覆盖的区域内。 * @param ENVELOP * 宽度和高度将自动调整,以使大小覆盖整个目标 * 面积,同时保持纵横比。这可能比目标尺寸延伸得更远。 * 同 css 的 cover * @param {Deleted} RESIZE * 画布将调整为画布大小,不考虑纵横比,宽高会被压缩 */ const { scaleMode } = config; let scale = 1; switch (scaleMode) { case GameConfig.ScaleMode.WIDTH_CONTROLS_HEIGHT: scale = window.innerWidth / config.width; break; case GameConfig.ScaleMode.HEIGHT_CONTROLS_WIDTH: scale = window.innerHeight / config.height; break; case GameConfig.ScaleMode.FIT: scale = Math.min( window.innerWidth / config.width, window.innerHeight / config.height ); break; case GameConfig.ScaleMode.ENVELOP: scale = Math.max( window.innerWidth / config.width, window.innerHeight / config.height ); break; case GameConfig.ScaleMode.NONE: default: break; } scale += 0.001; // +0.001 避免露出背景色 game.stage.scale.set(scale); return scale; } autoCuttingMode(conf: SceneSchema): number { const { config } = this; const { centerType } = config; const scale = this.scale || this.getScale(); /** * @centerType * 对齐方式,居中 * @param NO_CENTER * 不居中 * @param CENTER_BOTH * 全部居中, 水平和垂直都居中 * @param CENTER_HORIZONTALLY * 垂直居中 * @param CENTER_VERTICALLY * 水平居中 * @param {TODO} BOTTOM_VERTICALLY * 底部对齐, 水平居中 * @param {TODO} TOP_VERTICALLY * 顶部对齐,水平居中 * @if 如果有滑动的时候,用应用的宽高; */ // stage 为 window 的宽高容器 // container 为用户设置的宽高容器 const width = conf.autoSize || conf.scrollXBool ? config.width : conf.width ?? config.width; const height = conf.autoSize || conf.scrollYBool ? config.height : conf.height ?? config.height; const wWidth = window.innerWidth / scale; const wHeight = window.innerHeight / scale; // container 坐标为百分百; switch (centerType) { case GameConfig.CenterType.CENTER_BOTH: this.container.x = (wWidth - width) / 2; this.container.y = (wHeight - height) / 2; break; case GameConfig.CenterType.CENTER_VERTICALLY: this.container.x = 0; this.container.y = (wHeight - height) / 2; break; case GameConfig.CenterType.CENTER_HORIZONTALLY: this.container.x = (wWidth - width) / 2; this.container.y = 0; break; case GameConfig.CenterType.CENTER_RIGHT: this.container.x = wWidth - width; this.container.y = 0; break; case GameConfig.CenterType.BOTTOM_VERTICALLY: this.container.x = 0; this.container.y = wHeight - height; break; case GameConfig.CenterType.NO_CENTER: default: break; } return scale; } updateConfig(conf: SceneSchema): void { const { autoSize, scrollXBool, scrollYBool, closeScrollResistance } = conf; const { width, height } = this.config; const w = autoSize ? width : conf.width ?? width; const h = autoSize ? height : conf.height ?? height; const backgroundColor = autoSize ? this.config.backgroundColor : conf.backgroundColor || this.config.backgroundColor; if (!autoSize) { const color = getBackgroundConfig(backgroundColor); this.background.clear(); this.background.rect(0, 0, w, h); this.background.fill(color.backgroundColor); this.background.alpha = color.backgroundAlpha; } if (!this.config.isIDE) { // 适配 const scale = this.autoCuttingMode(conf); if (scrollXBool || scrollYBool) { const innerWidth = w * scale; const innerHeight = h * scale; const isXCenter = this.config.centerType === GameConfig.CenterType.CENTER_BOTH || this.config.centerType === GameConfig.CenterType.CENTER_HORIZONTALLY; const isYCenter = this.config.centerType === GameConfig.CenterType.CENTER_BOTH || this.config.centerType === GameConfig.CenterType.CENTER_VERTICALLY; // 右边开始 let x = this.config.centerType === GameConfig.CenterType.CENTER_RIGHT ? -(innerWidth - window.innerWidth) : 0; // 水平居中的情况下,移动 content x = isXCenter && !scrollXBool ? -(innerWidth - window.innerWidth) / 2 : x; // 如果开启滚动,水平居中的栽切两边; const xStart = isXCenter && scrollXBool ? -(width * scale - window.innerWidth) / 2 : 0; // 底部开始 let y = this.config.centerType === GameConfig.CenterType.BOTTOM_VERTICALLY ? -(innerHeight - window.innerHeight) : 0; // 垂直居中,移动 content; y = isYCenter && !scrollYBool ? -(innerHeight - window.innerHeight) / 2 : y; // 如果开启垂直滚动,垂直居中的栽切掉上下; const yStart = isYCenter && scrollYBool ? -(height * scale - window.innerHeight) / 2 : 0; const currentScroll = { x, y, }; if (!this.touchScrollEvent) { this.touchScrollEvent = new TouchScrollEvent( { app: this.game, closeScrollResistance, pageInnerRect: { width: xStart ? innerWidth + xStart / scale : innerWidth, // xStart 有值时减掉右边的另一半 height: yStart ? innerHeight + yStart / scale : innerHeight, }, xOpenBool: scrollXBool, yOpenBool: scrollYBool, currentScroll, setIsScrollSize: 15 * scale, }, (v: XYProps) => { if (this.container.destroyed) { return; } if (scrollXBool) { this.container.x = (v.x + xStart) / scale; } if (scrollYBool) { this.container.y = (v.y + yStart) / scale; } this.scrollScaleObjects.forEach(c => { if (scrollXBool) { c.rendererObject.x = (c.data.position?.x ?? 0) + (c.data.scrollScale! - 1) * (this.container.x - xStart / scale); } if (scrollYBool) { c.rendererObject.y = (c.data.position?.y ?? 0) + (c.data.scrollScale! - 1) * (this.container.y - yStart / scale); } }); const children = this.getAllGameObjects(this.root); children.forEach(gameObject => { if ( gameObject.type.match(/blur/i) && gameObject.type.match(/Filter$/i) ) { gameObject.update(gameObject.data); } }); this.onScroll?.( { x: v.x / scale, y: v.y / scale, }, scale ); } ); } else { this.touchScrollEvent.currentScroll = currentScroll; this.touchScrollEvent.innerRect = { width: window.innerWidth, height: window.innerHeight, }; } } } } async load(): Promise { if (this.isLoaded) { // 场景被销毁,重新生成 container; if (this.container.destroyed) { this.initContainer(); this.isLoaded = false; // 判断 audio 是否被删除,删除了重新添加; Object.keys(this.world.resources).forEach(key => { if (key.match(DisplayAssetType.AUDIO)) { const item = this.world.resources[key]; if (item instanceof PIXI.sound.Sound && !item.media) { delete this.world.resources[key]; this.addTexture(key, item.url, DisplayAssetType.AUDIO); } } }); return this.load(); } return; } this.container.visible = true; this.lifecycle.preload(); this.isLoaded = true; const keys = Array.from(this.world.loaderAssetsKey).filter( c => !this.world.resources[c] ); /** * v8 加载资源会再触发事件;元素被销毁,再设置坐标会报错; */ if (keys.length) { this.world.loadingEvent.onStart.forEach(c => c(PIXI.Assets.loader)); const assetsLoad = await PIXI.Assets.load(keys, e => { const cb = PIXI.Assets.loader; this.world.loadingEvent.onProgress.forEach(c => c(Object.assign(cb, { progress: e * 100 }), e) ); }); this.world.resources = { ...this.world.resources, ...assetsLoad, }; this.world.loadingEvent.onComplete.forEach(c => c(PIXI.Assets.loader, this.world.resources) ); } this.game.stage.addChild(this.container); // const deferred = new PromiseDeferred(); this.lifecycle.create(); /* this.game.loader.load(() => { this.lifecycle.create(); deferred.resolve(); }); return deferred.promise; */ } setVisible(visible: boolean): void { this.container.visible = visible; } getGameObjectById(nodeId: string): GameObject | undefined { return this.gameObjectStore.get(nodeId); } getTexture( resourceKey: string, ignore?: boolean ): PIXI.Texture | PIXI.sound.Sound { const resources = this.world.resources; const item = resources[resourceKey]; // 不报错,返回空 if (!item && !ignore) { console.warn(`resourceKey: ${resourceKey} not found`); return PIXI.Texture.EMPTY; } return item; } addTexture( resourceKey: string, uri: string, type: DisplayAssetType, data?: any ): void { // TODO support audio if (this.getTexture(resourceKey, true)) return; addTexture(this.game, resourceKey, uri, type, data); this.world.loaderAssetsKey.add(resourceKey); } // addListener( // event: string, // route: string, // gameObject: GameObject // ): Disposable { // // const listener = () => { // // this.director.dispatch && this.director.dispatch(route, { gameObject, api: this.api! }); // // }; // // this.scene.events.addListener(event, listener); // return { // dispose: () => { // // this.scene.events.removeListener(event, listener); // }, // }; // } destroy(): void { this.scrollScaleObjects = []; this.container.destroy(); // 新建时 root 为 undefined; this.root?.dispose(); this.touchScrollEvent?.dispose(); this.touchScrollEvent = undefined; } }