Spaces:
Running
Running
v55: fix transparency - floor/curtain renderOrder=20, char=0, so char shows through transparent objects
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)})});
|
| 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)}}}}
|
|
@@ -8,13 +8,13 @@ let scene,camera,renderer,controls,clock,mesh,mesh2,helper,stageMeshes=[],domeMe
|
|
| 8 |
function normalizePath(path){let p=path.replace(/\\/g,'/').normalize('NFC');try{p=decodeURIComponent(p)}catch(e){}return p.replace(/^\.\//,'').replace(/%20/g,' ').toLowerCase()}
|
| 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 |
-
async function init(){try{if(typeof Ammo==='function')await Ammo().then(()=>{ammoInitialized=true;dbg("Ammo.js初期化完了","info")})}catch(e){dbg("Ammo.js失敗:"+e.message,"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});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=
|
| 12 |
['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))return FALLBACK_PIXEL;return url});mgr.onError=url=>dbg(`[Load]エラー:${url}`,"error");modelData[type].loader=new MMDLoader(mgr);modelData[type].manager=mgr});
|
| 13 |
helper=new MMDAnimationHelper({afterglow:2.0,resetPhysicsOnLoop:true});setupEventListeners();animate();dbg("初期化完了","info");dbg(`[Device]${navigator.userAgent.slice(0,80)}`,"info");dbg(`[Screen]${screen.width}x${screen.height} win=${innerWidth}x${innerHeight} dpr=${devicePixelRatio}`,"info");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;}
|
| 14 |
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}}}
|
| 15 |
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}ファイル(PMXdir:${pmxDir||'root'})`,"info")}catch(e){dbg(`[ZIP]展開失敗:${e.message}`,"error")}}
|
| 16 |
-
// ★
|
| 17 |
-
function fixMMDMaterials(target,loadType){let mc=0,fc=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-transparent'}else{action='stage-opaque'}m.needsUpdate=true}else if(/eyehighlight|highlight/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='highlight'}else if(/eyelash/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='eyelash'}else if((/eyeline/i.test(ml)||/brow/i.test(ml))&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;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){m.transparent=true;m.alphaTest=0.01;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++;action='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'}m.needsUpdate=true;dbg(` [Mat#${mc}] "${m.name}" ha=${ha} op=${m.opacity.toFixed(2)} → ${action}`)})});target.traverse(child=>{if(!child.isMesh)return;const isEnv=(loadType==='stage'||loadType==='dome');child.renderOrder=
|
| 18 |
function setupEventListeners(){document.getElementById('file-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ1展開中...");await processFiles(e.target.files,'mesh');let pmx=findFileInMap('.pmx','mesh')||findFileInMap('.pmd','mesh');if(pmx){document.getElementById('pmx-label').classList.add('ready');loadPmx(pmx,'mesh')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('file-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ2展開中...");await processFiles(e.target.files,'mesh2');let pmx=findFileInMap('.pmx','mesh2')||findFileInMap('.pmd','mesh2');if(pmx){document.getElementById('pmx2-label').classList.add('ready');loadPmx(pmx,'mesh2')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('stage-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"ステージ展開中...");await processFiles(e.target.files,'stage');let pmx=findFileInMap('.pmx','stage')||findFileInMap('.pmd','stage');if(pmx){document.getElementById('stage-label').classList.add('ready');loadPmx(pmx,'stage')}else{showLoading(false);updateStatus("ステージPMXがありません♡")}});document.getElementById('cam-vmd-input').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;showLoading(true,"カメラVMD読込中...");const url=URL.createObjectURL(file);modelData.mesh.loader.loadAnimation(url,camera,clip=>{try{if(helper.camera)helper.remove(camera);helper.add(camera,{animation:clip});cameraVmdEnabled=true;helper.enabled.cameraAnimation=true;controls.enabled=false;maxDuration=Math.max(maxDuration,clip.duration);updateSeekBarLimit();document.getElementById('cam-vmd-label').classList.add('ready');document.getElementById('cam-vmd-toggle').style.display='inline-block';document.querySelectorAll('.aspect-btn').forEach(b=>b.style.display='inline-block');dbg(`[CamVMD]${file.name}(${clip.duration.toFixed(1)}s)`,"info")}catch(err){dbg(`[CamVMD]失敗:${err.message}`,"error")}showLoading(false)},null,()=>{dbg("[CamVMD]読込失敗","error");showLoading(false)})});document.getElementById('cam-vmd-toggle').addEventListener('click',()=>{cameraVmdEnabled=!cameraVmdEnabled;helper.enabled.cameraAnimation=cameraVmdEnabled;controls.enabled=!cameraVmdEnabled;const btn=document.getElementById('cam-vmd-toggle');btn.textContent=cameraVmdEnabled?'カメラVMD: ON':'カメラVMD: OFF';btn.style.color=cameraVmdEnabled?'#ff8c00':'#666';btn.style.borderColor=cameraVmdEnabled?'#ff8c00':'#666'});document.getElementById('vmd-input').addEventListener('change',async e=>{if(!e.target.files.length)return;if(!mesh){updateStatus("先にキャラ1モデルを♡");return}document.getElementById('vmd-label').classList.add('ready');showLoading(true,"モーション読込中...");await loadMotions(e.target.files,'mesh',mesh);showLoading(false)});document.getElementById('vmd-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;if(!mesh2){updateStatus("先にキャラ2モデルを♡");return}document.getElementById('vmd2-label').classList.add('ready');showLoading(true,"モーション読込中...");await loadMotions(e.target.files,'mesh2',mesh2);showLoading(false)});document.getElementById('audio-input').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;showLoading(true,"音楽デコード中...");try{if(!audioContext){audioContext=new(window.AudioContext||window.webkitAudioContext)();audioGainNode=audioContext.createGain();audioGainNode.connect(audioContext.destination)}audioBuffer=await audioContext.decodeAudioData(await file.arrayBuffer());document.getElementById('audio-label').classList.add('ready');maxDuration=Math.max(maxDuration,audioBuffer.duration);updateSeekBarLimit();updateStatus("音楽準備完了♡");dbg(`[Audio]${file.name}(${audioBuffer.duration.toFixed(1)}s)`,"info")}catch(err){dbg(`[Audio]エラー:${err.message}`,"error")}finally{showLoading(false)}});document.getElementById('clear-all-btn').addEventListener('click',clearAll);document.getElementById('play-pause-btn').addEventListener('click',togglePlay);document.getElementById('reset-btn').addEventListener('click',resetToStart);const seekBar=document.getElementById('seek-bar');seekBar.addEventListener('pointerdown',()=>{if(!isSeeking)wasPlayingBeforeSeek=isPlaying;isSeeking=true;if(isPlaying)pause()});seekBar.addEventListener('touchstart',()=>{if(!isSeeking)wasPlayingBeforeSeek=isPlaying;isSeeking=true;if(isPlaying)pause()},{passive:true});seekBar.addEventListener('input',handleSeekInput);seekBar.addEventListener('change',handleSeekFinalize);seekBar.addEventListener('pointerup',handleSeekFinalize);seekBar.addEventListener('touchend',handleSeekFinalize);document.getElementById('volume-bar').addEventListener('input',e=>{lastVolume=parseFloat(e.target.value);if(audioGainNode&&!isMuted)audioGainNode.gain.value=lastVolume});document.getElementById('mute-btn').addEventListener('click',()=>{isMuted=!isMuted;if(audioGainNode)audioGainNode.gain.value=isMuted?0:lastVolume;document.getElementById('vol-on-icon').style.display=isMuted?'none':'block';document.getElementById('vol-off-icon').style.display=isMuted?'block':'none'});document.getElementById('loop-btn').addEventListener('click',e=>{isLooping=!isLooping;e.target.textContent=`ループ: ${isLooping?'ON':'OFF'}`;e.target.classList.toggle('active',isLooping)});document.getElementById('gravity-bar').addEventListener('input',e=>{const val=parseFloat(e.target.value);document.getElementById('gravity-val').textContent=val.toFixed(1);[mesh,mesh2].forEach(m=>{if(m&&helper.objects.has(m)){const d=helper.objects.get(m);if(d.physics&&d.physics.world&&ammoInitialized)d.physics.world.setGravity(new Ammo.btVector3(0,val,0))}})});window.addEventListener('resize',updateRendererSize);window.addEventListener('orientationchange',()=>setTimeout(updateRendererSize,200));document.querySelectorAll('.bg-btn').forEach(btn=>btn.addEventListener('click',()=>{scene.background=new THREE.Color(btn.dataset.bg);document.querySelectorAll('.bg-btn').forEach(b=>b.style.borderColor='#555');btn.style.borderColor='#ff1493'}));document.getElementById('screenshot-btn').addEventListener('click',()=>{renderer.render(scene,camera);renderer.domElement.toBlob(blob=>{const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`mmd_ss_${Date.now()}.png`;a.click()},'image/png')});document.getElementById('record-btn').addEventListener('click',()=>{const btn=document.getElementById('record-btn');if(mediaRecorder&&mediaRecorder.state==='recording'){mediaRecorder.stop();btn.textContent='🎥';btn.classList.remove('active')}else{try{recordedChunks=[];const cs=renderer.domElement.captureStream(30);let stream;if(audioContext&&audioContext.state==='running'){const dest=audioContext.createMediaStreamDestination();audioGainNode.connect(dest);stream=new MediaStream([...cs.getVideoTracks(),...dest.stream.getAudioTracks()])}else stream=cs;const mimes=['video/webm;codecs=vp9,opus','video/webm;codecs=vp8,opus','video/webm','video/mp4'];let mime='';for(const m of mimes)if(MediaRecorder.isTypeSupported(m)){mime=m;break}if(!mime)return;mediaRecorder=new MediaRecorder(stream,{mimeType:mime,videoBitsPerSecond:5000000});mediaRecorder.ondataavailable=e=>{if(e.data.size>0)recordedChunks.push(e.data)};mediaRecorder.onstop=()=>{const blob=new Blob(recordedChunks,{type:mime});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`mmd_rec_${Date.now()}.webm`;a.click();recordedChunks=[]};mediaRecorder.start(100);btn.textContent='⏹';btn.classList.add('active')}catch(e){dbg(`[Record]${e.message}`,"error")}}});document.getElementById('fullscreen-btn').addEventListener('click',()=>{if(!document.fullscreenElement)document.documentElement.requestFullscreen().catch(e=>dbg(`[FS]${e.message}`,"error"));else document.exitFullscreen()});function setGroundMode(mode){groundMode=mode;document.getElementById('ground-grid-btn').classList.toggle('active',mode==='grid');document.getElementById('ground-floor-btn').classList.toggle('active',mode==='floor');document.getElementById('ground-none-btn').classList.toggle('active',mode==='none');if(gridHelper)gridHelper.visible=(mode==='grid');if(floorMesh)floorMesh.visible=(mode==='floor')}document.getElementById('ground-grid-btn').addEventListener('click',()=>setGroundMode('grid'));document.getElementById('ground-floor-btn').addEventListener('click',()=>setGroundMode('floor'));document.getElementById('ground-none-btn').addEventListener('click',()=>setGroundMode('none'));document.getElementById('shadow-toggle-btn').addEventListener('click',()=>{shadowEnabled=!shadowEnabled;renderer.shadowMap.enabled=shadowEnabled;[mesh,mesh2].forEach(m=>{if(m)m.traverse(c=>{if(c.isMesh)c.castShadow=shadowEnabled})});document.getElementById('shadow-toggle-btn').textContent=shadowEnabled?'ON':'OFF';document.getElementById('shadow-toggle-btn').classList.toggle('active',shadowEnabled)});['1','2'].forEach(n=>['x','y','z'].forEach(axis=>{const sl=document.getElementById(`pos${n}-${axis}`);const vl=document.getElementById(`pos${n}-${axis}-val`);if(!sl||!vl)return;sl.addEventListener('input',()=>{const v=parseFloat(sl.value);vl.textContent=v;const target=n==='1'?mesh:mesh2;if(target)target.position[axis]=v})}));document.querySelectorAll('.speed-btn').forEach(btn=>btn.addEventListener('click',()=>{playbackSpeed=parseFloat(btn.dataset.speed);document.querySelectorAll('.speed-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');[mesh,mesh2].forEach(m=>{if(m&&helper.objects.has(m)){const obj=helper.objects.get(m);if(obj.mixer)obj.mixer.timeScale=playbackSpeed}});if(audioSource&&audioSource.playbackRate)audioSource.playbackRate.value=playbackSpeed}));const CAM_PRESETS={free:{pos:[0,20,100],target:[0,10,0]},front:{pos:[0,12,35],target:[0,12,0]},side:{pos:[35,12,0],target:[0,12,0]},top:{pos:[0,60,1],target:[0,0,0]},back:{pos:[0,12,-35],target:[0,12,0]}};document.querySelectorAll('.cam-btn').forEach(btn=>btn.addEventListener('click',()=>{const p=CAM_PRESETS[btn.dataset.cam];if(!p)return;document.querySelectorAll('.cam-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');camera.position.set(...p.pos);controls.target.set(...p.target);controls.update()}));const LIGHT_PRESETS={studio:{amb:{color:0xffffff,i:0.8},main:{color:0xffffff,i:1.2,pos:[5,20,10]},sub:{color:0xffffff,i:0.4,pos:[-5,10,-5]}},dramatic:{amb:{color:0x222244,i:0.2},main:{color:0xffeedd,i:2.0,pos:[10,25,5]},sub:{color:0x4466aa,i:0.3,pos:[-10,5,-10]}},soft:{amb:{color:0xfff5ee,i:1.2},main:{color:0xffffff,i:0.5,pos:[0,15,15]},sub:{color:0xffe8f0,i:0.5,pos:[0,10,-10]}},sunset:{amb:{color:0x553322,i:0.4},main:{color:0xff8844,i:1.5,pos:[-15,10,5]},sub:{color:0xffaa66,i:0.6,pos:[10,5,-5]}},stage:{amb:{color:0x111122,i:0.15},main:{color:0xccddff,i:2.0,pos:[0,30,10]},sub:{color:0xff69b4,i:0.8,pos:[-10,5,-10]}},rim:{amb:{color:0x1a1a2e,i:0.3},main:{color:0x8888aa,i:0.5,pos:[0,10,20]},sub:{color:0xffffff,i:1.8,pos:[0,15,-20]}}};function applyLightPreset(key){const p=LIGHT_PRESETS[key];if(!p)return;currentLightPreset=key;ambLight.color.setHex(p.amb.color);ambLight.intensity=p.amb.i*lightIntensityScale;mainLight.color.setHex(p.main.color);mainLight.intensity=p.main.i*lightIntensityScale;mainLight.position.set(...p.main.pos);subLight.color.setHex(p.sub.color);subLight.intensity=p.sub.i*lightIntensityScale;subLight.position.set(...p.sub.pos);document.querySelectorAll('.light-btn').forEach(b=>b.classList.remove('active'));document.querySelector(`.light-btn[data-light="${key}"]`)?.classList.add('active')}document.querySelectorAll('.light-btn').forEach(btn=>btn.addEventListener('click',()=>applyLightPreset(btn.dataset.light)));document.getElementById('light-intensity').addEventListener('input',e=>{lightIntensityScale=parseFloat(e.target.value)/100;document.getElementById('light-intensity-val').textContent=e.target.value+'%';const p=LIGHT_PRESETS[currentLightPreset];if(p){ambLight.intensity=p.amb.i*lightIntensityScale;mainLight.intensity=p.main.i*lightIntensityScale;subLight.intensity=p.sub.i*lightIntensityScale}});document.querySelectorAll('.shader-btn').forEach(btn=>btn.addEventListener('click',()=>{const mode=btn.dataset.shader;document.querySelectorAll('.shader-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');[mesh,mesh2].forEach(m=>{if(!m)return;m.traverse(child=>{if(!child.isMesh)return;const mats=Array.isArray(child.material)?child.material:[child.material];const newMats=mats.map((mat,mi)=>{if(!child._origMats)child._origMats=[...mats];const orig=child._origMats[mi];if(mode==='default')return orig;const props={map:orig.map,color:orig.color,transparent:orig.transparent,opacity:orig.opacity,alphaTest:orig.alphaTest,side:orig.side,depthWrite:orig.depthWrite,blending:orig.blending,premultipliedAlpha:orig.premultipliedAlpha,name:orig.name};let nm;if(mode==='anime'){nm=new THREE.MeshToonMaterial(props);nm.emissive=new THREE.Color(0x222222)}else if(mode==='doll'){nm=new THREE.MeshPhongMaterial(props);nm.shininess=180;nm.specular=new THREE.Color(0xdddddd);nm.emissive=new THREE.Color(0x151515)}else if(mode==='real'){nm=new THREE.MeshStandardMaterial(props);const n=(orig.name||'').toLowerCase();if(/_hair/i.test(n)||/hairback/i.test(n)){nm.roughness=0.45;nm.metalness=0.05}else if(/_skin/i.test(n)||/face/i.test(n)||/body/i.test(n)){nm.roughness=0.75;nm.metalness=0}else if(/eye|iris|highlight/i.test(n)){nm.roughness=0.15;nm.metalness=0.1}else{nm.roughness=0.6;nm.metalness=0.02}}return nm||orig});child.material=newMats.length===1?newMats[0]:newMats})})}));document.querySelectorAll('.aspect-btn').forEach(btn=>btn.addEventListener('click',()=>{document.querySelectorAll('.aspect-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');const v=btn.dataset.aspect;forcedAspect=v==='16:9'?16/9:v==='4:3'?4/3:v==='9:16'?9/16:null;updateRendererSize()}));function resetUiHideTimer(){document.body.classList.remove('ui-hidden');if(uiHideTimer)clearTimeout(uiHideTimer);if(isPlaying)uiHideTimer=setTimeout(()=>document.body.classList.add('ui-hidden'),UI_HIDE_DELAY)}document.addEventListener('pointerdown',resetUiHideTimer);document.addEventListener('pointermove',resetUiHideTimer)}
|
| 19 |
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}
|
| 20 |
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))})}
|
|
|
|
| 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)})});
|
| 3 |
+
const APP_VER='v55';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)}}}}
|
|
|
|
| 8 |
function normalizePath(path){let p=path.replace(/\\/g,'/').normalize('NFC');try{p=decodeURIComponent(p)}catch(e){}return p.replace(/^\.\//,'').replace(/%20/g,' ').toLowerCase()}
|
| 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 |
+
async function init(){try{if(typeof Ammo==='function')await Ammo().then(()=>{ammoInitialized=true;dbg("Ammo.js初期化完了","info")})}catch(e){dbg("Ammo.js失敗:"+e.message,"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});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);
|
| 12 |
['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))return FALLBACK_PIXEL;return url});mgr.onError=url=>dbg(`[Load]エラー:${url}`,"error");modelData[type].loader=new MMDLoader(mgr);modelData[type].manager=mgr});
|
| 13 |
helper=new MMDAnimationHelper({afterglow:2.0,resetPhysicsOnLoop:true});setupEventListeners();animate();dbg("初期化完了","info");dbg(`[Device]${navigator.userAgent.slice(0,80)}`,"info");dbg(`[Screen]${screen.width}x${screen.height} win=${innerWidth}x${innerHeight} dpr=${devicePixelRatio}`,"info");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;}
|
| 14 |
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}}}
|
| 15 |
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}ファイル(PMXdir:${pmxDir||'root'})`,"info")}catch(e){dbg(`[ZIP]展開失敗:${e.message}`,"error")}}
|
| 16 |
+
// ★v55: renderOrder修正 - キャラ=0(先描画), ステージ透明/床=20(後描画で透過越しにキャラ見える)
|
| 17 |
+
function fixMMDMaterials(target,loadType){let mc=0,fc=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-transparent'}else{action='stage-opaque'}m.needsUpdate=true}else if(/eyehighlight|highlight/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='highlight'}else if(/eyelash/i.test(ml)&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;m.side=THREE.DoubleSide;fc++;action='eyelash'}else if((/eyeline/i.test(ml)||/brow/i.test(ml))&&ha){m.transparent=true;m.alphaTest=0.1;m.depthWrite=true;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){m.transparent=true;m.alphaTest=0.01;m.depthWrite=false;m.blending=THREE.NormalBlending;m.premultipliedAlpha=false;fc++;action='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'}m.needsUpdate=true;dbg(` [Mat#${mc}] "${m.name}" ha=${ha} op=${m.opacity.toFixed(2)} → ${action}`)})});target.traverse(child=>{if(!child.isMesh)return;const mats=Array.isArray(child.material)?child.material:[child.material];const isEnv=(loadType==='stage'||loadType==='dome');if(isEnv){const hasTransparent=mats.some(m=>m.transparent&&m.depthWrite===false);child.renderOrder=hasTransparent?20:0}else{child.renderOrder=0}});dbg(`[Material]${mc}個処理,${fc}個修正(${loadType})`,"info")}
|
| 18 |
function setupEventListeners(){document.getElementById('file-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ1展開中...");await processFiles(e.target.files,'mesh');let pmx=findFileInMap('.pmx','mesh')||findFileInMap('.pmd','mesh');if(pmx){document.getElementById('pmx-label').classList.add('ready');loadPmx(pmx,'mesh')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('file-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"キャラ2展開中...");await processFiles(e.target.files,'mesh2');let pmx=findFileInMap('.pmx','mesh2')||findFileInMap('.pmd','mesh2');if(pmx){document.getElementById('pmx2-label').classList.add('ready');loadPmx(pmx,'mesh2')}else{showLoading(false);updateStatus("PMXが見つかりません♡")}});document.getElementById('stage-input').addEventListener('change',async e=>{if(!e.target.files.length)return;showLoading(true,"ステージ展開中...");await processFiles(e.target.files,'stage');let pmx=findFileInMap('.pmx','stage')||findFileInMap('.pmd','stage');if(pmx){document.getElementById('stage-label').classList.add('ready');loadPmx(pmx,'stage')}else{showLoading(false);updateStatus("ステージPMXがありません♡")}});document.getElementById('cam-vmd-input').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;showLoading(true,"カメラVMD読込中...");const url=URL.createObjectURL(file);modelData.mesh.loader.loadAnimation(url,camera,clip=>{try{if(helper.camera)helper.remove(camera);helper.add(camera,{animation:clip});cameraVmdEnabled=true;helper.enabled.cameraAnimation=true;controls.enabled=false;maxDuration=Math.max(maxDuration,clip.duration);updateSeekBarLimit();document.getElementById('cam-vmd-label').classList.add('ready');document.getElementById('cam-vmd-toggle').style.display='inline-block';document.querySelectorAll('.aspect-btn').forEach(b=>b.style.display='inline-block');dbg(`[CamVMD]${file.name}(${clip.duration.toFixed(1)}s)`,"info")}catch(err){dbg(`[CamVMD]失敗:${err.message}`,"error")}showLoading(false)},null,()=>{dbg("[CamVMD]読込失敗","error");showLoading(false)})});document.getElementById('cam-vmd-toggle').addEventListener('click',()=>{cameraVmdEnabled=!cameraVmdEnabled;helper.enabled.cameraAnimation=cameraVmdEnabled;controls.enabled=!cameraVmdEnabled;const btn=document.getElementById('cam-vmd-toggle');btn.textContent=cameraVmdEnabled?'カメラVMD: ON':'カメラVMD: OFF';btn.style.color=cameraVmdEnabled?'#ff8c00':'#666';btn.style.borderColor=cameraVmdEnabled?'#ff8c00':'#666'});document.getElementById('vmd-input').addEventListener('change',async e=>{if(!e.target.files.length)return;if(!mesh){updateStatus("先にキャラ1モデルを♡");return}document.getElementById('vmd-label').classList.add('ready');showLoading(true,"モーション読込中...");await loadMotions(e.target.files,'mesh',mesh);showLoading(false)});document.getElementById('vmd-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;if(!mesh2){updateStatus("先にキャラ2モデルを♡");return}document.getElementById('vmd2-label').classList.add('ready');showLoading(true,"モーション読込中...");await loadMotions(e.target.files,'mesh2',mesh2);showLoading(false)});document.getElementById('audio-input').addEventListener('change',async e=>{const file=e.target.files[0];if(!file)return;showLoading(true,"音楽デコード中...");try{if(!audioContext){audioContext=new(window.AudioContext||window.webkitAudioContext)();audioGainNode=audioContext.createGain();audioGainNode.connect(audioContext.destination)}audioBuffer=await audioContext.decodeAudioData(await file.arrayBuffer());document.getElementById('audio-label').classList.add('ready');maxDuration=Math.max(maxDuration,audioBuffer.duration);updateSeekBarLimit();updateStatus("音楽準備完了♡");dbg(`[Audio]${file.name}(${audioBuffer.duration.toFixed(1)}s)`,"info")}catch(err){dbg(`[Audio]エラー:${err.message}`,"error")}finally{showLoading(false)}});document.getElementById('clear-all-btn').addEventListener('click',clearAll);document.getElementById('play-pause-btn').addEventListener('click',togglePlay);document.getElementById('reset-btn').addEventListener('click',resetToStart);const seekBar=document.getElementById('seek-bar');seekBar.addEventListener('pointerdown',()=>{if(!isSeeking)wasPlayingBeforeSeek=isPlaying;isSeeking=true;if(isPlaying)pause()});seekBar.addEventListener('touchstart',()=>{if(!isSeeking)wasPlayingBeforeSeek=isPlaying;isSeeking=true;if(isPlaying)pause()},{passive:true});seekBar.addEventListener('input',handleSeekInput);seekBar.addEventListener('change',handleSeekFinalize);seekBar.addEventListener('pointerup',handleSeekFinalize);seekBar.addEventListener('touchend',handleSeekFinalize);document.getElementById('volume-bar').addEventListener('input',e=>{lastVolume=parseFloat(e.target.value);if(audioGainNode&&!isMuted)audioGainNode.gain.value=lastVolume});document.getElementById('mute-btn').addEventListener('click',()=>{isMuted=!isMuted;if(audioGainNode)audioGainNode.gain.value=isMuted?0:lastVolume;document.getElementById('vol-on-icon').style.display=isMuted?'none':'block';document.getElementById('vol-off-icon').style.display=isMuted?'block':'none'});document.getElementById('loop-btn').addEventListener('click',e=>{isLooping=!isLooping;e.target.textContent=`ループ: ${isLooping?'ON':'OFF'}`;e.target.classList.toggle('active',isLooping)});document.getElementById('gravity-bar').addEventListener('input',e=>{const val=parseFloat(e.target.value);document.getElementById('gravity-val').textContent=val.toFixed(1);[mesh,mesh2].forEach(m=>{if(m&&helper.objects.has(m)){const d=helper.objects.get(m);if(d.physics&&d.physics.world&&ammoInitialized)d.physics.world.setGravity(new Ammo.btVector3(0,val,0))}})});window.addEventListener('resize',updateRendererSize);window.addEventListener('orientationchange',()=>setTimeout(updateRendererSize,200));document.querySelectorAll('.bg-btn').forEach(btn=>btn.addEventListener('click',()=>{scene.background=new THREE.Color(btn.dataset.bg);document.querySelectorAll('.bg-btn').forEach(b=>b.style.borderColor='#555');btn.style.borderColor='#ff1493'}));document.getElementById('screenshot-btn').addEventListener('click',()=>{renderer.render(scene,camera);renderer.domElement.toBlob(blob=>{const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`mmd_ss_${Date.now()}.png`;a.click()},'image/png')});document.getElementById('record-btn').addEventListener('click',()=>{const btn=document.getElementById('record-btn');if(mediaRecorder&&mediaRecorder.state==='recording'){mediaRecorder.stop();btn.textContent='🎥';btn.classList.remove('active')}else{try{recordedChunks=[];const cs=renderer.domElement.captureStream(30);let stream;if(audioContext&&audioContext.state==='running'){const dest=audioContext.createMediaStreamDestination();audioGainNode.connect(dest);stream=new MediaStream([...cs.getVideoTracks(),...dest.stream.getAudioTracks()])}else stream=cs;const mimes=['video/webm;codecs=vp9,opus','video/webm;codecs=vp8,opus','video/webm','video/mp4'];let mime='';for(const m of mimes)if(MediaRecorder.isTypeSupported(m)){mime=m;break}if(!mime)return;mediaRecorder=new MediaRecorder(stream,{mimeType:mime,videoBitsPerSecond:5000000});mediaRecorder.ondataavailable=e=>{if(e.data.size>0)recordedChunks.push(e.data)};mediaRecorder.onstop=()=>{const blob=new Blob(recordedChunks,{type:mime});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`mmd_rec_${Date.now()}.webm`;a.click();recordedChunks=[]};mediaRecorder.start(100);btn.textContent='⏹';btn.classList.add('active')}catch(e){dbg(`[Record]${e.message}`,"error")}}});document.getElementById('fullscreen-btn').addEventListener('click',()=>{if(!document.fullscreenElement)document.documentElement.requestFullscreen().catch(e=>dbg(`[FS]${e.message}`,"error"));else document.exitFullscreen()});function setGroundMode(mode){groundMode=mode;document.getElementById('ground-grid-btn').classList.toggle('active',mode==='grid');document.getElementById('ground-floor-btn').classList.toggle('active',mode==='floor');document.getElementById('ground-none-btn').classList.toggle('active',mode==='none');if(gridHelper)gridHelper.visible=(mode==='grid');if(floorMesh)floorMesh.visible=(mode==='floor')}document.getElementById('ground-grid-btn').addEventListener('click',()=>setGroundMode('grid'));document.getElementById('ground-floor-btn').addEventListener('click',()=>setGroundMode('floor'));document.getElementById('ground-none-btn').addEventListener('click',()=>setGroundMode('none'));document.getElementById('shadow-toggle-btn').addEventListener('click',()=>{shadowEnabled=!shadowEnabled;renderer.shadowMap.enabled=shadowEnabled;[mesh,mesh2].forEach(m=>{if(m)m.traverse(c=>{if(c.isMesh)c.castShadow=shadowEnabled})});document.getElementById('shadow-toggle-btn').textContent=shadowEnabled?'ON':'OFF';document.getElementById('shadow-toggle-btn').classList.toggle('active',shadowEnabled)});['1','2'].forEach(n=>['x','y','z'].forEach(axis=>{const sl=document.getElementById(`pos${n}-${axis}`);const vl=document.getElementById(`pos${n}-${axis}-val`);if(!sl||!vl)return;sl.addEventListener('input',()=>{const v=parseFloat(sl.value);vl.textContent=v;const target=n==='1'?mesh:mesh2;if(target)target.position[axis]=v})}));document.querySelectorAll('.speed-btn').forEach(btn=>btn.addEventListener('click',()=>{playbackSpeed=parseFloat(btn.dataset.speed);document.querySelectorAll('.speed-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');[mesh,mesh2].forEach(m=>{if(m&&helper.objects.has(m)){const obj=helper.objects.get(m);if(obj.mixer)obj.mixer.timeScale=playbackSpeed}});if(audioSource&&audioSource.playbackRate)audioSource.playbackRate.value=playbackSpeed}));const CAM_PRESETS={free:{pos:[0,20,100],target:[0,10,0]},front:{pos:[0,12,35],target:[0,12,0]},side:{pos:[35,12,0],target:[0,12,0]},top:{pos:[0,60,1],target:[0,0,0]},back:{pos:[0,12,-35],target:[0,12,0]}};document.querySelectorAll('.cam-btn').forEach(btn=>btn.addEventListener('click',()=>{const p=CAM_PRESETS[btn.dataset.cam];if(!p)return;document.querySelectorAll('.cam-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');camera.position.set(...p.pos);controls.target.set(...p.target);controls.update()}));const LIGHT_PRESETS={studio:{amb:{color:0xffffff,i:0.8},main:{color:0xffffff,i:1.2,pos:[5,20,10]},sub:{color:0xffffff,i:0.4,pos:[-5,10,-5]}},dramatic:{amb:{color:0x222244,i:0.2},main:{color:0xffeedd,i:2.0,pos:[10,25,5]},sub:{color:0x4466aa,i:0.3,pos:[-10,5,-10]}},soft:{amb:{color:0xfff5ee,i:1.2},main:{color:0xffffff,i:0.5,pos:[0,15,15]},sub:{color:0xffe8f0,i:0.5,pos:[0,10,-10]}},sunset:{amb:{color:0x553322,i:0.4},main:{color:0xff8844,i:1.5,pos:[-15,10,5]},sub:{color:0xffaa66,i:0.6,pos:[10,5,-5]}},stage:{amb:{color:0x111122,i:0.15},main:{color:0xccddff,i:2.0,pos:[0,30,10]},sub:{color:0xff69b4,i:0.8,pos:[-10,5,-10]}},rim:{amb:{color:0x1a1a2e,i:0.3},main:{color:0x8888aa,i:0.5,pos:[0,10,20]},sub:{color:0xffffff,i:1.8,pos:[0,15,-20]}}};function applyLightPreset(key){const p=LIGHT_PRESETS[key];if(!p)return;currentLightPreset=key;ambLight.color.setHex(p.amb.color);ambLight.intensity=p.amb.i*lightIntensityScale;mainLight.color.setHex(p.main.color);mainLight.intensity=p.main.i*lightIntensityScale;mainLight.position.set(...p.main.pos);subLight.color.setHex(p.sub.color);subLight.intensity=p.sub.i*lightIntensityScale;subLight.position.set(...p.sub.pos);document.querySelectorAll('.light-btn').forEach(b=>b.classList.remove('active'));document.querySelector(`.light-btn[data-light="${key}"]`)?.classList.add('active')}document.querySelectorAll('.light-btn').forEach(btn=>btn.addEventListener('click',()=>applyLightPreset(btn.dataset.light)));document.getElementById('light-intensity').addEventListener('input',e=>{lightIntensityScale=parseFloat(e.target.value)/100;document.getElementById('light-intensity-val').textContent=e.target.value+'%';const p=LIGHT_PRESETS[currentLightPreset];if(p){ambLight.intensity=p.amb.i*lightIntensityScale;mainLight.intensity=p.main.i*lightIntensityScale;subLight.intensity=p.sub.i*lightIntensityScale}});document.querySelectorAll('.shader-btn').forEach(btn=>btn.addEventListener('click',()=>{const mode=btn.dataset.shader;document.querySelectorAll('.shader-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');[mesh,mesh2].forEach(m=>{if(!m)return;m.traverse(child=>{if(!child.isMesh)return;const mats=Array.isArray(child.material)?child.material:[child.material];const newMats=mats.map((mat,mi)=>{if(!child._origMats)child._origMats=[...mats];const orig=child._origMats[mi];if(mode==='default')return orig;const props={map:orig.map,color:orig.color,transparent:orig.transparent,opacity:orig.opacity,alphaTest:orig.alphaTest,side:orig.side,depthWrite:orig.depthWrite,blending:orig.blending,premultipliedAlpha:orig.premultipliedAlpha,name:orig.name};let nm;if(mode==='anime'){nm=new THREE.MeshToonMaterial(props);nm.emissive=new THREE.Color(0x222222)}else if(mode==='doll'){nm=new THREE.MeshPhongMaterial(props);nm.shininess=180;nm.specular=new THREE.Color(0xdddddd);nm.emissive=new THREE.Color(0x151515)}else if(mode==='real'){nm=new THREE.MeshStandardMaterial(props);const n=(orig.name||'').toLowerCase();if(/_hair/i.test(n)||/hairback/i.test(n)){nm.roughness=0.45;nm.metalness=0.05}else if(/_skin/i.test(n)||/face/i.test(n)||/body/i.test(n)){nm.roughness=0.75;nm.metalness=0}else if(/eye|iris|highlight/i.test(n)){nm.roughness=0.15;nm.metalness=0.1}else{nm.roughness=0.6;nm.metalness=0.02}}return nm||orig});child.material=newMats.length===1?newMats[0]:newMats})})}));document.querySelectorAll('.aspect-btn').forEach(btn=>btn.addEventListener('click',()=>{document.querySelectorAll('.aspect-btn').forEach(b=>b.classList.remove('active'));btn.classList.add('active');const v=btn.dataset.aspect;forcedAspect=v==='16:9'?16/9:v==='4:3'?4/3:v==='9:16'?9/16:null;updateRendererSize()}));function resetUiHideTimer(){document.body.classList.remove('ui-hidden');if(uiHideTimer)clearTimeout(uiHideTimer);if(isPlaying)uiHideTimer=setTimeout(()=>document.body.classList.add('ui-hidden'),UI_HIDE_DELAY)}document.addEventListener('pointerdown',resetUiHideTimer);document.addEventListener('pointermove',resetUiHideTimer)}
|
| 19 |
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}
|
| 20 |
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))})}
|