Spaces:
Running
Running
Download app.js from mg696/pmx-vmd-sync-player: direct link, hf CLI and curl.
- Browser
- Download file 47.3 kB
-
https://huggingface.co/spaces/mg696/pmx-vmd-sync-player/resolve/main/app.js
- Command line
-
hf download hf://spaces/mg696/pmx-vmd-sync-player/app.js
-
curl -L -o app.js https://huggingface.co/spaces/mg696/pmx-vmd-sync-player/resolve/main/app.js
47.3 kB
| 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'; | |
| 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=''});const debugCopyBtn=document.getElementById('debug-copy-btn');function copyDebugLog(e){if(e){e.preventDefault();e.stopPropagation()}const btn=debugCopyBtn,txt=debugLogEl.innerText||'';const done=ok=>{btn.textContent=ok?'✅コピー完了':'⚠コピー失敗';btn.style.background=ok?'#064':'#700';btn.style.color='#fff';setTimeout(()=>{btn.textContent='📋 Copy All';btn.style.background='';btn.style.color=''},1800)};function fallback(){try{const ta=document.createElement('textarea');ta.value=txt;ta.readOnly=true;ta.style.position='fixed';ta.style.left='0';ta.style.top='0';ta.style.opacity='0.01';document.body.appendChild(ta);ta.focus();ta.select();ta.setSelectionRange(0,ta.value.length);const ok=document.execCommand('copy');document.body.removeChild(ta);done(ok)}catch(err){done(false)}}if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(txt).then(()=>done(true)).catch(fallback);else fallback()}debugCopyBtn.addEventListener('click',copyDebugLog);debugCopyBtn.addEventListener('touchend',copyDebugLog,{passive:false});debugCopyBtn.addEventListener('pointerup',copyDebugLog);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')}); | |
| const APP_VER='v117';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')}`} | |
| 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)} | |
| 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])} | |
| 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)}}}} | |
| let scene,camera,renderer,controls,clock,mesh,mesh2,helper,stageMeshes=[],domeMeshes=[],audioContext,audioBuffer,audioSource,audioGainNode,audioStartTime=0,audioPausedAt=0,isPlaying=false,isLooping=false,isMuted=false,lastVolume=1,maxDuration=0,ammoInitialized=false;const modelData={mesh:{fileMap:{},manager:null,loader:null},mesh2:{fileMap:{},manager:null,loader:null},stage:{fileMap:{},manager:null,loader:null},dome:{fileMap:{},manager:null,loader:null}};let isSeeking=false,seekRAFPending=false,seekFinalizeTimer=null,wasPlayingBeforeSeek=false,gridHelper=null,floorMesh=null,shadowEnabled=false,groundMode='grid',playbackSpeed=1,uiHideTimer=null;const UI_HIDE_DELAY=3000;let mediaRecorder=null,recordedChunks=[],ambLight=null,mainLight=null,subLight=null,lightIntensityScale=1.0,currentLightPreset='studio',cameraVmdEnabled=false,forcedAspect=null,uiManualHidden=false; | |
| const modelPhysicsMap=new WeakMap(); | |
| function clearModelSlot(slot){const old=slot==='mesh'?mesh:mesh2;if(old){scene.remove(old);if(helper&&helper.objects&&helper.objects.has(old))helper.remove(old);modelPhysicsMap.delete(old);if(window.__mmdMeshes)window.__mmdMeshes=window.__mmdMeshes.filter(m=>m!==old)}for(const k in modelData[slot].fileMap){const v=modelData[slot].fileMap[k];if(typeof v==='string'&&v.startsWith('blob:'))URL.revokeObjectURL(v)}modelData[slot].fileMap={};if(slot==='mesh'){mesh=null;window.mesh=null;document.getElementById('vmd-label')?.classList.remove('ready')}else{mesh2=null;window.mesh2=null;document.getElementById('vmd2-label')?.classList.remove('ready')}const md=document.getElementById('mat-debug');if(md)md.innerHTML='';document.getElementById('morph-panel').style.display='none';document.getElementById('morph-sliders').innerHTML='';document.getElementById('morph-tabs').innerHTML='';dbg(`[SlotClear:v117] ${slot} cleared`,"info")} | |
| function normalizePath(path){let p=path.replace(/\\/g,'/').normalize('NFC');try{p=decodeURIComponent(p)}catch(e){}return p.replace(/^\.\//,'').replace(/%20/g,' ').toLowerCase()} | |
| 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")} | |
| 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)} | |
| 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()}})} | |
| 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} | |
| // ★v88: physics patch | |
| function patchNewModelPhysics(target){const mmd=target.geometry?.userData?.MMD;if(!mmd||!mmd.rigidBodies)return;const rbs=mmd.rigidBodies;let eyeFix=0,hairFix=0,sleeveFix=0;rbs.forEach(r=>{const rn=r.name||'';if(rn.includes('FaceEyeSet')||rn.includes('J_Adj_L_FaceEye')||rn.includes('J_Adj_R_FaceEye')){r.type=0;r.weight=1.0;eyeFix++;return}if(rn.startsWith('髪_')){const seg=parseInt(rn.split('_')[2])||1;if(seg===1){r.type=2;r.weight=0.05}else if(seg<=3){r.weight=r.weight*0.05}else{r.weight=r.weight*0.02}r.positionDamping=0.95;r.rotationDamping=0.95;hairFix++;return}if(rn.includes('Sleeve')){r.type=2;r.weight=0.05;sleeveFix++;return}});dbg(`[PhysPatch] eye:${eyeFix} hair:${hairFix} sleeve:${sleeveFix}`,"info")} | |
| 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} | |
| 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})})} | |
| 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)})})} | |
| 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});window.helper=helper;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;} | |
| 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}}} | |
| 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")}} | |
| 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'}if(loadType!=='stage'&&loadType!=='dome'&&m.emissive){const oldEm=m.emissive.getHexString();if(oldEm!=='000000'){m.emissive.setHex(0x000000);emFix++}}m.needsUpdate=true;dbg(` [Mat#${mc}] "${m.name}" → ${action}`)})});dbg(`[Material] ${mc}個, ${fc}修正, em=${emFix} (${loadType})`,"info")} | |
| function setupEventListeners(){document.getElementById('file-input').addEventListener('change',async e=>{if(!e.target.files.length)return;clearModelSlot('mesh');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)}});document.getElementById('file-input2').addEventListener('change',async e=>{if(!e.target.files.length)return;clearModelSlot('mesh2');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)}});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)}});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){}showLoading(false)},null,()=>{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||!mesh)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||!mesh2)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();dbg(`[Audio] ${file.name}`,"info")}catch(err){}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').value=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))}})});setupValInput('gravity-val','gravity-bar',v=>{[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,v,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){}}});document.getElementById('fullscreen-btn').addEventListener('click',()=>{if(!document.fullscreenElement)document.documentElement.requestFullscreen().catch(()=>{});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.value=v;const target=n==='1'?mesh:mesh2;if(target)target.position[axis]=v});setupValInput(`pos${n}-${axis}-val`,`pos${n}-${axis}`,v=>{const target=n==='1'?mesh:mesh2;if(target)target.position[axis]=v})}));document.getElementById('pos1-reset').addEventListener('click',()=>{['x','y','z'].forEach(a=>{document.getElementById(`pos1-${a}`).value=0;document.getElementById(`pos1-${a}-val`).value=0;if(mesh)mesh.position[a]=0})});document.getElementById('pos2-reset').addEventListener('click',()=>{['x','y','z'].forEach(a=>{document.getElementById(`pos2-${a}`).value=0;document.getElementById(`pos2-${a}-val`).value=0;if(mesh2)mesh2.position[a]=0})});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').value=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}});setupValInput('light-intensity-val','light-intensity',v=>{lightIntensityScale=v/100;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(0x000000)}else if(mode==='doll'){nm=new THREE.MeshPhongMaterial(props);nm.shininess=180;nm.specular=new THREE.Color(0xdddddd);nm.emissive=new THREE.Color(0x000000)}else if(mode==='real'){nm=new THREE.MeshStandardMaterial(props);nm.emissive=new THREE.Color(0x000000);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()}));document.getElementById('ui-toggle').addEventListener('click',()=>{uiManualHidden=!uiManualHidden;if(uiManualHidden)document.body.classList.add('ui-hidden');else document.body.classList.remove('ui-hidden')});function resetUiHideTimer(){if(uiManualHidden)return;document.body.classList.remove('ui-hidden');if(uiHideTimer)clearTimeout(uiHideTimer);if(isPlaying)uiHideTimer=setTimeout(()=>{if(!uiManualHidden)document.body.classList.add('ui-hidden')},UI_HIDE_DELAY)}document.addEventListener('pointerdown',resetUiHideTimer);document.addEventListener('pointermove',resetUiHideTimer)} | |
| 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} | |
| 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))})} | |
| 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)} | |
| 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("モーション準備完了♡")} | |
| function findFileInMap(ext,t){for(let key in modelData[t].fileMap)if(key.endsWith(ext))return key;return null} | |
| 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;window.mesh2=target}else{if(mesh){scene.remove(mesh);if(helper.objects.has(mesh))helper.remove(mesh)}mesh=target;window.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);let usePhys=ammoInitialized;if(!isOldModel&&ammoInitialized){patchNewModelPhysics(target)}modelPhysicsMap.set(target,usePhys);try{helper.add(target,{physics:usePhys});dbg(`[Helper] 追加 physics:${usePhys} (${isOldModel?'旧モデル':'新モデル(v117)'})`,"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)})} | |
| 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")} | |
| function togglePlay(){if(audioContext&&audioContext.state==='suspended')audioContext.resume();isPlaying?pause():play()} | |
| 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)} | |
| function pause(){if(audioSource&&audioContext){try{audioSource.stop()}catch(e){}audioPausedAt=Math.max(0,(audioContext.currentTime-audioStartTime)*playbackSpeed)}document.getElementById('play-icon').style.display='block';document.getElementById('pause-icon').style.display='none';isPlaying=false;if(uiHideTimer){clearTimeout(uiHideTimer);uiHideTimer=null}if(!uiManualHidden)document.body.classList.remove('ui-hidden')} | |
| function resetToStart(){const wp=isPlaying;if(wp)pause();audioPausedAt=0;helperSeekTo(0);[mesh,mesh2].forEach(m=>{if(!m||!helper.objects.has(m))return;const obj=helper.objects.get(m);if(obj.physics)obj.physics.reset()});document.getElementById('seek-bar').value=0;document.getElementById('time-current').textContent="0:00";document.getElementById('time-total').textContent='-'+formatTime(maxDuration);if(wp)play()} | |
| function updateRendererSize(){if(!camera||!renderer)return;const w=innerWidth,h=innerHeight;const container=document.getElementById('container');const canvas=renderer.domElement;if(forcedAspect){let rw=w,rh=Math.round(w/forcedAspect);if(rh>h){rh=h;rw=Math.round(h*forcedAspect)}renderer.setSize(rw,rh,false);canvas.style.width=rw+'px';canvas.style.height=rh+'px';container.style.width=rw+'px';container.style.height=rh+'px';container.style.left=Math.round((w-rw)/2)+'px';container.style.top=Math.round((h-rh)/2)+'px';container.style.right='auto';container.style.bottom='auto';camera.aspect=forcedAspect}else{renderer.setSize(w,h);canvas.style.width='';canvas.style.height='';container.style.width='';container.style.height='';container.style.left='0';container.style.top='0';container.style.right='0';container.style.bottom='0';camera.aspect=w/h}camera.updateProjectionMatrix()} | |
| function buildMorphUI(){const sd=document.getElementById('morph-sliders'),td=document.getElementById('morph-tabs');sd.innerHTML='';td.innerHTML='';const panel=document.getElementById('morph-panel');const targets=[];if(mesh&&mesh.morphTargetDictionary&&Object.keys(mesh.morphTargetDictionary).length>0)targets.push({label:'キャラ1',mesh:mesh});if(mesh2&&mesh2.morphTargetDictionary&&Object.keys(mesh2.morphTargetDictionary).length>0)targets.push({label:'キャラ2',mesh:mesh2});if(!targets.length){panel.style.display='none';return}panel.style.display='block';const pages=[];targets.forEach(({label,mesh:m},ti)=>{const page=document.createElement('div');page.style.display=ti===0?'block':'none';const dict=m.morphTargetDictionary;Object.keys(dict).sort((a,b)=>dict[a]-dict[b]).forEach(name=>{const idx=dict[name];const row=document.createElement('div');row.className='flex items-center gap-1 mb-1';row.innerHTML=`<span class="text-[7px] text-pink-300 w-16 truncate">${name}</span><input type="range" value="${Math.round((m.morphTargetInfluences[idx]||0)*100)}" min="0" max="100" step="1" class="h-1 flex-1"><input class="val-input" value="${Math.round((m.morphTargetInfluences[idx]||0)*100)}">`;const sl=row.querySelector('input[type="range"]'),vi=row.querySelector('.val-input');sl.addEventListener('input',()=>{m.morphTargetInfluences[idx]=parseInt(sl.value)/100;vi.value=sl.value});vi.addEventListener('blur',()=>{const v=parseInt(vi.value);if(isNaN(v)){vi.value=sl.value;return}const c=Math.max(0,Math.min(100,v));sl.value=c;vi.value=c;m.morphTargetInfluences[idx]=c/100});vi.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();vi.blur()}});page.appendChild(row)});pages.push(page);sd.appendChild(page);const tab=document.createElement('button');tab.className='sub-btn'+(ti===0?' active':'');tab.style.fontSize='8px';tab.style.padding='2px 6px';tab.textContent=`${label}(${Object.keys(dict).length})`;tab.addEventListener('click',()=>{pages.forEach(p=>p.style.display='none');page.style.display='block';td.querySelectorAll('button').forEach(b=>b.classList.remove('active'));tab.classList.add('active')});td.appendChild(tab)})} | |
| function updateSeekBarLimit(){document.getElementById('seek-bar').max=maxDuration||100;document.getElementById('time-total').textContent='-'+formatTime(maxDuration)}function updateStatus(msg){document.getElementById('status').textContent=msg}function formatTime(s){if(!isFinite(s)||s<0)s=0;return`${Math.floor(s/60)}:${Math.floor(s%60).toString().padStart(2,'0')}`}function showLoading(s,d){document.getElementById('loading').style.display=s?'flex':'none';if(d)document.getElementById('loading-detail').textContent=d} | |
| function animate(){requestAnimationFrame(animate);if(!clock||!renderer||!scene||!camera)return;const delta=clock.getDelta();if(isPlaying){let t;if(audioBuffer&&audioContext)t=(audioContext.currentTime-audioStartTime)*playbackSpeed;else{audioPausedAt+=delta*playbackSpeed;t=audioPausedAt}if(t<0)t=0;if(t>=maxDuration&&maxDuration>0){if(isLooping)resetToStart();else{audioPausedAt=maxDuration;pause();document.getElementById('seek-bar').value=maxDuration;document.getElementById('time-current').textContent=formatTime(maxDuration);document.getElementById('time-total').textContent='-0:00'}}else{try{helper.update(delta)}catch(e){}}if(!isSeeking)document.getElementById('seek-bar').value=t;document.getElementById('time-current').textContent=formatTime(t);document.getElementById('time-total').textContent='-'+formatTime(Math.max(0,maxDuration-t))}if(controls)controls.update();renderer.render(scene,camera)} | |
| window.onload=init; |