File size: 21,326 Bytes
c47613b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
const mathFunc = {
  'arrayMax': (array) => {
    const maxfct = (a, b) => {return Math.max(a, b)};
    return array.reduce(maxfct);
  },
  'arrayMin': (array) => {
    const minfct = (a, b) => {return Math.min(a, b)};
    return array.reduce(minfct);
  },
  'arrayTotal': (array) => {
    return array.reduce((acc, f) => acc + f, 0);
  },
  'arrayAvg': (array) => {
    return array.reduce((acc, f) => acc + f, 0) / array.length;
  },
  'rounder': (method, num, n, zeroPadding = false) => {
    const pow = Math.pow(10, n);
    let result;
    switch (method) {
      case 'floor':
        result = Math.floor(num * pow) / pow;
        break;
      case 'ceil':
        result = Math.ceil(num * pow) / pow;
        break;
      case 'round':
        result = Math.round(num * pow) / pow;
        break;
      default:
        throw new Error('Invalid rounding method specified.');
    }
    if (zeroPadding) {
      return result.toFixed(n);
    } else {
      return result;
    }
  },
  'formatFileSize': (bytes, decimals = 2) => {
    if (bytes === 0) return '0 byte';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }
};

const resourcePathSetsDefault = {
  'track': 'melancholy_night',
  'mainModel': 'alicia'
};
const resourcePathSets = {
  'track': {
    'apdh': {
      'mainMotion': './res/track/apdh/hime_motion_-8f.bvmd',
      'audio': './res/track/apdh/audio.m4a',
      'bakeMotion': {
        // 'hutao': './res/track/apdh/hime_motion_-8f_bake_hutao.bvmd'
      }
    },
    'conqueror': {
      'mainMotion': './res/track/conqueror/merged.bvmd',
      'audio': './res/track/conqueror/audio.m4a',
      'bakeMotion': {}
    },
    'melancholy_night': {
      'mainMotion': './res/track/melancholy_night/motion.bvmd',
      'audio': './res/track/melancholy_night/melancholy_night.m4a',
      'bakeMotion': {}
    }
  },
  'mainModel': {
    'alicia': './res/model/Alicia.bpmx',
    'higuchiKaede': './res/model/higuchi_kaede.bpmx',
    'higuchiKaedeHair': './res/model/higuchi_kaede_alt.bpmx',
    'higuchiKaedeSummer': './res/model/higuchi_kaede_summer.bpmx',
    'higuchiKaedeSummerHair': './res/model/higuchi_kaede_summer_alt.bpmx',
    'higuchiKaedeCasual': './res/model/higuchi_kaede_casual.bpmx',
    'higuchiKaedeOni': './res/model/higuchi_kaede_oni.bpmx',
    'higuchiKaedeArmy': './res/model/higuchi_kaede_army.bpmx',
    'higuchiKaedeArmyHair': './res/model/higuchi_kaede_army_alt.bpmx',
    'hutao': './res/model/HuTao/HuTao.pmx',
    'inuiToko': './res/model/inui_toko.bpmx',
    'lumine': './res/model/Lumine/LumineModified.pmx',
    'miraiAkari': './res/model/MiraiAkari_v1.0.bpmx',
    'raidenShogun': './res/model/RaidenShogun.bpmx',
    'tokinoSora': './res/model/tokino_sora.bpmx',
    'yyb_miku_10th': './res/model/yyb_hatsune_miku_10th_v1.02.bpmx'
  }
};
let isEnablePhysicsEngine = true;
const resourcePaths = {
  'mainModel': resourcePathSets.mainModel[resourcePathSetsDefault.mainModel],
  'mainMotion': resourcePathSets.track[resourcePathSetsDefault.track].mainMotion,
  'audio': resourcePathSets.track[resourcePathSetsDefault.track].audio,
};
const resourceNames = {
  'track': resourcePathSetsDefault.track,
  'mainModel': resourcePathSetsDefault.mainModel
};
const urlQueryObject = Object.fromEntries(new URLSearchParams(window.location.search));
if (Object.keys(urlQueryObject).some(el => el === 'track')) {
  for (let i = 0; i < Object.keys(resourcePathSets.track).length; i++) {
    if (urlQueryObject.track === Object.keys(resourcePathSets.track)[i]) {
      resourcePaths.mainMotion = resourcePathSets.track[Object.keys(resourcePathSets.track)[i]].mainMotion;
      resourcePaths.audio = resourcePathSets.track[Object.keys(resourcePathSets.track)[i]].audio;
      resourceNames.track = Object.keys(resourcePathSets.track)[i];
    }
  }
}
if (Object.keys(urlQueryObject).some(el => el === 'mainModel')) {
  for (let i = 0; i < Object.keys(resourcePathSets.mainModel).length; i++) {
    if (urlQueryObject.mainModel === Object.keys(resourcePathSets.mainModel)[i]) {
      resourcePaths.mainModel = resourcePathSets.mainModel[Object.keys(resourcePathSets.mainModel)[i]];
      resourceNames.mainModel = Object.keys(resourcePathSets.mainModel)[i];
    }
  }
}
for (let i = 0; i < Object.keys(resourcePathSets.track[resourceNames.track].bakeMotion).length; i++) {
  if (Object.keys(resourcePathSets.track[resourceNames.track].bakeMotion)[i] === resourceNames.mainModel) {
    resourcePaths.mainMotion = resourcePathSets.track[resourceNames.track].bakeMotion[resourceNames.mainModel];
    isEnablePhysicsEngine = false;
  }
}
console.log(resourcePaths)

var canvas = document.getElementById("renderCanvas");
var startRenderLoop = function (engine, canvas) {
  engine.runRenderLoop(function () {
    if (sceneToRender && sceneToRender.activeCamera) {
      sceneToRender.render();
    }
  });
};
var engine = null;
var scene = null;
var sceneToRender = null;
var createDefaultEngine = function () {
  return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true, disableWebGL2Support: false });
};
class Playground {
  static async CreateScene(engine, canvas) {
    await new Promise((resolve) => {
      const babylonMmdScript = document.createElement("script");
      babylonMmdScript.src = "https://www.unpkg.com/babylon-mmd@0.54.3/umd/babylon.mmd.min.js";
      document.head.appendChild(babylonMmdScript);
      babylonMmdScript.onload = resolve;
    });
    if (engine.hostInformation.isMobile) {engine.setHardwareScalingLevel(0.85)} else {engine.setHardwareScalingLevel(0.75)}
    if (Object.keys(urlQueryObject).some(el => el === 'scale')) {
      engine.setHardwareScalingLevel(parseFloat(urlQueryObject.scale));
    }
    const pmxLoader = BABYLON.SceneLoader.GetPluginForExtension(".pmx");
    const materialBuilder = pmxLoader.materialBuilder;
    materialBuilder.useAlphaEvaluation = false;
    // materialBuilder.loadOutlineRenderingProperties;
    // const alphaBlendMaterials = ["face02", "Facial02", "HL", "Hairshadow", "q302"];
    // const alphaTestMaterials = ["q301"];
    // materialBuilder.afterBuildSingleMaterial = (material) => {
    //   if (!alphaBlendMaterials.includes(material.name) && !alphaTestMaterials.includes(material.name)) return;
    //   material.transparencyMode = alphaBlendMaterials.includes(material.name) ? BABYLON.Material.MATERIAL_ALPHABLEND : BABYLON.Material.MATERIAL_ALPHATEST;
    //   material.useAlphaFromDiffuseTexture = true;
    //   material.diffuseTexture.hasAlpha = true;
    // };
    const scene = new BABYLON.Scene(engine);
    // BABYLON.SceneOptimizer.OptimizeAsync(scene);
    // scene.clearColor = new BABYLON.Color4(0.95, 0.95, 0.95, 1.0);
    scene.clearColor = new BABYLON.Color4(0, 0, 0, 1.0);
    const mmdCamera = new BABYLONMMD.MmdCamera("MmdCamera", new BABYLON.Vector3(0, 10, 0), scene);
    mmdCamera.maxZ = 5000;
    const camera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 0, 0, 45, new BABYLON.Vector3(0, 10, 0), scene);
    camera.maxZ = 5000;
    camera.setPosition(new BABYLON.Vector3(0, 10, -45));
    camera.attachControl(canvas, false);
    camera.inertia = 0.8;
    camera.speed = 10;
    const hemisphericLight = new BABYLON.HemisphericLight("HemisphericLight", new BABYLON.Vector3(0, 1, 0), scene);
    hemisphericLight.intensity = 0.4;
    hemisphericLight.specular = new BABYLON.Color3(0, 0, 0);
    hemisphericLight.groundColor = new BABYLON.Color3(1, 0.9, 0.9);
    const directionalLight = new BABYLON.DirectionalLight("DirectionalLight", new BABYLON.Vector3(0.5, -1, 1), scene);
    directionalLight.intensity = 0.8;
    directionalLight.autoCalcShadowZBounds = false;
    directionalLight.autoUpdateExtends = false;
    directionalLight.shadowMaxZ = 20;
    directionalLight.shadowMinZ = -15;
    directionalLight.orthoTop = 18;
    directionalLight.orthoBottom = -1;
    directionalLight.orthoLeft = -10;
    directionalLight.orthoRight = 10;
    directionalLight.shadowOrthoScale = 0;
    const shadowGenerator = new BABYLON.ShadowGenerator(1024, directionalLight, true);
    shadowGenerator.usePercentageCloserFiltering = true;
    shadowGenerator.forceBackFacesOnly = true;
    shadowGenerator.filteringQuality = BABYLON.ShadowGenerator.QUALITY_MEDIUM;
    shadowGenerator.frustumEdgeFalloff = 0.1;
    const mmdRuntime = isEnablePhysicsEngine ? new BABYLONMMD.MmdRuntime(scene, new BABYLONMMD.MmdPhysics(scene)) : new BABYLONMMD.MmdRuntime(scene)
    mmdRuntime.register(scene);
    const audioPlayer = new BABYLONMMD.StreamAudioPlayer(scene);
    audioPlayer.preservesPitch = true;
    audioPlayer.source = resourcePaths.audio;
    mmdRuntime.setAudioPlayer(audioPlayer);
    const mmdPlayerControl = new BABYLONMMD.MmdPlayerControl(scene, mmdRuntime, audioPlayer);
    mmdPlayerControl.showPlayerControl();
    engine.displayLoadingUI();
    let loadingTexts = [];
    const updateLoadingText = (updateIndex, text) => {
      loadingTexts[updateIndex] = text;
      engine.loadingUIText = "<br/><br/><br/><br/>" + loadingTexts.join("<br/><br/>");
    };
    const promises = [];
    const bvmdLoader = new BABYLONMMD.BvmdLoader(scene);
    promises.push(bvmdLoader.loadAsync("motion", resourcePaths.mainMotion, (event) => updateLoadingText(0, `Loading motion... ${event.loaded}/${event.total} (${Math.floor((event.loaded * 100) / event.total)}%)`)));
    promises.push(BABYLON.SceneLoader.ImportMeshAsync(undefined, resourcePaths.mainModel, undefined, scene, (event) => updateLoadingText(1, `Loading model... ${event.loaded}/${event.total} (${Math.floor((event.loaded * 100) / event.total)}%)`)));
    if (isEnablePhysicsEngine === true) {
      promises.push(
        (async () => {
          updateLoadingText(2, "Loading physics engine...");
          const havokPlugin = new BABYLON.HavokPlugin();
          // scene.enablePhysics(new BABYLON.Vector3(0, -9.8, 0), havokPlugin);
          scene.enablePhysics(new BABYLON.Vector3(0, -9.8, 0), havokPlugin);
          updateLoadingText(2, "Loading physics engine... Done");
        })()
      );
    }
    loadingTexts = new Array(promises.length).fill("");
    const loadResults = await Promise.all(promises);
    scene.onAfterRenderObservable.addOnce(() => engine.hideLoadingUI());
    mmdRuntime.setCamera(mmdCamera);
    mmdCamera.addAnimation(loadResults[0]);
    mmdCamera.setAnimation("motion");
    const modelMesh = loadResults[1].meshes[0];
    modelMesh.receiveShadows = true;
    shadowGenerator.addShadowCaster(modelMesh);
    const mmdModel = mmdRuntime.createMmdModel(modelMesh);
    mmdModel.addAnimation(loadResults[0]);
    mmdModel.setAnimation("motion");
    // mmdModel.mesh.outlineWidth = 10
    const bodyBone = loadResults[1].skeletons[0].bones.find((bone) => bone.name === "センター");
    scene.onBeforeRenderObservable.add(() => {
      bodyBone.getFinalMatrix().getTranslationToRef(directionalLight.position);
      directionalLight.position.y -= 10;
    });
    const ground = BABYLON.MeshBuilder.CreateGround("Ground", { width: 100, height: 100, subdivisions: 2, updatable: false }, scene);
    ground.receiveShadows = true;
    const groundMaterial = (ground.material = new BABYLON.StandardMaterial("GroundMaterial", scene));
    groundMaterial.diffuseColor = new BABYLON.Color3(0.25, 0.25, 0.25);
    groundMaterial.specularPower = 128;
    const groundReflectionTexture = (groundMaterial.reflectionTexture = new BABYLON.MirrorTexture("MirrorTexture", 1024, scene, true));
    groundReflectionTexture.mirrorPlane = BABYLON.Plane.FromPositionAndNormal(ground.position, ground.getFacetNormal(0).scale(-1));
    groundReflectionTexture.renderList = [modelMesh];
    groundReflectionTexture.level = 0.25;
    const defaultPipeline = new BABYLON.DefaultRenderingPipeline("default", true, scene, [mmdCamera, camera]);
    defaultPipeline.samples = 4;
    defaultPipeline.bloomEnabled = true;
    defaultPipeline.bloomThreshold = 0;
    defaultPipeline.bloomWeight = 0.1;
    defaultPipeline.bloomKernel = 38;
    defaultPipeline.bloomScale = 0.5;
    defaultPipeline.chromaticAberrationEnabled = true;
    defaultPipeline.chromaticAberration.aberrationAmount = 0;
    defaultPipeline.fxaaEnabled = true;
    defaultPipeline.imageProcessingEnabled = true;
    defaultPipeline.imageProcessing.toneMappingEnabled = false;
    defaultPipeline.imageProcessing.toneMappingType = BABYLON.ImageProcessingConfiguration.TONEMAPPING_ACES;
    defaultPipeline.imageProcessing.vignetteWeight = 0.5;
    defaultPipeline.imageProcessing.vignetteStretch = 0.5;
    defaultPipeline.imageProcessing.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
    defaultPipeline.imageProcessing.vignetteEnabled = true;
    const lensEffect = new BABYLON.LensRenderingPipeline('lensEffects', {edge_blur: engine.hostInformation.isMobile ? 0.0 : 1.0, chromatic_aberration: engine.hostInformation.isMobile ? 0.5 : 1.0, distortion: 0.2}, scene, 1.0);
    scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline('lensEffects', camera);
    scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline('lensEffects', mmdCamera);
    // BABYLON.ParticleHelper.CreateAsync("rain", scene, false).then((set) => {set.start()});
    const guiCamera = new BABYLON.ArcRotateCamera("GUICamera", Math.PI / 2 + Math.PI / 7, Math.PI / 2, 100, new BABYLON.Vector3(0, 20, 0), scene);
    guiCamera.layerMask = 0x10000000;
    scene.activeCameras = [mmdCamera, guiCamera];
    let lastClickTime = -Infinity;
    canvas.onclick = () => {
      const currentTime = performance.now();
      if (500 < currentTime - lastClickTime) {
        lastClickTime = currentTime;
        return;
      }
      lastClickTime = -Infinity;
      if (scene.activeCameras[0] === mmdCamera) scene.activeCameras = [camera, guiCamera];
      else scene.activeCameras = [mmdCamera, guiCamera];
    };
    let engineInstrumentation = new BABYLON.EngineInstrumentation(engine);
    engineInstrumentation.captureGPUFrameTime = true;
    engineInstrumentation.captureShaderCompilationTime = true;
    let sceneInstrumentation = new BABYLON.SceneInstrumentation(scene);
    sceneInstrumentation.captureActiveMeshesEvaluationTime = true;
    sceneInstrumentation.captureFrameTime = true;
    sceneInstrumentation.captureParticlesRenderTime = true;
    sceneInstrumentation.captureRenderTime = true;
    sceneInstrumentation.captureCameraRenderTime = true;
    sceneInstrumentation.captureRenderTargetsRenderTime = true;
    sceneInstrumentation.captureInterFrameTime = true;
    let isLimitFPS = false;
    let targetFPS = null;
    if (Object.keys(urlQueryObject).some(el => el === 'fps')) {
      isLimitFPS = true;
      targetFPS = parseFloat(urlQueryObject.fps) + 0.35;
      engine.customAnimationFrameRequester = {
        requestAnimationFrame: (func) => {setTimeout(func, 1000 / targetFPS - sceneInstrumentation.frameTimeCounter.current - sceneInstrumentation.activeMeshesEvaluationTimeCounter.current - sceneInstrumentation.particlesRenderTimeCounter.lastSecAverage - sceneInstrumentation.renderTimeCounter.current - sceneInstrumentation.cameraRenderTimeCounter.current - sceneInstrumentation.renderTargetsRenderTimeCounter.current)}
      };
    }
    const advancedTexture = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
    advancedTexture.layer.layerMask = 0x10000000;
    advancedTexture.renderScale = 1.5;
    const textblock = new BABYLON.GUI.TextBlock();
    // textblock.widthInPixels = 800;
    // textblock.left = 10;
    textblock.text = `${engine._glRenderer}\n${engine._glVersion}`;
    textblock.fontSize = 32;
    textblock.fontFamily = "'SF Mono', 'SF Pro Text', 'Inter', 'Noto Sans JP', 'system-ui'";
    textblock.textHorizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
    textblock.textVerticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
    textblock.horizontalAlignment = BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
    textblock.verticalAlignment = BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;
    textblock.color = "#ffffff";
    advancedTexture.addControl(textblock);
    const textBlockUpdateDisp = setInterval(() => {
      if (engine.hostInformation.isMobile) {
        textblock.text = `${engine._glRenderer}
${engine._glVersion}

${engine.frameId} f
${mathFunc.rounder('floor', engine.performanceMonitor.averageFPS, 2)} fps
${mathFunc.rounder('floor', engine.performanceMonitor.averageFrameTime, 2)} ms`;
      } else {
        textblock.text = `${engine._glRenderer}
${engine._glVersion}

Main Model Path:    ${resourcePaths.mainModel}
Main Motion Path:   ${resourcePaths.mainMotion}
Main Audio Path:    ${resourcePaths.audio}

FPS Disp:           ${mathFunc.rounder('floor', engine.performanceMonitor.averageFPS, 2, true)} fps avg (${mathFunc.rounder('floor', engine.performanceMonitor.instantaneousFPS, 2, true)} fps)
FPS Limit:          ${isLimitFPS ? mathFunc.rounder('floor', parseFloat(urlQueryObject.fps), 2, true) + ' fps' : 'unlimited'}
FPS Real:           ${isLimitFPS ? mathFunc.rounder('floor', 1000 / sceneInstrumentation.frameTimeCounter.lastSecAverage, 2, true) : mathFunc.rounder('floor', 1000 / sceneInstrumentation.frameTimeCounter.lastSecAverage, 2, true)} fps

Active Meshes:      ${scene.getActiveMeshes().length} / ${scene.meshes.length}
Total Vertices:     ${scene.totalVerticesPerfCounter.current}
Active Indices:     ${scene.totalActiveIndicesPerfCounter.current}
Total Objects:      ${scene.materials.length} mat, ${scene.textures.length} tex, ${scene.animatables.length} anm, ${scene.lights.length} lit
Draw Calls Count:   ${sceneInstrumentation.drawCallsCounter.current}

Frame Count:        ${engine.frameId} frame
Actually Frame:     ${mathFunc.rounder('floor', engine.performanceMonitor.averageFrameTime, 2, true)} ms avg (${mathFunc.rounder('floor', engine.performanceMonitor.instantaneousFrameTime, 2, true)} ms)
Scene Frame:        ${mathFunc.rounder('ceil', sceneInstrumentation.frameTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.frameTimeCounter.current, 2, true)} ms)
Active Meshes Eval: ${mathFunc.rounder('ceil', sceneInstrumentation.activeMeshesEvaluationTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.activeMeshesEvaluationTimeCounter.current, 2, true)} ms)
Particles Render:   ${mathFunc.rounder('ceil', sceneInstrumentation.particlesRenderTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.particlesRenderTimeCounter.current, 2, true)} ms)
Inter Frame:        ${mathFunc.rounder('ceil', sceneInstrumentation.interFrameTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.interFrameTimeCounter.current, 2, true)} ms)
GPU Frame:          ${mathFunc.rounder('ceil', engineInstrumentation.gpuFrameTimeCounter.lastSecAverage * 0.000001, 2, true)} ms avg (${mathFunc.rounder('ceil', engineInstrumentation.gpuFrameTimeCounter.current * 0.000001, 2, true)} ms)
Shader Comp Total:  ${mathFunc.rounder('ceil', engineInstrumentation.shaderCompilationTimeCounter.count, 2, true)} ms
Scene Render:       ${mathFunc.rounder('ceil', sceneInstrumentation.renderTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.renderTimeCounter.current, 2, true)} ms)
Camera Render:      ${mathFunc.rounder('ceil', sceneInstrumentation.cameraRenderTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.cameraRenderTimeCounter.current, 2, true)} ms)
Targets Render:     ${mathFunc.rounder('ceil', sceneInstrumentation.renderTargetsRenderTimeCounter.lastSecAverage, 2, true)} ms avg (${mathFunc.rounder('ceil', sceneInstrumentation.renderTargetsRenderTimeCounter.current, 2, true)} ms)

Heap: ${!performance.memory ? 'Unavailable' : (mathFunc.rounder('ceil', performance.memory.usedJSHeapSize / 1024 / 1024, 2, true))} MB / ${!performance.memory ? 'Unavailable' : (mathFunc.rounder('ceil', performance.memory.totalJSHeapSize / 1024 / 1024, 2, true))} MB (Limit ${!performance.memory ? 'Unavailable' : (mathFunc.rounder('ceil', performance.memory.jsHeapSizeLimit / 1024 / 1024, 2, true))} MB)
`;
      }
    }, 10);
    await new Promise(resolve => setTimeout(resolve, 1000));
    mmdRuntime.playAnimation();
    return scene;
  }
}
createScene = function () {
  return Playground.CreateScene(engine, engine.getRenderingCanvas());
};
window.initFunction = async function () {
  globalThis.HK = await HavokPhysics();

  var asyncEngineCreation = async function () {
    try {
      return createDefaultEngine();
    } catch (e) {
      console.log("the available createEngine function failed. Creating the default engine instead");
      return createDefaultEngine();
    }
  };

  window.engine = await asyncEngineCreation();
  if (!engine) throw "engine should not be null.";
  startRenderLoop(engine, canvas);
  window.scene = createScene();
};
initFunction().then(() => {
  scene.then((returnedScene) => {
    sceneToRender = returnedScene;
  });
});

// Resize
window.addEventListener("resize", function () {
  engine.resize();
});