Spaces:
Running
Running
v85: add rigidBody + bone dump for physics analysis (no behavior change)
Browse files
app.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import*as THREE from'three';import{MMDLoader}from'three/examples/jsm/loaders/MMDLoader';import{TGALoader}from'three/examples/jsm/loaders/TGALoader';import{MMDAnimationHelper}from'three/examples/jsm/animation/MMDAnimationHelper';import{OrbitControls}from'three/examples/jsm/controls/OrbitControls';
|
| 2 |
const debugLogEl=document.getElementById('debug-log'),debugPanel=document.getElementById('debug-panel'),debugToggle=document.getElementById('debug-toggle');let debugVisible=false;debugToggle.addEventListener('click',e=>{e.preventDefault();e.stopPropagation();debugVisible=!debugVisible;if(debugVisible){debugPanel.removeAttribute('hidden');debugPanel.classList.add('visible')}else{debugPanel.classList.remove('visible');debugPanel.setAttribute('hidden','')}});debugToggle.addEventListener('touchend',e=>{e.preventDefault();debugToggle.click()});document.getElementById('debug-clear-btn').addEventListener('click',()=>{debugLogEl.innerHTML=''});document.getElementById('debug-copy-btn').addEventListener('click',()=>{const btn=document.getElementById('debug-copy-btn');navigator.clipboard.writeText(debugLogEl.innerText).then(()=>{btn.textContent='✅Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)}).catch(()=>{const ta=document.createElement('textarea');ta.value=debugLogEl.innerText;document.body.appendChild(ta);ta.select();document.execCommand('copy');document.body.removeChild(ta);btn.textContent='✅Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)})});document.getElementById('tab-log').addEventListener('click',()=>{document.getElementById('debug-log').style.display='block';document.getElementById('mat-debug').style.display='none';document.getElementById('tab-log').classList.add('active');document.getElementById('tab-mat').classList.remove('active')});document.getElementById('tab-mat').addEventListener('click',()=>{document.getElementById('debug-log').style.display='none';document.getElementById('mat-debug').style.display='block';document.getElementById('tab-mat').classList.add('active');document.getElementById('tab-log').classList.remove('active')});
|
| 3 |
-
const APP_VER='
|
| 4 |
function dbg(msg,level='log'){if(!_dbgH){_dbgH=true;const h=document.createElement('div');h.className='info';h.textContent=`[MMD_pmx_Player_${APP_VER}_${_ds()}]`;debugLogEl.appendChild(h)}const cls=level==='warn'?'warn':level==='error'?'error':level==='info'?'info':'';const line=document.createElement('div');if(cls)line.className=cls;line.textContent=`[${_t()}] ${msg}`;debugLogEl.appendChild(line);debugLogEl.scrollTop=debugLogEl.scrollHeight;if(level==='error')console.error(msg);else if(level==='warn')console.warn(msg);else console.log(msg)}
|
| 5 |
const FALLBACK_PIXEL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";function generateToonDataURL(tR,tG,tB,bR,bG,bB){const c=document.createElement('canvas');c.width=1;c.height=256;const x=c.getContext('2d');const g=x.createLinearGradient(0,0,0,256);g.addColorStop(0,`rgb(${tR},${tG},${tB})`);g.addColorStop(1,`rgb(${bR},${bG},${bB})`);x.fillStyle=g;x.fillRect(0,0,1,256);return c.toDataURL('image/png')}const BUILTIN_TOONS={};const TOON_DEFS=[[255,255,255,180,180,180],[255,220,220,160,120,120],[255,240,210,160,140,100],[255,255,230,160,160,110],[220,255,220,110,160,110],[220,255,255,110,160,160],[210,220,255,100,110,160],[255,220,255,160,110,160],[245,245,245,150,150,150],[230,230,230,100,100,100]];for(let i=0;i<10;i++){const n=String(i+1).padStart(2,'0');const d=TOON_DEFS[i];BUILTIN_TOONS[`toon${n}.bmp`]=generateToonDataURL(d[0],d[1],d[2],d[3],d[4],d[5])}
|
| 6 |
if(window.CharsetEncoder){window.CharsetEncoder.install();const orig=window.CharsetEncoder.decode;window.CharsetEncoder.decode=function(data,enc){try{return orig(data,enc||'shift_jis')}catch(e){try{return new TextDecoder('shift_jis').decode(data)}catch(e2){return new TextDecoder('utf-8').decode(data)}}}}
|
|
@@ -11,13 +11,31 @@ function saveInitialBonePose(m){if(!m||!m.skeleton)return;m.userData._ib=m.skele
|
|
| 11 |
function restoreInitialBonePose(m){if(!m||!m.userData._ib)return;const saved=m.userData._ib;const bm={};m.skeleton.bones.forEach(b=>{bm[b.name]=b});for(const d of saved){const bone=bm[d.n];if(!bone)continue;bone.position.copy(d.p);bone.quaternion.copy(d.q);bone.scale.copy(d.s)}m.skeleton.bones.forEach(b=>b.updateMatrix());m.skeleton.update();m.updateMatrixWorld(true)}
|
| 12 |
function setupValInput(inputId,sliderId,applyFn){const inp=document.getElementById(inputId);const sl=document.getElementById(sliderId);if(!inp||!sl)return;inp.addEventListener('blur',()=>{const v=parseFloat(inp.value);if(isNaN(v)){inp.value=sl.value;return}const min=parseFloat(sl.min),max=parseFloat(sl.max);const clamped=Math.max(min,Math.min(max,v));sl.value=clamped;inp.value=clamped;if(applyFn)applyFn(clamped)});inp.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();inp.blur()}})}
|
| 13 |
function hasMatPrefix(target){let found=false;target.traverse(child=>{if(found||!child.isMesh)return;const mats=Array.isArray(child.material)?child.material:[child.material];if(mats[0]&&/^\d{4}_/.test(mats[0].name||''))found=true});return found}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
function getDrawPriority(name){const n=(name||'').toLowerCase();if(/eyewhite/i.test(n))return 2000;if(/face.*skin/i.test(n))return 2001;if(/mouth/i.test(n))return 2002;if(/eyeiris/i.test(n))return 2450;if(/hairback/i.test(n))return 2451;if(/_hair/i.test(n))return 2452;if(/shoes/i.test(n))return 2453;if(/body.*skin/i.test(n))return 2454;if(/_cloth/i.test(n))return 2455;if(/eyeextra/i.test(n))return 3000;if(/eyehighlight|highlight/i.test(n))return 3001;if(/brow/i.test(n))return 3002;if(/eyeline/i.test(n))return 3003;if(/eyelash/i.test(n))return 4500;return 2500}
|
| 15 |
function reorderMaterials(target,loadType){if(loadType==='stage'||loadType==='dome')return;target.traverse(child=>{if(!child.isMesh)return;const mats=child.material;if(!Array.isArray(mats)||mats.length<=1)return;const geo=child.geometry;if(!geo||!geo.groups||geo.groups.length!==mats.length)return;if(mats[0]&&/^\d{4}_/.test(mats[0].name||''))return;const indexed=mats.map((m,i)=>({mat:m,group:{...geo.groups[i]},pri:getDrawPriority(m.name)}));indexed.sort((a,b)=>a.pri-b.pri);child.material=indexed.map(x=>x.mat);geo.groups=indexed.map((x,i)=>{const g={...x.group};g.materialIndex=i;return g})})}
|
| 16 |
function buildMatDebugUI(){const container=document.getElementById('mat-debug');if(!container)return;container.innerHTML='';const targets=[];if(mesh)targets.push({label:'モデル1',m:mesh});if(mesh2)targets.push({label:'モデル2',m:mesh2});if(!targets.length){container.innerHTML='<div style="color:#888;padding:8px">モデル未読込</div>';return}targets.forEach(({label,m:target})=>{const header=document.createElement('div');header.style.cssText='color:#ff69b4;font-size:11px;padding:4px 0;border-bottom:1px solid #ff1493';header.textContent=`【${label}】`;container.appendChild(header);const matList=[];target.traverse(child=>{if(!child.isMesh)return;(Array.isArray(child.material)?child.material:[child.material]).forEach(mat=>{matList.push(mat)})});matList.sort((a,b)=>(a.name||'').localeCompare(b.name||''));matList.forEach((mat,i)=>{const row=document.createElement('div');row.className='mat-row';const name=document.createElement('span');name.className='mat-name';name.textContent=mat.name||`(unnamed#${i})`;row.appendChild(name);const mapBtn=document.createElement('button');mapBtn.textContent=mat.map?'map:ON':'map:無';mapBtn.className=mat.map?'':'off';if(!mat.map&&!mat.userData._origMap)mapBtn.disabled=true;mapBtn.addEventListener('click',()=>{if(!mat.userData._origMap&&mat.map)mat.userData._origMap=mat.map;if(mat.map){mat.map=null;mapBtn.textContent='map:OFF';mapBtn.className='off'}else if(mat.userData._origMap){mat.map=mat.userData._origMap;mapBtn.textContent='map:ON';mapBtn.className=''}mat.needsUpdate=true});row.appendChild(mapBtn);const visBtn=document.createElement('button');visBtn.textContent='表示';visBtn.addEventListener('click',()=>{mat.visible=!mat.visible;visBtn.textContent=mat.visible?'表示':'非表示';visBtn.className=mat.visible?'':'off';mat.needsUpdate=true});row.appendChild(visBtn);container.appendChild(row)})})}
|
| 17 |
-
async function init(){dbg(`[Device] ${navigator.userAgent.slice(0,80)}`,"info");dbg(`[Screen] ${screen.width}x${screen.height} dpr=${devicePixelRatio}`,"info");dbg(`[Camera] pos=(0,20,100) target=(0,10,0) fov=45`,"info");try{if(typeof Ammo==='function')await Ammo().then(()=>{ammoInitialized=true;dbg("[Init] Ammo.js OK","info")})}catch(e){dbg("[Init] Ammo失敗","error")}scene=new THREE.Scene();scene.background=new THREE.Color(0x220022);clock=new THREE.Clock();camera=new THREE.PerspectiveCamera(45,innerWidth/innerHeight,1,20000);camera.position.set(0,20,100);renderer=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true,logarithmicDepthBuffer:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setSize(innerWidth,innerHeight);renderer.outputColorSpace=THREE.SRGBColorSpace;document.getElementById('container').appendChild(renderer.domElement);controls=new OrbitControls(camera,renderer.domElement);controls.target.set(0,10,0);controls.enableDamping=true;controls.dampingFactor=0.1;gridHelper=new THREE.GridHelper(200,20,0xff1493,0x444444);scene.add(gridHelper);const fg=new THREE.PlaneGeometry(200,200);const fm=new THREE.MeshPhongMaterial({color:0x888888,transparent:true,opacity:0.5,side:THREE.DoubleSide,depthWrite:false});floorMesh=new THREE.Mesh(fg,fm);floorMesh.rotation.x=-Math.PI/2;floorMesh.receiveShadow=true;floorMesh.visible=false;floorMesh.renderOrder=20;scene.add(floorMesh);ambLight=new THREE.AmbientLight(0xffffff,0.8);scene.add(ambLight);mainLight=new THREE.DirectionalLight(0xffffff,1.2);mainLight.position.set(5,20,10);mainLight.castShadow=true;mainLight.shadow.mapSize.set(2048,2048);mainLight.shadow.camera.near=0.5;mainLight.shadow.camera.far=200;mainLight.shadow.camera.left=-50;mainLight.shadow.camera.right=50;mainLight.shadow.camera.top=50;mainLight.shadow.camera.bottom=-50;scene.add(mainLight);subLight=new THREE.DirectionalLight(0xffffff,0.4);subLight.position.set(-5,10,-5);scene.add(subLight);dbg("[Init] Scene OK
|
| 18 |
async function processFiles(files,t){for(let i=0;i<files.length;i++){const file=files[i];const name=file.name.toLowerCase().normalize('NFC');if(name.endsWith('.zip'))await processZip(file,t);else{const url=URL.createObjectURL(file);const n=normalizePath(file.name);const fn=n.split('/').pop();modelData[t].fileMap[n]=url;modelData[t].fileMap[fn]=url}}}
|
| 19 |
async function processZip(zipFile,t){try{const zip=await JSZip.loadAsync(zipFile,{decodeFileName:b=>{try{return new TextDecoder("utf-8",{fatal:true}).decode(b).normalize('NFC')}catch(e){try{return new TextDecoder("shift_jis").decode(b).normalize('NFC')}catch(e2){return new TextDecoder("utf-8",{fatal:false}).decode(b).normalize('NFC')}}}});const entries=Object.keys(zip.files).filter(k=>!zip.files[k].dir);let pmxDir='';for(const p of entries)if(/\.(pmx|pmd)$/i.test(p)){const n=p.replace(/\\/g,'/').normalize('NFC');const pts=n.split('/');pts.pop();pmxDir=pts.length?pts.join('/')+'/':'';break}const f=modelData[t].fileMap;let count=0;for(const rp of entries){const u8=await zip.files[rp].async("uint8array");const ext=rp.split('.').pop().toLowerCase();const mm={'png':'image/png','jpg':'image/jpeg','jpeg':'image/jpeg','gif':'image/gif','bmp':'image/bmp','tga':'image/x-tga'};const blob=new Blob([u8],{type:mm[ext]||'application/octet-stream'});const url=URL.createObjectURL(blob);const nf=normalizePath(rp);const fn=nf.split('/').pop();f[nf]=url;f[fn]=url;if(pmxDir){const pd=pmxDir.toLowerCase().normalize('NFC');if(nf.startsWith(pd)){const rel=nf.substring(pd.length);if(rel&&rel!==fn)f[rel]=url}}count++}dbg(`[ZIP] ${zipFile.name}: ${count}ファイル`,"info")}catch(e){dbg(`[ZIP] 展開失敗: ${e.message}`,"error")}}
|
| 20 |
-
// ★v84: v82と完全同一のマテリアル設定(polygonOffset削除、CLOTH/SHOESをv82に戻す)
|
| 21 |
function fixMMDMaterials(target,loadType){let mc=0,fc=0,emFix=0;target.traverse(child=>{if(!child.isMesh)return;child.frustumCulled=false;const mats=Array.isArray(child.material)?child.material:[child.material];mats.forEach((m)=>{mc++;const ml=(m.name||'').toLowerCase();const ha=m.map&&m.map.format===THREE.RGBAFormat&&!/\.(jpg|jpeg)$/i.test(m.map?.name||'');const it=m.opacity<1;let action='none';if(loadType==='stage'||loadType==='dome'){m.side=THREE.DoubleSide;if(it){m.transparent=true;m.depthWrite=false;fc++;action='stage-trans'}else{action='stage-opaque'}m.needsUpdate=true}else if(/eyehighlight|highlight/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='highlight(dw:f)'}else if(/eyeextra/i.test(ml)){m.transparent=true;m.alphaTest=0;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='eyeExtra(dw:f)'}else if(/eyewhite/i.test(ml)){fc++;action='eyeWhite'}else if(/eyeiris/i.test(ml)){m.depthWrite=false;fc++;action='eyeIris(dw:f)'}else if(/eyelash/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.01;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.FrontSide;fc++;action='eyelash'}else if((/eyeline/i.test(ml)||/brow/i.test(ml))&&ha){m.transparent=true;m.alphaTest=0.01;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='eyeline/brow'}else if(/_HAIR(?:_\d+)?$/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.05;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='hair'}else if(/_CLOTH(?:_\d+)?$/i.test(ml)&&ha){const isShoes=/shoes/i.test(ml);m.transparent=true;m.alphaTest=isShoes?0.5:0.01;m.depthWrite=isShoes?true:false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++;action=isShoes?'cloth(shoes)':'cloth'}else if(it){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++;action='opacity<1'}else{action='default'}
|
| 22 |
if(loadType!=='stage'&&loadType!=='dome'&&m.emissive){const oldEm=m.emissive.getHexString();if(oldEm!=='000000'){m.emissive.setHex(0x000000);emFix++}}
|
| 23 |
m.needsUpdate=true;dbg(` [Mat#${mc}] "${m.name}" → ${action}`)})});dbg(`[Material] ${mc}個, ${fc}修正, em=${emFix} (${loadType})`,"info")}
|
|
@@ -27,7 +45,11 @@ function handleSeekInput(e){if(seekRAFPending)return;seekRAFPending=true;const t
|
|
| 27 |
function handleSeekFinalize(){if(!isSeeking)return;isSeeking=false;const shouldResume=wasPlayingBeforeSeek;wasPlayingBeforeSeek=false;if(seekFinalizeTimer)clearTimeout(seekFinalizeTimer);seekFinalizeTimer=setTimeout(()=>{seekFinalizeTimer=null;const time=parseFloat(document.getElementById('seek-bar').value);helperSeekTo(time);[mesh,mesh2].forEach(m=>{if(!m||!helper.objects.has(m))return;const obj=helper.objects.get(m);if(obj.physics)obj.physics.reset()});audioPausedAt=time;if(shouldResume)play()},150)}
|
| 28 |
async function loadMotions(files,targetType,targetMesh){for(let i=0;i<files.length;i++){const file=files[i];const name=file.name.toLowerCase().normalize('NFC');if(!name.endsWith('.vmd')&&!name.endsWith('.vpd'))continue;const url=URL.createObjectURL(file);modelData[targetType].fileMap[name]=url;const virtualUrl="virtual_path/"+name;await new Promise(resolve=>{if(name.endsWith('.vmd')){restoreInitialBonePose(targetMesh);modelData[targetType].loader.loadAnimation(virtualUrl,targetMesh,vmd=>{try{if(helper.objects.has(targetMesh))helper.remove(targetMesh);restoreInitialBonePose(targetMesh);const usePhys=modelPhysicsMap.get(targetMesh)||false;helper.add(targetMesh,{animation:vmd,physics:usePhys});if(usePhys){const obj=helper.objects.get(targetMesh);if(obj&&obj.physics)obj.physics.reset()}helperSeekTo(0);audioPausedAt=0;document.getElementById('seek-bar').value=0;document.getElementById('time-current').textContent='0:00';maxDuration=Math.max(maxDuration,vmd.duration);updateSeekBarLimit();dbg(`[VMD] ${file.name} (${vmd.duration.toFixed(1)}s) physics:${usePhys}`,"info")}catch(e){dbg(`[VMD] 失敗: ${e.message}`,"error")}resolve()},null,()=>{resolve()})}else{file.arrayBuffer().then(buf=>{const sjisBlob=new Blob([buf],{type:'text/plain; charset=shift_jis'});const sjisUrl=URL.createObjectURL(sjisBlob);modelData[targetType].loader.loadVPD(sjisUrl,false,vpd=>{URL.revokeObjectURL(sjisUrl);try{restoreInitialBonePose(targetMesh);helper.pose(targetMesh,vpd);targetMesh.updateMatrixWorld(true);const obj=helper.objects.get(targetMesh);if(obj&&obj.physics)obj.physics.reset();dbg(`[VPD] ${file.name} 適用`,"info");buildMorphUI()}catch(e){}resolve()},null,()=>{resolve()})}).catch(()=>{resolve()})}});}updateStatus("モーション準備完了♡")}
|
| 29 |
function findFileInMap(ext,t){for(let key in modelData[t].fileMap)if(key.endsWith(ext))return key;return null}
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
function clearAll(){if(isPlaying)pause();[mesh,mesh2].forEach(m=>{if(m){scene.remove(m);if(helper.objects.has(m))helper.remove(m)}});mesh=mesh2=null;if(helper.camera)try{helper.remove(camera)}catch(e){}cameraVmdEnabled=false;helper.enabled.cameraAnimation=false;controls.enabled=true;document.getElementById('cam-vmd-toggle').style.display='none';document.querySelectorAll('.aspect-btn').forEach(b=>b.style.display='none');forcedAspect=null;updateRendererSize();document.getElementById('morph-panel').style.display='none';document.getElementById('morph-sliders').innerHTML='';document.getElementById('morph-tabs').innerHTML='';const md=document.getElementById('mat-debug');if(md)md.innerHTML='';stageMeshes.forEach(s=>scene.remove(s));stageMeshes=[];domeMeshes.forEach(s=>scene.remove(s));domeMeshes=[];['mesh','mesh2','stage','dome'].forEach(t=>{for(const k in modelData[t].fileMap){const v=modelData[t].fileMap[k];if(typeof v==='string'&&v.startsWith('blob:'))URL.revokeObjectURL(v)}modelData[t].fileMap={}});audioBuffer=null;maxDuration=0;audioPausedAt=0;document.querySelectorAll('.btn-lab').forEach(l=>l.classList.remove('ready'));document.querySelectorAll('input[type="file"]').forEach(inp=>inp.value='');document.getElementById('seek-bar').value=0;document.getElementById('time-current').textContent="0:00";document.getElementById('time-total').textContent="-0:00";updateStatus("クリアしました♡");dbg("[Clear] 全クリア","info")}
|
| 32 |
function togglePlay(){if(audioContext&&audioContext.state==='suspended')audioContext.resume();isPlaying?pause():play()}
|
| 33 |
function play(){if(audioBuffer&&audioContext){try{if(audioSource)try{audioSource.stop()}catch(e){}audioSource=audioContext.createBufferSource();audioSource.buffer=audioBuffer;audioSource.connect(audioGainNode);audioSource.playbackRate.value=playbackSpeed;audioStartTime=audioContext.currentTime-audioPausedAt/playbackSpeed;audioSource.start(0,audioPausedAt)}catch(e){}}document.getElementById('play-icon').style.display='none';document.getElementById('pause-icon').style.display='block';isPlaying=true;clock.getDelta();if(uiHideTimer)clearTimeout(uiHideTimer);if(!uiManualHidden)uiHideTimer=setTimeout(()=>{if(!uiManualHidden)document.body.classList.add('ui-hidden')},UI_HIDE_DELAY)}
|
|
|
|
| 1 |
import*as THREE from'three';import{MMDLoader}from'three/examples/jsm/loaders/MMDLoader';import{TGALoader}from'three/examples/jsm/loaders/TGALoader';import{MMDAnimationHelper}from'three/examples/jsm/animation/MMDAnimationHelper';import{OrbitControls}from'three/examples/jsm/controls/OrbitControls';
|
| 2 |
const debugLogEl=document.getElementById('debug-log'),debugPanel=document.getElementById('debug-panel'),debugToggle=document.getElementById('debug-toggle');let debugVisible=false;debugToggle.addEventListener('click',e=>{e.preventDefault();e.stopPropagation();debugVisible=!debugVisible;if(debugVisible){debugPanel.removeAttribute('hidden');debugPanel.classList.add('visible')}else{debugPanel.classList.remove('visible');debugPanel.setAttribute('hidden','')}});debugToggle.addEventListener('touchend',e=>{e.preventDefault();debugToggle.click()});document.getElementById('debug-clear-btn').addEventListener('click',()=>{debugLogEl.innerHTML=''});document.getElementById('debug-copy-btn').addEventListener('click',()=>{const btn=document.getElementById('debug-copy-btn');navigator.clipboard.writeText(debugLogEl.innerText).then(()=>{btn.textContent='✅Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)}).catch(()=>{const ta=document.createElement('textarea');ta.value=debugLogEl.innerText;document.body.appendChild(ta);ta.select();document.execCommand('copy');document.body.removeChild(ta);btn.textContent='✅Copied!';setTimeout(()=>btn.textContent='📋 Copy All',1500)})});document.getElementById('tab-log').addEventListener('click',()=>{document.getElementById('debug-log').style.display='block';document.getElementById('mat-debug').style.display='none';document.getElementById('tab-log').classList.add('active');document.getElementById('tab-mat').classList.remove('active')});document.getElementById('tab-mat').addEventListener('click',()=>{document.getElementById('debug-log').style.display='none';document.getElementById('mat-debug').style.display='block';document.getElementById('tab-mat').classList.add('active');document.getElementById('tab-log').classList.remove('active')});
|
| 3 |
+
const APP_VER='v85';let _dbgH=false;function _t(){const d=new Date();return`${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`}function _ds(){const d=new Date();return`${d.getFullYear()}/${String(d.getMonth()+1).padStart(2,'0')}/${String(d.getDate()).padStart(2,'0')}`}
|
| 4 |
function dbg(msg,level='log'){if(!_dbgH){_dbgH=true;const h=document.createElement('div');h.className='info';h.textContent=`[MMD_pmx_Player_${APP_VER}_${_ds()}]`;debugLogEl.appendChild(h)}const cls=level==='warn'?'warn':level==='error'?'error':level==='info'?'info':'';const line=document.createElement('div');if(cls)line.className=cls;line.textContent=`[${_t()}] ${msg}`;debugLogEl.appendChild(line);debugLogEl.scrollTop=debugLogEl.scrollHeight;if(level==='error')console.error(msg);else if(level==='warn')console.warn(msg);else console.log(msg)}
|
| 5 |
const FALLBACK_PIXEL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";function generateToonDataURL(tR,tG,tB,bR,bG,bB){const c=document.createElement('canvas');c.width=1;c.height=256;const x=c.getContext('2d');const g=x.createLinearGradient(0,0,0,256);g.addColorStop(0,`rgb(${tR},${tG},${tB})`);g.addColorStop(1,`rgb(${bR},${bG},${bB})`);x.fillStyle=g;x.fillRect(0,0,1,256);return c.toDataURL('image/png')}const BUILTIN_TOONS={};const TOON_DEFS=[[255,255,255,180,180,180],[255,220,220,160,120,120],[255,240,210,160,140,100],[255,255,230,160,160,110],[220,255,220,110,160,110],[220,255,255,110,160,160],[210,220,255,100,110,160],[255,220,255,160,110,160],[245,245,245,150,150,150],[230,230,230,100,100,100]];for(let i=0;i<10;i++){const n=String(i+1).padStart(2,'0');const d=TOON_DEFS[i];BUILTIN_TOONS[`toon${n}.bmp`]=generateToonDataURL(d[0],d[1],d[2],d[3],d[4],d[5])}
|
| 6 |
if(window.CharsetEncoder){window.CharsetEncoder.install();const orig=window.CharsetEncoder.decode;window.CharsetEncoder.decode=function(data,enc){try{return orig(data,enc||'shift_jis')}catch(e){try{return new TextDecoder('shift_jis').decode(data)}catch(e2){return new TextDecoder('utf-8').decode(data)}}}}
|
|
|
|
| 11 |
function restoreInitialBonePose(m){if(!m||!m.userData._ib)return;const saved=m.userData._ib;const bm={};m.skeleton.bones.forEach(b=>{bm[b.name]=b});for(const d of saved){const bone=bm[d.n];if(!bone)continue;bone.position.copy(d.p);bone.quaternion.copy(d.q);bone.scale.copy(d.s)}m.skeleton.bones.forEach(b=>b.updateMatrix());m.skeleton.update();m.updateMatrixWorld(true)}
|
| 12 |
function setupValInput(inputId,sliderId,applyFn){const inp=document.getElementById(inputId);const sl=document.getElementById(sliderId);if(!inp||!sl)return;inp.addEventListener('blur',()=>{const v=parseFloat(inp.value);if(isNaN(v)){inp.value=sl.value;return}const min=parseFloat(sl.min),max=parseFloat(sl.max);const clamped=Math.max(min,Math.min(max,v));sl.value=clamped;inp.value=clamped;if(applyFn)applyFn(clamped)});inp.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();inp.blur()}})}
|
| 13 |
function hasMatPrefix(target){let found=false;target.traverse(child=>{if(found||!child.isMesh)return;const mats=Array.isArray(child.material)?child.material:[child.material];if(mats[0]&&/^\d{4}_/.test(mats[0].name||''))found=true});return found}
|
| 14 |
+
|
| 15 |
+
// ★v85: 剛体ダンプ関数(デバッグ用)
|
| 16 |
+
function dumpRigidBodies(target,label){
|
| 17 |
+
const mmd=target.geometry?.userData?.MMD;
|
| 18 |
+
if(!mmd||!mmd.rigidBodies){dbg(`[RBDump] ${label}: rigidBodies無し`,"warn");return}
|
| 19 |
+
const bones=target.skeleton?.bones||[];
|
| 20 |
+
const rbs=mmd.rigidBodies;
|
| 21 |
+
const constraints=mmd.constraints||[];
|
| 22 |
+
dbg(`[RBDump] === ${label} === 剛体:${rbs.length} 制約:${constraints.length} ボーン:${bones.length}`,"info");
|
| 23 |
+
// type別カウント
|
| 24 |
+
let t0=0,t1=0,t2=0;
|
| 25 |
+
rbs.forEach(r=>{if(r.type===0)t0++;else if(r.type===1)t1++;else t2++});
|
| 26 |
+
dbg(`[RBDump] type0(kinematic):${t0} type1(physics):${t1} type2(phys+bone):${t2}`,"info");
|
| 27 |
+
// 各剛体の詳細
|
| 28 |
+
rbs.forEach((r,i)=>{
|
| 29 |
+
const bn=(r.boneIndex>=0&&r.boneIndex<bones.length)?bones[r.boneIndex].name:'(none)';
|
| 30 |
+
dbg(` [RB${i}] "${r.name}" bone[${r.boneIndex}]="${bn}" type=${r.type} shape=${r.shapeType} w=${r.weight.toFixed(2)} grp=${r.groupIndex} mask=${r.groupTarget}`);
|
| 31 |
+
})}
|
| 32 |
+
|
| 33 |
function getDrawPriority(name){const n=(name||'').toLowerCase();if(/eyewhite/i.test(n))return 2000;if(/face.*skin/i.test(n))return 2001;if(/mouth/i.test(n))return 2002;if(/eyeiris/i.test(n))return 2450;if(/hairback/i.test(n))return 2451;if(/_hair/i.test(n))return 2452;if(/shoes/i.test(n))return 2453;if(/body.*skin/i.test(n))return 2454;if(/_cloth/i.test(n))return 2455;if(/eyeextra/i.test(n))return 3000;if(/eyehighlight|highlight/i.test(n))return 3001;if(/brow/i.test(n))return 3002;if(/eyeline/i.test(n))return 3003;if(/eyelash/i.test(n))return 4500;return 2500}
|
| 34 |
function reorderMaterials(target,loadType){if(loadType==='stage'||loadType==='dome')return;target.traverse(child=>{if(!child.isMesh)return;const mats=child.material;if(!Array.isArray(mats)||mats.length<=1)return;const geo=child.geometry;if(!geo||!geo.groups||geo.groups.length!==mats.length)return;if(mats[0]&&/^\d{4}_/.test(mats[0].name||''))return;const indexed=mats.map((m,i)=>({mat:m,group:{...geo.groups[i]},pri:getDrawPriority(m.name)}));indexed.sort((a,b)=>a.pri-b.pri);child.material=indexed.map(x=>x.mat);geo.groups=indexed.map((x,i)=>{const g={...x.group};g.materialIndex=i;return g})})}
|
| 35 |
function buildMatDebugUI(){const container=document.getElementById('mat-debug');if(!container)return;container.innerHTML='';const targets=[];if(mesh)targets.push({label:'モデル1',m:mesh});if(mesh2)targets.push({label:'モデル2',m:mesh2});if(!targets.length){container.innerHTML='<div style="color:#888;padding:8px">モデル未読込</div>';return}targets.forEach(({label,m:target})=>{const header=document.createElement('div');header.style.cssText='color:#ff69b4;font-size:11px;padding:4px 0;border-bottom:1px solid #ff1493';header.textContent=`【${label}】`;container.appendChild(header);const matList=[];target.traverse(child=>{if(!child.isMesh)return;(Array.isArray(child.material)?child.material:[child.material]).forEach(mat=>{matList.push(mat)})});matList.sort((a,b)=>(a.name||'').localeCompare(b.name||''));matList.forEach((mat,i)=>{const row=document.createElement('div');row.className='mat-row';const name=document.createElement('span');name.className='mat-name';name.textContent=mat.name||`(unnamed#${i})`;row.appendChild(name);const mapBtn=document.createElement('button');mapBtn.textContent=mat.map?'map:ON':'map:無';mapBtn.className=mat.map?'':'off';if(!mat.map&&!mat.userData._origMap)mapBtn.disabled=true;mapBtn.addEventListener('click',()=>{if(!mat.userData._origMap&&mat.map)mat.userData._origMap=mat.map;if(mat.map){mat.map=null;mapBtn.textContent='map:OFF';mapBtn.className='off'}else if(mat.userData._origMap){mat.map=mat.userData._origMap;mapBtn.textContent='map:ON';mapBtn.className=''}mat.needsUpdate=true});row.appendChild(mapBtn);const visBtn=document.createElement('button');visBtn.textContent='表示';visBtn.addEventListener('click',()=>{mat.visible=!mat.visible;visBtn.textContent=mat.visible?'表示':'非表示';visBtn.className=mat.visible?'':'off';mat.needsUpdate=true});row.appendChild(visBtn);container.appendChild(row)})})}
|
| 36 |
+
async function init(){dbg(`[Device] ${navigator.userAgent.slice(0,80)}`,"info");dbg(`[Screen] ${screen.width}x${screen.height} dpr=${devicePixelRatio}`,"info");dbg(`[Camera] pos=(0,20,100) target=(0,10,0) fov=45`,"info");try{if(typeof Ammo==='function')await Ammo().then(()=>{ammoInitialized=true;dbg("[Init] Ammo.js OK","info")})}catch(e){dbg("[Init] Ammo失敗","error")}scene=new THREE.Scene();scene.background=new THREE.Color(0x220022);clock=new THREE.Clock();camera=new THREE.PerspectiveCamera(45,innerWidth/innerHeight,1,20000);camera.position.set(0,20,100);renderer=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true,logarithmicDepthBuffer:true});renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setSize(innerWidth,innerHeight);renderer.outputColorSpace=THREE.SRGBColorSpace;document.getElementById('container').appendChild(renderer.domElement);controls=new OrbitControls(camera,renderer.domElement);controls.target.set(0,10,0);controls.enableDamping=true;controls.dampingFactor=0.1;gridHelper=new THREE.GridHelper(200,20,0xff1493,0x444444);scene.add(gridHelper);const fg=new THREE.PlaneGeometry(200,200);const fm=new THREE.MeshPhongMaterial({color:0x888888,transparent:true,opacity:0.5,side:THREE.DoubleSide,depthWrite:false});floorMesh=new THREE.Mesh(fg,fm);floorMesh.rotation.x=-Math.PI/2;floorMesh.receiveShadow=true;floorMesh.visible=false;floorMesh.renderOrder=20;scene.add(floorMesh);ambLight=new THREE.AmbientLight(0xffffff,0.8);scene.add(ambLight);mainLight=new THREE.DirectionalLight(0xffffff,1.2);mainLight.position.set(5,20,10);mainLight.castShadow=true;mainLight.shadow.mapSize.set(2048,2048);mainLight.shadow.camera.near=0.5;mainLight.shadow.camera.far=200;mainLight.shadow.camera.left=-50;mainLight.shadow.camera.right=50;mainLight.shadow.camera.top=50;mainLight.shadow.camera.bottom=-50;scene.add(mainLight);subLight=new THREE.DirectionalLight(0xffffff,0.4);subLight.position.set(-5,10,-5);scene.add(subLight);dbg("[Init] Scene OK","info");['mesh','mesh2','stage','dome'].forEach(type=>{const mgr=new THREE.LoadingManager();mgr.addHandler(/\.tga$/i,new TGALoader(mgr));mgr.setURLModifier(url=>{let c=url.split(/[?#]/)[0];if(c.startsWith('blob:')||c.startsWith('data:'))return c;const n=normalizePath(c);let sp=n;if(sp.includes('virtual_path/'))sp=sp.split('virtual_path/').pop();const fn=sp.split('/').pop();const f=modelData[type].fileMap;if(BUILTIN_TOONS[fn]&&!f[fn])return BUILTIN_TOONS[fn];if(f[sp])return f[sp];if(f[fn])return f[fn];for(const k in f)if(k.endsWith('/'+fn)||k===fn)return f[k];const bn=fn.replace(/\.[^.]+$/,'');for(const ext of['.png','.jpg','.jpeg','.tga','.bmp','.gif']){const an=bn+ext;if(f[an])return f[an];for(const k in f)if(k.endsWith('/'+an))return f[k]}if(bn.length>=3)for(const k in f){if(k.split('/').pop().replace(/\.[^.]+$/,'')===bn)return f[k]}if(/\.(png|jpg|jpeg|tga|bmp|gif|dds|spa|sph)$/i.test(fn)){dbg(`[Tex]⚠未解決:${fn}(${type})`,"error");return FALLBACK_PIXEL}return url});mgr.onError=url=>dbg(`[Load]エラー:${url}`,"error");modelData[type].loader=new MMDLoader(mgr);modelData[type].manager=mgr});dbg("[Init] Loaders OK","info");helper=new MMDAnimationHelper({afterglow:2.0,resetPhysicsOnLoop:true});dbg("[Init] Helper OK","info");setupEventListeners();dbg("[Init] Events OK","info");animate();window.__mainLight=mainLight;window.__subLight=subLight;window.__ambLight=ambLight;window.__appReady=true;window.__processFiles=processFiles;window.__findFileInMap=findFileInMap;window.__loadPmx=loadPmx;window.__showLoading=showLoading;window.__updateStatus=updateStatus;window.__dbg=dbg;}
|
| 37 |
async function processFiles(files,t){for(let i=0;i<files.length;i++){const file=files[i];const name=file.name.toLowerCase().normalize('NFC');if(name.endsWith('.zip'))await processZip(file,t);else{const url=URL.createObjectURL(file);const n=normalizePath(file.name);const fn=n.split('/').pop();modelData[t].fileMap[n]=url;modelData[t].fileMap[fn]=url}}}
|
| 38 |
async function processZip(zipFile,t){try{const zip=await JSZip.loadAsync(zipFile,{decodeFileName:b=>{try{return new TextDecoder("utf-8",{fatal:true}).decode(b).normalize('NFC')}catch(e){try{return new TextDecoder("shift_jis").decode(b).normalize('NFC')}catch(e2){return new TextDecoder("utf-8",{fatal:false}).decode(b).normalize('NFC')}}}});const entries=Object.keys(zip.files).filter(k=>!zip.files[k].dir);let pmxDir='';for(const p of entries)if(/\.(pmx|pmd)$/i.test(p)){const n=p.replace(/\\/g,'/').normalize('NFC');const pts=n.split('/');pts.pop();pmxDir=pts.length?pts.join('/')+'/':'';break}const f=modelData[t].fileMap;let count=0;for(const rp of entries){const u8=await zip.files[rp].async("uint8array");const ext=rp.split('.').pop().toLowerCase();const mm={'png':'image/png','jpg':'image/jpeg','jpeg':'image/jpeg','gif':'image/gif','bmp':'image/bmp','tga':'image/x-tga'};const blob=new Blob([u8],{type:mm[ext]||'application/octet-stream'});const url=URL.createObjectURL(blob);const nf=normalizePath(rp);const fn=nf.split('/').pop();f[nf]=url;f[fn]=url;if(pmxDir){const pd=pmxDir.toLowerCase().normalize('NFC');if(nf.startsWith(pd)){const rel=nf.substring(pd.length);if(rel&&rel!==fn)f[rel]=url}}count++}dbg(`[ZIP] ${zipFile.name}: ${count}ファイル`,"info")}catch(e){dbg(`[ZIP] 展開失敗: ${e.message}`,"error")}}
|
|
|
|
| 39 |
function fixMMDMaterials(target,loadType){let mc=0,fc=0,emFix=0;target.traverse(child=>{if(!child.isMesh)return;child.frustumCulled=false;const mats=Array.isArray(child.material)?child.material:[child.material];mats.forEach((m)=>{mc++;const ml=(m.name||'').toLowerCase();const ha=m.map&&m.map.format===THREE.RGBAFormat&&!/\.(jpg|jpeg)$/i.test(m.map?.name||'');const it=m.opacity<1;let action='none';if(loadType==='stage'||loadType==='dome'){m.side=THREE.DoubleSide;if(it){m.transparent=true;m.depthWrite=false;fc++;action='stage-trans'}else{action='stage-opaque'}m.needsUpdate=true}else if(/eyehighlight|highlight/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='highlight(dw:f)'}else if(/eyeextra/i.test(ml)){m.transparent=true;m.alphaTest=0;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='eyeExtra(dw:f)'}else if(/eyewhite/i.test(ml)){fc++;action='eyeWhite'}else if(/eyeiris/i.test(ml)){m.depthWrite=false;fc++;action='eyeIris(dw:f)'}else if(/eyelash/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.01;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.FrontSide;fc++;action='eyelash'}else if((/eyeline/i.test(ml)||/brow/i.test(ml))&&ha){m.transparent=true;m.alphaTest=0.01;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='eyeline/brow'}else if(/_HAIR(?:_\d+)?$/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.05;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='hair'}else if(/_CLOTH(?:_\d+)?$/i.test(ml)&&ha){const isShoes=/shoes/i.test(ml);m.transparent=true;m.alphaTest=isShoes?0.5:0.01;m.depthWrite=isShoes?true:false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++;action=isShoes?'cloth(shoes)':'cloth'}else if(it){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++;action='opacity<1'}else{action='default'}
|
| 40 |
if(loadType!=='stage'&&loadType!=='dome'&&m.emissive){const oldEm=m.emissive.getHexString();if(oldEm!=='000000'){m.emissive.setHex(0x000000);emFix++}}
|
| 41 |
m.needsUpdate=true;dbg(` [Mat#${mc}] "${m.name}" → ${action}`)})});dbg(`[Material] ${mc}個, ${fc}修正, em=${emFix} (${loadType})`,"info")}
|
|
|
|
| 45 |
function handleSeekFinalize(){if(!isSeeking)return;isSeeking=false;const shouldResume=wasPlayingBeforeSeek;wasPlayingBeforeSeek=false;if(seekFinalizeTimer)clearTimeout(seekFinalizeTimer);seekFinalizeTimer=setTimeout(()=>{seekFinalizeTimer=null;const time=parseFloat(document.getElementById('seek-bar').value);helperSeekTo(time);[mesh,mesh2].forEach(m=>{if(!m||!helper.objects.has(m))return;const obj=helper.objects.get(m);if(obj.physics)obj.physics.reset()});audioPausedAt=time;if(shouldResume)play()},150)}
|
| 46 |
async function loadMotions(files,targetType,targetMesh){for(let i=0;i<files.length;i++){const file=files[i];const name=file.name.toLowerCase().normalize('NFC');if(!name.endsWith('.vmd')&&!name.endsWith('.vpd'))continue;const url=URL.createObjectURL(file);modelData[targetType].fileMap[name]=url;const virtualUrl="virtual_path/"+name;await new Promise(resolve=>{if(name.endsWith('.vmd')){restoreInitialBonePose(targetMesh);modelData[targetType].loader.loadAnimation(virtualUrl,targetMesh,vmd=>{try{if(helper.objects.has(targetMesh))helper.remove(targetMesh);restoreInitialBonePose(targetMesh);const usePhys=modelPhysicsMap.get(targetMesh)||false;helper.add(targetMesh,{animation:vmd,physics:usePhys});if(usePhys){const obj=helper.objects.get(targetMesh);if(obj&&obj.physics)obj.physics.reset()}helperSeekTo(0);audioPausedAt=0;document.getElementById('seek-bar').value=0;document.getElementById('time-current').textContent='0:00';maxDuration=Math.max(maxDuration,vmd.duration);updateSeekBarLimit();dbg(`[VMD] ${file.name} (${vmd.duration.toFixed(1)}s) physics:${usePhys}`,"info")}catch(e){dbg(`[VMD] 失敗: ${e.message}`,"error")}resolve()},null,()=>{resolve()})}else{file.arrayBuffer().then(buf=>{const sjisBlob=new Blob([buf],{type:'text/plain; charset=shift_jis'});const sjisUrl=URL.createObjectURL(sjisBlob);modelData[targetType].loader.loadVPD(sjisUrl,false,vpd=>{URL.revokeObjectURL(sjisUrl);try{restoreInitialBonePose(targetMesh);helper.pose(targetMesh,vpd);targetMesh.updateMatrixWorld(true);const obj=helper.objects.get(targetMesh);if(obj&&obj.physics)obj.physics.reset();dbg(`[VPD] ${file.name} 適用`,"info");buildMorphUI()}catch(e){}resolve()},null,()=>{resolve()})}).catch(()=>{resolve()})}});}updateStatus("モーション準備完了♡")}
|
| 47 |
function findFileInMap(ext,t){for(let key in modelData[t].fileMap)if(key.endsWith(ext))return key;return null}
|
| 48 |
+
// ★v85: 剛体ダンプ追加、物理制御はv82/v84と同じ
|
| 49 |
+
function loadPmx(pmxPath,loadType){if(!pmxPath)return;const fn=pmxPath.split('/').pop().toLowerCase().normalize('NFC');const vurl="virtual_path/"+fn;dbg(`[PMX] ロード: ${fn} (${loadType})`,"info");modelData[loadType].loader.load(vurl,target=>{if(!target){dbg("[PMX] null","error");showLoading(false);return}dbg(`[PMX] 成功`,"info");if(loadType==='stage'){stageMeshes.forEach(s=>scene.remove(s));stageMeshes=[target]}else if(loadType==='dome'){domeMeshes.forEach(s=>scene.remove(s));domeMeshes=[target]}else if(loadType==='mesh2'){if(mesh2){scene.remove(mesh2);if(helper.objects.has(mesh2))helper.remove(mesh2)}mesh2=target}else{if(mesh){scene.remove(mesh);if(helper.objects.has(mesh))helper.remove(mesh)}mesh=target}fixMMDMaterials(target,loadType);reorderMaterials(target,loadType);scene.add(target);if(shadowEnabled&&loadType!=='stage'&&loadType!=='dome')target.traverse(c=>{if(c.isMesh)c.castShadow=true});if(loadType==='stage'||loadType==='dome')target.traverse(c=>{if(c.isMesh)c.receiveShadow=true});if(loadType!=='stage'&&loadType!=='dome'){const isOldModel=hasMatPrefix(target);const usePhys=isOldModel&&ammoInitialized;modelPhysicsMap.set(target,usePhys);
|
| 50 |
+
// ★v85: 剛体ダンプ(旧新両方)
|
| 51 |
+
dumpRigidBodies(target,isOldModel?'旧モデル':'新モデル');
|
| 52 |
+
try{helper.add(target,{physics:usePhys});dbg(`[Helper] 追加 physics:${usePhys} (${isOldModel?'旧モデル':'新モデル'})`,"info")}catch(e){dbg(`[Helper] 失敗→physics:off`,"warn");try{helper.add(target,{physics:false});modelPhysicsMap.set(target,false)}catch(e2){}}saveInitialBonePose(target)}updateStatus(loadType==='stage'?"ステージ召喚♡":loadType==='dome'?"ドーム召喚♡":"キャラ召喚♡");buildMorphUI();buildMatDebugUI();showLoading(false)},xhr=>{if(xhr.lengthComputable)showLoading(true,`${loadType}: ${Math.round(xhr.loaded/xhr.total*100)}%`)},()=>{dbg("[PMX] エラー","error");showLoading(false)})}
|
| 53 |
function clearAll(){if(isPlaying)pause();[mesh,mesh2].forEach(m=>{if(m){scene.remove(m);if(helper.objects.has(m))helper.remove(m)}});mesh=mesh2=null;if(helper.camera)try{helper.remove(camera)}catch(e){}cameraVmdEnabled=false;helper.enabled.cameraAnimation=false;controls.enabled=true;document.getElementById('cam-vmd-toggle').style.display='none';document.querySelectorAll('.aspect-btn').forEach(b=>b.style.display='none');forcedAspect=null;updateRendererSize();document.getElementById('morph-panel').style.display='none';document.getElementById('morph-sliders').innerHTML='';document.getElementById('morph-tabs').innerHTML='';const md=document.getElementById('mat-debug');if(md)md.innerHTML='';stageMeshes.forEach(s=>scene.remove(s));stageMeshes=[];domeMeshes.forEach(s=>scene.remove(s));domeMeshes=[];['mesh','mesh2','stage','dome'].forEach(t=>{for(const k in modelData[t].fileMap){const v=modelData[t].fileMap[k];if(typeof v==='string'&&v.startsWith('blob:'))URL.revokeObjectURL(v)}modelData[t].fileMap={}});audioBuffer=null;maxDuration=0;audioPausedAt=0;document.querySelectorAll('.btn-lab').forEach(l=>l.classList.remove('ready'));document.querySelectorAll('input[type="file"]').forEach(inp=>inp.value='');document.getElementById('seek-bar').value=0;document.getElementById('time-current').textContent="0:00";document.getElementById('time-total').textContent="-0:00";updateStatus("クリアしました♡");dbg("[Clear] 全クリア","info")}
|
| 54 |
function togglePlay(){if(audioContext&&audioContext.state==='suspended')audioContext.resume();isPlaying?pause():play()}
|
| 55 |
function play(){if(audioBuffer&&audioContext){try{if(audioSource)try{audioSource.stop()}catch(e){}audioSource=audioContext.createBufferSource();audioSource.buffer=audioBuffer;audioSource.connect(audioGainNode);audioSource.playbackRate.value=playbackSpeed;audioStartTime=audioContext.currentTime-audioPausedAt/playbackSpeed;audioSource.start(0,audioPausedAt)}catch(e){}}document.getElementById('play-icon').style.display='none';document.getElementById('pause-icon').style.display='block';isPlaying=true;clock.getDelta();if(uiHideTimer)clearTimeout(uiHideTimer);if(!uiManualHidden)uiHideTimer=setTimeout(()=>{if(!uiManualHidden)document.body.classList.add('ui-hidden')},UI_HIDE_DELAY)}
|