mg696 commited on
Commit
bf00bc4
·
verified ·
1 Parent(s): 2b627f1

v76: whitelist approach - only keep physics on hair/breast/skirt bodies, kinematic everything else

Browse files
Files changed (1) hide show
  1. app.js +4 -6
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='v75';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)}}}}
@@ -9,8 +9,8 @@ function normalizePath(path){let p=path.replace(/\\/g,'/').normalize('NFC');try{
9
  function saveInitialBonePose(m){if(!m||!m.skeleton)return;m.userData._ib=m.skeleton.bones.map(b=>({n:b.name,p:b.position.clone(),q:b.quaternion.clone(),s:b.scale.clone()}));dbg(`[BoneSave] ${m.skeleton.bones.length}ボーン保存`,"info")}
10
  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);dbg(`[BoneRestore] ${saved.length}ボーン復元`,"info")}
11
  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()}})}
12
- // ★v75: 目関連剛体をキネマティック化(物理シミュレーションの影響を受けない)
13
- function disableEyePhysics(targetMesh){const obj=helper.objects.get(targetMesh);if(!obj||!obj.physics)return;const mmdPhysics=obj.physics;if(!mmdPhysics.bodies||!mmdPhysics.bodies.length)return;const EYE_PATTERN=/eye|目|瞳|iris|白目|左目|右目|両目/i;let count=0;mmdPhysics.bodies.forEach((rb,i)=>{const p=rb.params;const bodyName=p.name||'';const boneName=rb.bone?(rb.bone.name||''):'';if(EYE_PATTERN.test(bodyName)||EYE_PATTERN.test(boneName)){if(p.type!==0){p.type=0;const ammoBody=rb.body;ammoBody.setCollisionFlags(ammoBody.getCollisionFlags()|2);ammoBody.setActivationState(4);count++}}});if(count>0)dbg(`[Physics] 目関連${count}剛体をキネマティック化`,"info")}
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;const mats=Array.isArray(child.material)?child.material:[child.material];mats.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)})})}
@@ -24,11 +24,9 @@ function setupEventListeners(){document.getElementById('file-input').addEventLis
24
  function helperSeekTo(t){[mesh,mesh2].forEach(m=>{if(!m||!helper.objects.has(m))return;const obj=helper.objects.get(m);if(obj.mixer){obj.mixer.time=t;if(obj.mixer._actions)obj.mixer._actions.forEach(a=>{a.enabled=true;a.paused=false;a.time=a._clip?(t%a._clip.duration):t})}});const sp=helper.enabled.physics;helper.enabled.physics=false;try{helper.update(0)}catch(e){}helper.enabled.physics=sp}
25
  function handleSeekInput(e){if(seekRAFPending)return;seekRAFPending=true;const time=parseFloat(e.target.value);requestAnimationFrame(()=>{seekRAFPending=false;helperSeekTo(time);audioPausedAt=time;document.getElementById('time-current').textContent=formatTime(time);document.getElementById('time-total').textContent='-'+formatTime(Math.max(0,maxDuration-time))})}
26
  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)}
27
- // ★v75: VMD読込時 physics:true + disableEyePhysics
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);helper.add(targetMesh,{animation:vmd,physics:ammoInitialized});disableEyePhysics(targetMesh);helperSeekTo(0);const obj=helper.objects.get(targetMesh);if(obj&&obj.physics)obj.physics.reset();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)`,"info")}catch(e){dbg(`[VMD] 適用失敗: ${e.message}`,"error")}resolve()},null,()=>{dbg("[VMD] 読込失敗","error");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){dbg(`[VPD] 失敗: ${e.message}`,"error")}resolve()},null,()=>{dbg("[VPD] 読込失敗","error");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
- // ★v75: physics:true + disableEyePhysics
31
- 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] 成功: skinned=${target.isSkinnedMesh}`,"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'){try{helper.add(target,{physics:ammoInitialized});disableEyePhysics(target);dbg(`[Helper] 追加 (physics:${ammoInitialized}) + 目キネマティック化`,"info")}catch(e){dbg(`[Helper] 失敗→physics:off`,"warn");try{helper.add(target,{physics:false})}catch(e2){dbg("[Helper] 完全失敗","error")}}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)})}
32
  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")}
33
  function togglePlay(){if(audioContext&&audioContext.state==='suspended')audioContext.resume();isPlaying?pause():play()}
34
  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='v76';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)}}}}
 
9
  function saveInitialBonePose(m){if(!m||!m.skeleton)return;m.userData._ib=m.skeleton.bones.map(b=>({n:b.name,p:b.position.clone(),q:b.quaternion.clone(),s:b.scale.clone()}));dbg(`[BoneSave] ${m.skeleton.bones.length}ボーン保存`,"info")}
10
  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);dbg(`[BoneRestore] ${saved.length}ボーン復元`,"info")}
11
  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()}})}
12
+ // ★v76: ホワイトリスト方式 — 揺らすべきボーンのみ物理維持、それ以外は全てキネマティック化
13
+ function disableEyePhysics(targetMesh){const obj=helper.objects.get(targetMesh);if(!obj||!obj.physics)return;const mmdPhysics=obj.physics;if(!mmdPhysics.bodies||!mmdPhysics.bodies.length)return;const KEEP_PHYSICS=/hair|ヘア|髪|毛|breast|胸|おっぱい|乳|bust|skirt|スカート|裾|尻|butt|ribbon|リボン|ネクタイ|tie|袖|sleeve|衣|cloth|服|ジョイント|joint|アクセ|accessory|イヤリング|earring|ネックレス|necklace|ペンダント|pendant|揺れ/i;let kept=0,forced=0;mmdPhysics.bodies.forEach((rb)=>{const p=rb.params;const bodyName=p.name||'';const boneName=rb.bone?(rb.bone.name||''):'';if(KEEP_PHYSICS.test(bodyName)||KEEP_PHYSICS.test(boneName)){kept++}else{if(p.type!==0){p.type=0;const ammoBody=rb.body;ammoBody.setCollisionFlags(ammoBody.getCollisionFlags()|2);ammoBody.setActivationState(4);forced++}}});dbg(`[Physics] 剛体: 物理維持=${kept}, キネマティック化=${forced}, 合計=${mmdPhysics.bodies.length}`,"info")}
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;const mats=Array.isArray(child.material)?child.material:[child.material];mats.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)})})}
 
24
  function helperSeekTo(t){[mesh,mesh2].forEach(m=>{if(!m||!helper.objects.has(m))return;const obj=helper.objects.get(m);if(obj.mixer){obj.mixer.time=t;if(obj.mixer._actions)obj.mixer._actions.forEach(a=>{a.enabled=true;a.paused=false;a.time=a._clip?(t%a._clip.duration):t})}});const sp=helper.enabled.physics;helper.enabled.physics=false;try{helper.update(0)}catch(e){}helper.enabled.physics=sp}
25
  function handleSeekInput(e){if(seekRAFPending)return;seekRAFPending=true;const time=parseFloat(e.target.value);requestAnimationFrame(()=>{seekRAFPending=false;helperSeekTo(time);audioPausedAt=time;document.getElementById('time-current').textContent=formatTime(time);document.getElementById('time-total').textContent='-'+formatTime(Math.max(0,maxDuration-time))})}
26
  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)}
 
27
  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);helper.add(targetMesh,{animation:vmd,physics:ammoInitialized});disableEyePhysics(targetMesh);helperSeekTo(0);const obj=helper.objects.get(targetMesh);if(obj&&obj.physics)obj.physics.reset();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)`,"info")}catch(e){dbg(`[VMD] 適用失敗: ${e.message}`,"error")}resolve()},null,()=>{dbg("[VMD] 読込失敗","error");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){dbg(`[VPD] 失敗: ${e.message}`,"error")}resolve()},null,()=>{dbg("[VPD] 読込失敗","error");resolve()})}).catch(()=>{resolve()})}});}updateStatus("モーション準備完了♡")}
28
  function findFileInMap(ext,t){for(let key in modelData[t].fileMap)if(key.endsWith(ext))return key;return null}
29
+ 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] 成功: skinned=${target.isSkinnedMesh}`,"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'){try{helper.add(target,{physics:ammoInitialized});disableEyePhysics(target);dbg(`[Helper] 追加 (physics:${ammoInitialized}) + 顔面キネマティック化`,"info")}catch(e){dbg(`[Helper] 失敗→physics:off`,"warn");try{helper.add(target,{physics:false})}catch(e2){dbg("[Helper] 完全失敗","error")}}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)})}
 
30
  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")}
31
  function togglePlay(){if(audioContext&&audioContext.state==='suspended')audioContext.resume();isPlaying?pause():play()}
32
  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)}