Spaces:
Running
Running
| 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': { | |
| 'conqueror': { | |
| 'mainMotion': './res/track/conqueror/merged.bvmd', | |
| 'audio': './res/track/conqueror/audio.m4a' | |
| }, | |
| 'melancholy_night': { | |
| 'mainMotion': './res/track/melancholy_night/motion.bvmd', | |
| 'audio': './res/track/melancholy_night/melancholy_night.m4a' | |
| } | |
| }, | |
| 'mainModel': { | |
| 'alicia': './res/model/Alicia.bpmx', | |
| 'raidenShogun': './res/model/RaidenShogun.bpmx', | |
| 'yyb_miku_10th': './res/model/yyb_hatsune_miku_10th_v1.02.bpmx' | |
| } | |
| }; | |
| const resourcePaths = { | |
| 'mainModel': resourcePathSets.mainModel[resourcePathSetsDefault.mainModel], | |
| 'mainMotion': resourcePathSets.track[resourcePathSetsDefault.track].mainMotion, | |
| 'audio': resourcePathSets.track[resourcePathSetsDefault.track].audio, | |
| }; | |
| 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; | |
| } | |
| } | |
| } | |
| 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]]; | |
| } | |
| } | |
| } | |
| 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.37.2/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)} | |
| 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 = 1; | |
| hemisphericLight.specular = new BABYLON.Color3(0, 0, 0); | |
| hemisphericLight.groundColor = new BABYLON.Color3(0, 0, 0); | |
| // 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 = new BABYLONMMD.MmdRuntime(scene, new BABYLONMMD.MmdPhysics(scene)); | |
| mmdRuntime.register(scene); | |
| const audioPlayer = new BABYLONMMD.StreamAudioPlayer(scene); | |
| audioPlayer.preservesPitch = false; | |
| 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)}%)`))); | |
| 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.metadata.materials.forEach(mtr => {mtr.wireframe = true}); | |
| 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 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]; | |
| }; | |
| 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 = "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}\n${engine._glVersion}\n\n${engine.frameId} f\n${mathFunc.rounder('floor', engine.getFps(), 2)} fps\n${mathFunc.rounder('floor', engine.performanceMonitor.averageFrameTime, 2)} ms`; | |
| } else { | |
| textblock.text = `${engine._glRenderer}\n${engine._glVersion}\n\n${resourcePaths.mainModel}\n${resourcePaths.mainMotion}\n${resourcePaths.audio}\n\n${engine.frameId} frame\n${Math.floor(engine.getFps())} fps\n${Math.floor(engine.performanceMonitor.averageFrameTime)} ms`; | |
| } | |
| }, 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(); | |
| }); | |