From 054352acfbd93a599e07a8be368afa6f3ad1c524 Mon Sep 17 00:00:00 2001 From: rei1024 Date: Fri, 4 Oct 2024 15:59:35 +0900 Subject: [PATCH] feat: improve performance --- src/app.ts | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/app.ts b/src/app.ts index d34e767..8cb509c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -4,25 +4,32 @@ import { $autoRandom } from "./bind"; import { createTemplateCell } from "./lib/cell"; import { setRLE } from "./lib/setRLE"; -const WORLD_SIZE = 32 * 2; const stackHeight = 1; export class App { private prevGrid: BitGrid | null = null; private prevPrevGrid: BitGrid | null = null; - private bitWorld = BitWorld.make({ width: WORLD_SIZE, height: WORLD_SIZE }); + private worldSize = 32 * 2; + private bitWorld: BitWorld; private generation = 0; public historySize = 16; private templateMesh: BABYLON.Mesh; private cellMaterial: BABYLON.StandardMaterial; private cellMeshes: BABYLON.InstancedMesh[][] = []; + /** ここに入っていれば isVisible=false */ + private meshPool: BABYLON.InstancedMesh[] = []; + constructor( private engine: BABYLON.Engine, private scene: BABYLON.Scene, private camera: BABYLON.ArcRotateCamera, private pointLight: BABYLON.PointLight ) { + this.bitWorld = BitWorld.make({ + width: this.worldSize, + height: this.worldSize, + }); this.bitWorld.random(); this.initCamera(); const { templateCell, cellMaterial } = createTemplateCell(scene); @@ -38,6 +45,7 @@ export class App { } setSize(size: number) { + this.worldSize = size; this.generation = 0; this.camera.target.y = 0; this.pointLight.position.y = 0; @@ -67,7 +75,10 @@ export class App { this.bitWorld.forEach((x, y, alive) => { if (alive === 1) { // セルのインスタンスを作成 - const instance = this.templateMesh.createInstance(`cell_${x}_${y}`); + const instance = + this.meshPool.pop() ?? + this.templateMesh.createInstance(`cell_${x}_${y}`); + instance.isVisible = true; instance.position = new BABYLON.Vector3( x, this.generation * stackHeight, @@ -89,7 +100,14 @@ export class App { this.cellMeshes.length - this.historySize ); old.forEach((a) => { - a.forEach((c) => c.dispose()); + a.forEach((c) => { + if (this.meshPool.length <= this.worldSize * this.worldSize) { + c.isVisible = false; + this.meshPool.push(c); + } else { + c.dispose(); + } + }); }); this.cellMeshes = this.cellMeshes.slice( this.cellMeshes.length - this.historySize @@ -103,6 +121,10 @@ export class App { } clearCell() { + this.meshPool.forEach((c) => { + c.dispose(); + }); + this.meshPool = []; this.cellMeshes.forEach((a) => { a.forEach((c) => c.dispose()); });