Spaces:
Running
Running
File size: 13,323 Bytes
7c003ea |
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 |
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();
});
|