Spaces:
Running
Running
feat: update web app with 3D avatar studio, FBX rigged character, and updated UI
Browse filesFiles changed (24)
- .gitattributes+2
- app.js+1010-110
- assets/Ch46_nonPBR.fbxAdded+3
- assets/T-Pose.fbxAdded+3
- avatar/AvatarCanvas.jsAdded+374
- avatar/boneMap.jsAdded+184
- avatar/package.jsonAdded+4
- avatar/retargetUtils.jsAdded+197
- avatar/rig.jsAdded+420
- avatar/tests/register.mjsAdded+2
- avatar/tests/resolve-three.mjsAdded+13
- avatar/tests/retarget.test.mjsAdded+248
- avatar/tests/testRig.mjsAdded+70
- index.html+116-4
- style.css+533-1
- vendor/three/LICENSEAdded+21
- vendor/three/examples/jsm/controls/OrbitControls.jsAdded+1417
- vendor/three/examples/jsm/curves/NURBSCurve.jsAdded+80
- vendor/three/examples/jsm/curves/NURBSUtils.jsAdded+487
- vendor/three/examples/jsm/libs/fflate.module.jsAdded+2474
- vendor/three/examples/jsm/loaders/FBXLoader.jsAdded
- vendor/three/examples/jsm/loaders/GLTFLoader.jsAdded
- vendor/three/examples/jsm/utils/BufferGeometryUtils.jsAdded+1375
- vendor/three/three.module.jsAdded
34 unmodified lines35363734 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textASL_Alphabet_Chart.png filter=lfs diff=lfs merge=lfs -textISL_Hand_Signs_Official.png filter=lfs diff=lfs merge=lfs -text34 unmodified lines353637383934 unmodified lines*tfevents* filter=lfs diff=lfs merge=lfs -textASL_Alphabet_Chart.png filter=lfs diff=lfs merge=lfs -textISL_Hand_Signs_Official.png filter=lfs diff=lfs merge=lfs -textassets/Ch46_nonPBR.fbx filter=lfs diff=lfs merge=lfs -textassets/T-Pose.fbx filter=lfs diff=lfs merge=lfs -text
4 unmodified lines567891043 unmodified lines545556575859797 unmodified lines857858859860861862134 unmodified lines99799899910001001100210031004100510061007100810091010101110121013101410151016101710181 unmodified line102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105083 unmodified lines113411351136113711381139334 unmodified lines147414751476147714781479104 unmodified lines1584158515861587158815894 unmodified lines159415951596159715981599465 unmodified lines20652066206720682069207020712072207320742075207620772078207927 unmodified lines21072108210921102111211221133 unmodified lines2117211821192120212121226 unmodified lines21292130213121322133213490 unmodified lines222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236317 unmodified lines23812382238323844 unmodified lines* of our custom MLP Neural Network trained on the 21 hand landmarks.*/// ── Config ──────────────────────────────────────────────────────────────────let STREAK_NEEDED = 5; // frames of same letter to capture (settings sheet, matches native)const COOLDOWN_MS = 350; // ms after capture before detecting again (fluid sign transitions)43 unmodified lineslet streakCount = 0;let noHandCount = 0;// State tracking to prevent runaway letter repeat without releasing handlet lastCapturedLetter = '';let releasedSinceLastCapture = true;797 unmodified linesresetStreak();});document.getElementById('btn-pause-detection').addEventListener('click', function() {paused = !paused;this.textContent = paused ? 'Resume' : 'Pause';134 unmodified linesconst btnAsl = document.getElementById('btn-asl');const btnIsl = document.getElementById('btn-isl');const btnVisually = document.getElementById('btn-visually');const liveWorkspace = document.getElementById('live-workspace');const visuallyWorkspace = document.getElementById('visually-workspace');function isInVisuallyMode() {return visuallyWorkspace && !visuallyWorkspace.classList.contains('hidden');}btnAsl.addEventListener('click', () => {currentMode = 'asl';currentWeights = aslWeights;btnAsl.classList.add('active');btnIsl.classList.remove('active');if (btnVisually) btnVisually.classList.remove('active');modeToggle.classList.remove('isl-mode', 'visually-mode');if (liveWorkspace) liveWorkspace.classList.remove('hidden');if (visuallyWorkspace) visuallyWorkspace.classList.add('hidden');resetStreak();showToast('Switched to ASL (Live Camera)');});1 unmodified linebtnIsl.addEventListener('click', () => {currentMode = 'isl';currentWeights = islWeights;btnIsl.classList.add('active');btnAsl.classList.remove('active');if (btnVisually) btnVisually.classList.remove('active');modeToggle.classList.remove('visually-mode');modeToggle.classList.add('isl-mode');if (liveWorkspace) liveWorkspace.classList.remove('hidden');if (visuallyWorkspace) visuallyWorkspace.classList.add('hidden');resetStreak();showToast('Switched to ISL (Live Camera)');});if (btnVisually) {btnVisually.addEventListener('click', () => {btnVisually.classList.add('active');btnAsl.classList.remove('active');btnIsl.classList.remove('active');modeToggle.classList.remove('isl-mode');modeToggle.classList.add('visually-mode');if (liveWorkspace) liveWorkspace.classList.add('hidden');if (visuallyWorkspace) visuallyWorkspace.classList.remove('hidden');activatePracticeStudio();showToast('Practice Studio Active');});}// Settings sheet. Both thresholds are read live by processResult(),// so no restart is needed after a change.const setConf = document.getElementById('set-confidence');83 unmodified linesbtnIsl.click();} else if (e.key === '3') {if (btnVisually) btnVisually.click();}});}334 unmodified linessetupControls();initPracticeStudio();initSignGuide();setStatus('loading', 'Loading…');try {104 unmodified linesconsole.log('[PracticeStudio] Loaded sign templates:', Object.keys(data.asl || {}).length, 'ASL,', Object.keys(data.isl || {}).length, 'ISL');// Set initial posepracticeCurrentPose = clonePose(getTemplatePose('REST'));drawAvatar();const panelGuide = document.getElementById('panel-guide');if (panelGuide && (panelGuide.matches(':popover-open') || panelGuide.classList.contains('open'))) {4 unmodified linesconsole.warn('[PracticeStudio] Failed to load sign_templates.json:', err);});// 2. DOM elementsconst txtInput = document.getElementById('practice-input');const charCount = document.getElementById('practice-char-count');465 unmodified linesfunction avatarAnimationLoop(now) {practiceAnimFrameId = requestAnimationFrame(avatarAnimationLoop);// Calculate step timing based on speedconst transitionMs = 450 / practiceSpeed;const holdMs = 700 / practiceSpeed;const totalStepMs = transitionMs + holdMs;if (practiceToPose && practiceFromPose) {const elapsed = now - practiceStepStartTime;const progress = Math.min(1.0, elapsed / transitionMs);const t = easeInOutCubic(progress);if (!practiceCurrentPose) {practiceCurrentPose = clonePose(practiceFromPose);27 unmodified linespracticeCurrentPose.twoHanded = false;}// Interpolate wrist offsetspracticeCurrentPose.wristL = [lerp(practiceFromPose.wristL ? practiceFromPose.wristL[0] : 0, practiceToPose.wristL ? practiceToPose.wristL[0] : 0, t),lerp(practiceFromPose.wristL ? practiceFromPose.wristL[1] : 0, practiceToPose.wristL ? practiceToPose.wristL[1] : 0, t)3 unmodified lineslerp(practiceFromPose.wristR ? practiceFromPose.wristR[1] : 0, practiceToPose.wristR ? practiceToPose.wristR[1] : 0, t)];practiceCurrentPose.desc = practiceToPose.desc;if (practiceIsPlaying && elapsed >= totalStepMs) {if (practiceCurrentIndex < practiceSequence.length - 1) {6 unmodified lines}}drawAvatar();}90 unmodified linesctx.save();ctx.clearRect(0, 0, w, h);// 1. Studio background (theme-aware)const isLight = document.documentElement.getAttribute('data-theme') === 'light';ctx.fillStyle = isLight ? '#eaedf4' : '#161619';ctx.fillRect(0, 0, w, h);// 2. Stylized Red Silhouette Avatar (Head, Face, Torso, Arms - matching RyloTranslate)const red = '#d82222';ctx.strokeStyle = red;ctx.fillStyle = red;ctx.lineCap = 'round';ctx.lineJoin = 'round';ctx.shadowBlur = 0;// Shoulder & torso anchor pointsconst shoulderY = h * 0.48;const leftShoulderX = w * 0.33;const rightShoulderX = w * 0.71;// Head dimensionsconst headCx = w * 0.51;const headCy = h * 0.25;const headRx = w * 0.082;const headRy = h * 0.125;// Head contourctx.lineWidth = 5 * dpr;ctx.beginPath();ctx.ellipse(headCx, headCy, headRx, headRy, 0, 0, Math.PI * 2);ctx.stroke();// Eyebrows (bold expressive arches)ctx.lineWidth = 7 * dpr;ctx.beginPath();ctx.arc(headCx - headRx * 0.44, headCy - headRy * 0.35, headRx * 0.34, Math.PI * 1.1, Math.PI * 1.9, false);ctx.stroke();ctx.beginPath();ctx.arc(headCx + headRx * 0.44, headCy - headRy * 0.35, headRx * 0.34, Math.PI * 1.1, Math.PI * 1.9, false);ctx.stroke();// Eyes (almond shaped contours)ctx.lineWidth = 3.5 * dpr;ctx.beginPath();ctx.ellipse(headCx - headRx * 0.42, headCy - headRy * 0.12, headRx * 0.24, headRy * 0.12, 0, 0, Math.PI * 2);ctx.stroke();ctx.beginPath();ctx.ellipse(headCx + headRx * 0.42, headCy - headRy * 0.12, headRx * 0.24, headRy * 0.12, 0, 0, Math.PI * 2);ctx.stroke();// Mouth (expressive open oval)ctx.lineWidth = 4.5 * dpr;ctx.beginPath();ctx.ellipse(headCx, headCy + headRy * 0.38, headRx * 0.32, headRy * 0.16, 0, 0, Math.PI * 2);ctx.stroke();// Torso Frame:ctx.lineWidth = 5 * dpr;// Clavicle / shoulder horizontal barctx.beginPath();ctx.moveTo(leftShoulderX, shoulderY);ctx.lineTo(rightShoulderX, shoulderY);ctx.stroke();// Torso body lines (tapering downwards)ctx.beginPath();ctx.moveTo(leftShoulderX, shoulderY);ctx.lineTo(w * 0.39, h * 0.98);ctx.moveTo(rightShoulderX, shoulderY);ctx.lineTo(w * 0.65, h * 0.98);ctx.stroke();// Determine dual-hand vs single-hand postureconst is2H = practiceCurrentPose && practiceCurrentPose.twoHanded && practiceCurrentPose.left;const handScale = Math.min(w * 0.20, h * 0.20);if (is2H) {// TWO-HANDED MODE: Both arms raised into signing spaceconst offLx = (practiceCurrentPose.wristL ? practiceCurrentPose.wristL[0] : 0) * handScale;const offLy = (practiceCurrentPose.wristL ? practiceCurrentPose.wristL[1] : 0) * handScale;const offRx = (practiceCurrentPose.wristR ? practiceCurrentPose.wristR[0] : 0) * handScale;const offRy = (practiceCurrentPose.wristR ? practiceCurrentPose.wristR[1] : 0) * handScale;const wristL_X = w * 0.37 + offLx;const wristL_Y = h * 0.65 + offLy;const wristR_X = w * 0.63 + offRx;const wristR_Y = h * 0.65 + offRy;const elbowL_X = leftShoulderX - w * 0.07;const elbowL_Y = (shoulderY + wristL_Y) / 2 + h * 0.08;const elbowR_X = rightShoulderX + w * 0.07;const elbowR_Y = (shoulderY + wristR_Y) / 2 + h * 0.08;// Left Arm (viewer-left): Shoulder -> Elbow -> Wristctx.beginPath();ctx.moveTo(leftShoulderX, shoulderY);ctx.lineTo(elbowL_X, elbowL_Y);ctx.lineTo(wristL_X, wristL_Y);ctx.stroke();// Right Arm (viewer-right): Shoulder -> Elbow -> Wristctx.beginPath();ctx.moveTo(rightShoulderX, shoulderY);ctx.lineTo(elbowR_X, elbowR_Y);ctx.lineTo(wristR_X, wristR_Y);ctx.stroke();// Render both hand skeletonsdrawHandSkeleton(ctx, practiceCurrentPose.left, wristL_X, wristL_Y, dpr, handScale, true);drawHandSkeleton(ctx, practiceCurrentPose.right, wristR_X, wristR_Y, dpr, handScale, false);} else {// SINGLE-HANDED MODE: Dominant signing arm active, other arm resting naturallyconst wristX = w * 0.34;const wristY = h * 0.65;const elbowL_X = w * 0.24;const elbowL_Y = h * 0.84;// Signing Arm (viewer-left): Shoulder -> Elbow -> Wristctx.beginPath();ctx.moveTo(leftShoulderX, shoulderY);ctx.lineTo(elbowL_X, elbowL_Y);ctx.lineTo(wristX, wristY);ctx.stroke();// Resting Arm (viewer-right): Shoulder -> Elbow -> Forearm downconst elbowR_X = w * 0.76;const elbowR_Y = h * 0.82;ctx.beginPath();ctx.moveTo(rightShoulderX, shoulderY);ctx.lineTo(elbowR_X, elbowR_Y);ctx.lineTo(w * 0.68, h * 0.98);ctx.stroke();// Render single hand skeletonconst singlePose = practiceCurrentPose ? (practiceCurrentPose.right || practiceCurrentPose.left) : null;if (singlePose) {drawHandSkeleton(ctx, singlePose, wristX, wristY, dpr, handScale, false);17 unmodified linescanvas.height = Math.floor(rect.height) * dpr;}}}4 unmodified lines5678910111213141543 unmodified lines596061626364656667797 unmodified lines865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899134 unmodified lines10341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611 unmodified line1063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109783 unmodified lines11811182118311841185118611871188334 unmodified lines1523152415251526152715281529104 unmodified lines163416351636163716381639164016411642164316444 unmodified lines1649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688465 unmodified lines215421552156215721582159216021612162216321642165216621672168216921702171217221732174217527 unmodified lines22032204220522062207220822093 unmodified lines221322142215221622172218221922206 unmodified lines22272228222922302231223222332234223590 unmodified lines232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280617 unmodified lines282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332844 unmodified lines* of our custom MLP Neural Network trained on the 21 hand landmarks.*/// ── Avatar 3D Module ────────────────────────────────────────────────────────import { AvatarCanvas } from './avatar/AvatarCanvas.js?v=28';let globalAvatar3D = null;window.globalAvatar3D = null;// ── Config ──────────────────────────────────────────────────────────────────let STREAK_NEEDED = 5; // frames of same letter to capture (settings sheet, matches native)const COOLDOWN_MS = 350; // ms after capture before detecting again (fluid sign transitions)43 unmodified lineslet streakCount = 0;let noHandCount = 0;// Camera view mirror state (default: false for normal real view, togglable to mirror)let cameraMirrorMode = localStorage.getItem('signlens_camera_mirror') === 'true';// State tracking to prevent runaway letter repeat without releasing handlet lastCapturedLetter = '';let releasedSinceLastCapture = true;797 unmodified linesresetStreak();});// Mirror Camera Toggleconst btnMirror = document.getElementById('btn-mirror-toggle');function updateMirrorUI() {if (!displayCanvas) return;if (cameraMirrorMode) {displayCanvas.classList.add('mirrored');if (btnMirror) {btnMirror.innerHTML = '🪞 Mirror: On';btnMirror.classList.add('active-btn');}} else {displayCanvas.classList.remove('mirrored');if (btnMirror) {btnMirror.innerHTML = '📷 Normal View';btnMirror.classList.remove('active-btn');}}}updateMirrorUI();if (btnMirror) {btnMirror.addEventListener('click', () => {cameraMirrorMode = !cameraMirrorMode;localStorage.setItem('signlens_camera_mirror', cameraMirrorMode);updateMirrorUI();showToast(cameraMirrorMode ? '🪞 Mirror Mode Enabled' : '📷 Normal View Enabled');});}document.getElementById('btn-pause-detection').addEventListener('click', function() {paused = !paused;this.textContent = paused ? 'Resume' : 'Pause';134 unmodified linesconst btnAsl = document.getElementById('btn-asl');const btnIsl = document.getElementById('btn-isl');const btnVisually = document.getElementById('btn-visually');const btnUpload = document.getElementById('btn-upload');const liveWorkspace = document.getElementById('live-workspace');const visuallyWorkspace = document.getElementById('visually-workspace');const uploadWorkspace = document.getElementById('upload-workspace');function hideAllWorkspaces() {if (liveWorkspace) liveWorkspace.classList.add('hidden');if (visuallyWorkspace) visuallyWorkspace.classList.add('hidden');if (uploadWorkspace) uploadWorkspace.classList.add('hidden');btnAsl.classList.remove('active');btnIsl.classList.remove('active');if (btnVisually) btnVisually.classList.remove('active');if (btnUpload) btnUpload.classList.remove('active');modeToggle.classList.remove('isl-mode', 'visually-mode', 'upload-mode');}btnAsl.addEventListener('click', () => {currentMode = 'asl';currentWeights = aslWeights;hideAllWorkspaces();btnAsl.classList.add('active');if (liveWorkspace) liveWorkspace.classList.remove('hidden');resetStreak();showToast('Switched to ASL (Live Camera)');});1 unmodified linebtnIsl.addEventListener('click', () => {currentMode = 'isl';currentWeights = islWeights;hideAllWorkspaces();btnIsl.classList.add('active');modeToggle.classList.add('isl-mode');if (liveWorkspace) liveWorkspace.classList.remove('hidden');resetStreak();showToast('Switched to ISL (Live Camera)');});if (btnVisually) {btnVisually.addEventListener('click', () => {hideAllWorkspaces();btnVisually.classList.add('active');modeToggle.classList.add('visually-mode');if (visuallyWorkspace) visuallyWorkspace.classList.remove('hidden');activatePracticeStudio();showToast('Practice Studio Active');});}if (btnUpload) {btnUpload.addEventListener('click', () => {hideAllWorkspaces();btnUpload.classList.add('active');modeToggle.classList.add('upload-mode');if (uploadWorkspace) uploadWorkspace.classList.remove('hidden');showToast('Upload Image Recognition Active');});}// Settings sheet. Both thresholds are read live by processResult(),// so no restart is needed after a change.const setConf = document.getElementById('set-confidence');83 unmodified linesbtnIsl.click();} else if (e.key === '3') {if (btnVisually) btnVisually.click();} else if (e.key === '4') {if (btnUpload) btnUpload.click();}});}334 unmodified linessetupControls();initPracticeStudio();initSignGuide();initUploadStudio();setStatus('loading', 'Loading…');try {104 unmodified linesconsole.log('[PracticeStudio] Loaded sign templates:', Object.keys(data.asl || {}).length, 'ASL,', Object.keys(data.isl || {}).length, 'ISL');// Set initial posepracticeCurrentPose = clonePose(getTemplatePose('REST'));window.practiceCurrentPose = practiceCurrentPose;// ── Initialize 3D Avatar (Feature Flag: window.USE_3D_AVATAR) ──initAvatar3DRenderer();drawAvatar();const panelGuide = document.getElementById('panel-guide');if (panelGuide && (panelGuide.matches(':popover-open') || panelGuide.classList.contains('open'))) {4 unmodified linesconsole.warn('[PracticeStudio] Failed to load sign_templates.json:', err);});function initAvatar3DRenderer() {if (window.USE_3D_AVATAR === false) {if (globalAvatar3D) {globalAvatar3D.dispose();globalAvatar3D = null;window.globalAvatar3D = null;}return;}const canvas3D = document.getElementById('avatar-canvas-3d');if (!globalAvatar3D && canvas3D) {try {const restHand = practiceTemplates?.asl?.REST || null;globalAvatar3D = new AvatarCanvas(canvas3D, {modelUrl: './assets/Ch46_nonPBR.fbx',restHand: restHand,onReady: () => {console.log('[PracticeStudio] 3D Avatar active and tracking practice playback.');if (ctx && canvas) {ctx.clearRect(0, 0, canvas.width, canvas.height);}},onError: (err) => {console.info('[PracticeStudio] Falling back to 2D character renderer while 3D model is not present.');}});window.globalAvatar3D = globalAvatar3D;} catch (err) {console.warn('[PracticeStudio] Failed to initialize Three.js AvatarCanvas:', err);}}}window._reinitAvatarRenderer = initAvatar3DRenderer;// 2. DOM elementsconst txtInput = document.getElementById('practice-input');const charCount = document.getElementById('practice-char-count');465 unmodified linesfunction avatarAnimationLoop(now) {practiceAnimFrameId = requestAnimationFrame(avatarAnimationLoop);// Timing for step transitions (smoother spring-like curve at high refresh rate)const transitionMs = 600 / practiceSpeed;const holdMs = 850 / practiceSpeed;const totalStepMs = transitionMs + holdMs;// Organic micro-breathing & idle motion for natural 60 FPS live feelconst breathT = (now * 0.0022);const breathOffset = Math.sin(breathT) * 1.5;if (practiceToPose && practiceFromPose) {const elapsed = now - practiceStepStartTime;const rawProgress = Math.min(1.0, elapsed / transitionMs);// Quintic smoothstep for butter-smooth 60fps acceleration and decelerationconst t = rawProgress < 0.5? 16 * Math.pow(rawProgress, 5): 1 - Math.pow(-2 * rawProgress + 2, 5) / 2;if (!practiceCurrentPose) {practiceCurrentPose = clonePose(practiceFromPose);27 unmodified linespracticeCurrentPose.twoHanded = false;}// Interpolate wrist offsets with subtle micro-swaypracticeCurrentPose.wristL = [lerp(practiceFromPose.wristL ? practiceFromPose.wristL[0] : 0, practiceToPose.wristL ? practiceToPose.wristL[0] : 0, t),lerp(practiceFromPose.wristL ? practiceFromPose.wristL[1] : 0, practiceToPose.wristL ? practiceToPose.wristL[1] : 0, t)3 unmodified lineslerp(practiceFromPose.wristR ? practiceFromPose.wristR[1] : 0, practiceToPose.wristR ? practiceToPose.wristR[1] : 0, t)];practiceCurrentPose.desc = practiceToPose.desc;practiceCurrentPose.breathOffset = breathOffset;window.practiceCurrentPose = practiceCurrentPose;if (practiceIsPlaying && elapsed >= totalStepMs) {if (practiceCurrentIndex < practiceSequence.length - 1) {6 unmodified lines}}// When 3D Avatar has loaded its rig and is rendering via WebGL, skip 2D canvas drawingif (globalAvatar3D && globalAvatar3D.rig) return;drawAvatar();}90 unmodified linesctx.save();ctx.clearRect(0, 0, w, h);// 1. Studio background (theme-aware soft vignette)const isLight = document.documentElement.getAttribute('data-theme') === 'light';const bgGrad = ctx.createRadialGradient(w * 0.5, h * 0.45, 10, w * 0.5, h * 0.5, Math.max(w, h) * 0.75);if (isLight) {bgGrad.addColorStop(0, '#f8fafc');bgGrad.addColorStop(0.6, '#edf2f7');bgGrad.addColorStop(1, '#e2e8f0');} else {bgGrad.addColorStop(0, '#1c1f26');bgGrad.addColorStop(0.6, '#14161b');bgGrad.addColorStop(1, '#0c0d10');}ctx.fillStyle = bgGrad;ctx.fillRect(0, 0, w, h);// 2. Continuous 60fps Micro-Motion Dynamicsconst breath = (practiceCurrentPose && practiceCurrentPose.breathOffset !== undefined)? practiceCurrentPose.breathOffset: 0;// Harmonious Skin & Clothing Paletteconst skinBase = isLight ? '#f2caa7' : '#d8af8c';const skinShadow = isLight ? '#dbaa83' : '#be8f6c';const skinHighlight = isLight ? '#fce5d4' : '#eaceb9';const hairBase = isLight ? '#2a1f1b' : '#1b1411';const hairHighlight = isLight ? '#44352e' : '#332722';const clothesTone = isLight ? '#1e293b' : '#18202f';const clothesHighlight = isLight ? '#334155' : '#273447';const collarTone = isLight ? '#e2e8f0' : '#334155';// Perfectly Balanced Proportions// Head size & center (natural human ratio ~ 1:7.5)const headCx = w * 0.50;const headCy = h * 0.22 + breath * 0.4;const headRx = w * 0.092;const headRy = h * 0.118;// Shoulders & Torso anchors (broad, natural masculine/athletic posture)const shoulderY = h * 0.41 + breath;const leftShoulderX = w * 0.33;const rightShoulderX = w * 0.67;// Neck dimensionsconst neckTopY = headCy + headRy * 0.70;const neckBottomY = shoulderY + h * 0.02;const neckHalfW = headRx * 0.44;// ── NECK & TRAPEZIUS (Base layer drawn behind head) ──ctx.save();// Trapezius muscles connecting neck to shouldersconst trapGrad = ctx.createLinearGradient(0, headCy + headRy, 0, shoulderY);trapGrad.addColorStop(0, skinShadow);trapGrad.addColorStop(1, skinBase);ctx.fillStyle = trapGrad;ctx.beginPath();ctx.moveTo(headCx - neckHalfW * 1.05, neckTopY);ctx.quadraticCurveTo(headCx - neckHalfW * 1.5, shoulderY - h * 0.02, leftShoulderX, shoulderY);ctx.lineTo(rightShoulderX, shoulderY);ctx.quadraticCurveTo(headCx + neckHalfW * 1.5, shoulderY - h * 0.02, headCx + neckHalfW * 1.05, neckTopY);ctx.closePath();ctx.fill();// Neck cylinder with cylindrical 3D radial/linear shadingconst neckGrad = ctx.createLinearGradient(headCx - neckHalfW, 0, headCx + neckHalfW, 0);neckGrad.addColorStop(0, skinShadow);neckGrad.addColorStop(0.25, skinBase);neckGrad.addColorStop(0.70, skinHighlight);neckGrad.addColorStop(1, skinShadow);ctx.fillStyle = neckGrad;ctx.beginPath();ctx.moveTo(headCx - neckHalfW, neckTopY);ctx.lineTo(headCx - neckHalfW * 1.25, neckBottomY);ctx.quadraticCurveTo(headCx, neckBottomY + 8 * dpr, headCx + neckHalfW * 1.25, neckBottomY);ctx.lineTo(headCx + neckHalfW, neckTopY);ctx.closePath();ctx.fill();// Deep under-jaw shadowconst chinShadowGrad = ctx.createRadialGradient(headCx, neckTopY, 0, headCx, neckTopY, neckHalfW * 1.8);chinShadowGrad.addColorStop(0, 'rgba(0, 0, 0, 0.28)');chinShadowGrad.addColorStop(0.7, 'rgba(0, 0, 0, 0.12)');chinShadowGrad.addColorStop(1, 'rgba(0, 0, 0, 0.0)');ctx.fillStyle = chinShadowGrad;ctx.beginPath();ctx.ellipse(headCx, neckTopY + 2, neckHalfW * 1.3, 14 * dpr, 0, 0, Math.PI);ctx.fill();ctx.restore();// ── TORSO & CLOTHING (Modern crewneck sweater / tee) ──ctx.save();const torsoGrad = ctx.createLinearGradient(0, shoulderY - 10, 0, h);torsoGrad.addColorStop(0, clothesHighlight);torsoGrad.addColorStop(0.3, clothesTone);torsoGrad.addColorStop(1, isLight ? '#0f172a' : '#0b0f19');ctx.fillStyle = torsoGrad;ctx.beginPath();// Neckline collar anchorctx.moveTo(headCx - neckHalfW * 1.25, shoulderY - h * 0.01);// Smooth left shoulder archctx.bezierCurveTo(w * 0.38, shoulderY - h * 0.01,leftShoulderX + w * 0.02, shoulderY - h * 0.005,leftShoulderX, shoulderY + h * 0.015);// Left torso side bodyctx.lineTo(w * 0.32, h * 0.99);ctx.lineTo(w * 0.68, h * 0.99);// Right torso side bodyctx.lineTo(rightShoulderX, shoulderY + h * 0.015);// Smooth right shoulder archctx.bezierCurveTo(rightShoulderX - w * 0.02, shoulderY - h * 0.005,w * 0.62, shoulderY - h * 0.01,headCx + neckHalfW * 1.25, shoulderY - h * 0.01);ctx.closePath();ctx.fill();// Ribbed Crewneck Collar (outer & inner)ctx.fillStyle = collarTone;ctx.beginPath();ctx.ellipse(headCx, shoulderY + 4 * dpr, neckHalfW * 1.35, 14 * dpr, 0, 0, Math.PI * 2);ctx.fill();// Inner collar scoopctx.fillStyle = skinShadow;ctx.beginPath();ctx.ellipse(headCx, shoulderY + 2 * dpr, neckHalfW * 1.05, 9 * dpr, 0, 0, Math.PI * 2);ctx.fill();// Clavicle & chest contour creasesctx.strokeStyle = 'rgba(255, 255, 255, 0.07)';ctx.lineWidth = 2 * dpr;ctx.beginPath();ctx.moveTo(headCx - neckHalfW * 1.3, shoulderY + 18 * dpr);ctx.quadraticCurveTo(headCx, shoulderY + 28 * dpr, headCx + neckHalfW * 1.3, shoulderY + 18 * dpr);ctx.stroke();ctx.restore();// ── EARS (Behind face, natural organic pinna) ──const earY = headCy + headRy * 0.05;const earRx = headRx * 0.20;const earRy = headRy * 0.30;[-1, 1].forEach(dir => {const ex = headCx + dir * (headRx * 0.98);ctx.fillStyle = skinShadow;ctx.beginPath();ctx.ellipse(ex, earY, earRx, earRy, dir * 0.08, 0, Math.PI * 2);ctx.fill();// Inner ear fossa foldctx.fillStyle = 'rgba(0, 0, 0, 0.12)';ctx.beginPath();ctx.ellipse(ex - dir * 2, earY, earRx * 0.55, earRy * 0.55, dir * 0.08, 0, Math.PI * 2);ctx.fill();});// ── HEAD & JAW SHAPE (Smooth handsome proportioned jawline) ──ctx.save();const faceGrad = ctx.createRadialGradient(headCx - headRx * 0.2, headCy - headRy * 0.25, headRx * 0.1,headCx, headCy, headRy * 1.15);faceGrad.addColorStop(0, skinHighlight);faceGrad.addColorStop(0.55, skinBase);faceGrad.addColorStop(1, skinShadow);ctx.fillStyle = faceGrad;ctx.beginPath();// Start at templesctx.moveTo(headCx - headRx, headCy - headRy * 0.2);// Smooth cheek and tapered jaw to chinctx.bezierCurveTo(headCx - headRx * 0.98, headCy + headRy * 0.40,headCx - headRx * 0.55, headCy + headRy * 0.90,headCx - headRx * 0.24, headCy + headRy);// Flat rounded chinctx.quadraticCurveTo(headCx, headCy + headRy * 1.02, headCx + headRx * 0.24, headCy + headRy);// Right cheek and tapered jawctx.bezierCurveTo(headCx + headRx * 0.55, headCy + headRy * 0.90,headCx + headRx * 0.98, headCy + headRy * 0.40,headCx + headRx, headCy - headRy * 0.2);// Cranium topctx.bezierCurveTo(headCx + headRx, headCy - headRy * 1.05,headCx - headRx, headCy - headRy * 1.05,headCx - headRx, headCy - headRy * 0.2);ctx.closePath();ctx.fill();// Subtle natural jawline definitionctx.strokeStyle = isLight ? 'rgba(120, 80, 60, 0.20)' : 'rgba(255, 255, 255, 0.10)';ctx.lineWidth = 1.6 * dpr;ctx.stroke();// ── STYLISH MODERN HAIR (Volumetric layered brush-back crop) ──const hairGrad = ctx.createLinearGradient(0, headCy - headRy * 1.25, 0, headCy);hairGrad.addColorStop(0, hairHighlight);hairGrad.addColorStop(1, hairBase);ctx.fillStyle = hairGrad;ctx.beginPath();ctx.moveTo(headCx - headRx * 1.04, headCy - headRy * 0.15);// Sideburn leftctx.lineTo(headCx - headRx * 0.96, headCy + headRy * 0.08);ctx.lineTo(headCx - headRx * 0.88, headCy - headRy * 0.18);// Volumetric top with texturectx.bezierCurveTo(headCx - headRx * 1.10, headCy - headRy * 1.05,headCx - headRx * 0.40, headCy - headRy * 1.35,headCx, headCy - headRy * 1.25);ctx.bezierCurveTo(headCx + headRx * 0.45, headCy - headRy * 1.35,headCx + headRx * 1.12, headCy - headRy * 1.02,headCx + headRx * 1.04, headCy - headRy * 0.15);// Sideburn rightctx.lineTo(headCx + headRx * 0.88, headCy - headRy * 0.18);ctx.lineTo(headCx + headRx * 0.96, headCy + headRy * 0.08);// Hairline across forehead with natural textured sweepctx.quadraticCurveTo(headCx + headRx * 0.80, headCy - headRy * 0.50, headCx + headRx * 0.50, headCy - headRy * 0.55);ctx.quadraticCurveTo(headCx + headRx * 0.20, headCy - headRy * 0.65, headCx - headRx * 0.10, headCy - headRy * 0.50);ctx.quadraticCurveTo(headCx - headRx * 0.50, headCy - headRy * 0.60, headCx - headRx * 0.90, headCy - headRy * 0.40);ctx.closePath();ctx.fill();// Subtle hairline highlight sheenctx.strokeStyle = hairHighlight;ctx.lineWidth = 2.0 * dpr;ctx.beginPath();ctx.moveTo(headCx - headRx * 0.6, headCy - headRy * 1.05);ctx.quadraticCurveTo(headCx, headCy - headRy * 1.18, headCx + headRx * 0.5, headCy - headRy * 1.02);ctx.stroke();// ── EYEBROWS (Natural feathered arches) ──ctx.strokeStyle = hairBase;ctx.lineWidth = 3.6 * dpr;ctx.lineCap = 'round';const browY = headCy - headRy * 0.15;// Left eyebrowctx.beginPath();ctx.moveTo(headCx - headRx * 0.60, browY + 1 * dpr);ctx.quadraticCurveTo(headCx - headRx * 0.38, browY - 6 * dpr, headCx - headRx * 0.14, browY);ctx.stroke();// Right eyebrowctx.beginPath();ctx.moveTo(headCx + headRx * 0.14, browY);ctx.quadraticCurveTo(headCx + headRx * 0.38, browY - 6 * dpr, headCx + headRx * 0.60, browY + 1 * dpr);ctx.stroke();// ── EYES (Realistic almond contour, iris, pupil, gleam) ──const eyeY = headCy - headRy * 0.01;const eyeSpacing = headRx * 0.38;const eyeW = headRx * 0.22;const eyeH = headRy * 0.11;[-1, 1].forEach(dir => {const ex = headCx + dir * eyeSpacing;// Almond eye scleractx.fillStyle = '#ffffff';ctx.beginPath();ctx.moveTo(ex - eyeW, eyeY);ctx.quadraticCurveTo(ex, eyeY - eyeH * 1.1, ex + eyeW, eyeY);ctx.quadraticCurveTo(ex, eyeY + eyeH * 0.95, ex - eyeW, eyeY);ctx.closePath();ctx.fill();// Soft eyelid outlinectx.strokeStyle = isLight ? 'rgba(70, 40, 30, 0.45)' : 'rgba(255, 230, 220, 0.35)';ctx.lineWidth = 1.4 * dpr;ctx.stroke();// Iris (Warm Hazel-Amber)ctx.save();ctx.beginPath();ctx.arc(ex, eyeY, eyeH * 0.88, 0, Math.PI * 2);ctx.fillStyle = '#4c3525';ctx.fill();// Pupilctx.fillStyle = '#121215';ctx.beginPath();ctx.arc(ex, eyeY, eyeH * 0.48, 0, Math.PI * 2);ctx.fill();// Catchlight sparkle (vital for life-like presence)ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';ctx.beginPath();ctx.arc(ex - eyeW * 0.18, eyeY - eyeH * 0.22, 1.8 * dpr, 0, Math.PI * 2);ctx.fill();ctx.restore();// Upper eyelid crease (fold)ctx.strokeStyle = isLight ? 'rgba(100, 60, 45, 0.35)' : 'rgba(255, 255, 255, 0.15)';ctx.lineWidth = 1.6 * dpr;ctx.beginPath();ctx.arc(ex, eyeY - 2 * dpr, eyeW * 0.95, Math.PI * 1.15, Math.PI * 1.85, false);ctx.stroke();});// ── NOSE (Subtle sculpted bridge and philtrum) ──const noseY = headCy + headRy * 0.26;ctx.strokeStyle = isLight ? 'rgba(130, 85, 65, 0.42)' : 'rgba(255, 210, 190, 0.35)';ctx.lineWidth = 2.0 * dpr;ctx.lineCap = 'round';ctx.beginPath();ctx.moveTo(headCx - 1 * dpr, headCy + headRy * 0.06);ctx.lineTo(headCx - 2 * dpr, noseY);ctx.quadraticCurveTo(headCx, noseY + 3 * dpr, headCx + 4 * dpr, noseY);ctx.stroke();// ── MOUTH (Warm, confident, natural masculine lips) ──const mouthY = headCy + headRy * 0.52;const mouthW = headRx * 0.32;// Upper lipctx.fillStyle = isLight ? '#c86f66' : '#ad5950';ctx.beginPath();ctx.moveTo(headCx - mouthW, mouthY);ctx.quadraticCurveTo(headCx - mouthW * 0.3, mouthY - 3 * dpr, headCx, mouthY - 1 * dpr);ctx.quadraticCurveTo(headCx + mouthW * 0.3, mouthY - 3 * dpr, headCx + mouthW, mouthY);ctx.quadraticCurveTo(headCx, mouthY + 3 * dpr, headCx - mouthW, mouthY);ctx.fill();// Lower lipctx.fillStyle = isLight ? '#d47b74' : '#ba665f';ctx.beginPath();ctx.moveTo(headCx - mouthW * 0.75, mouthY + 1 * dpr);ctx.quadraticCurveTo(headCx, mouthY + headRy * 0.12, headCx + mouthW * 0.75, mouthY + 1 * dpr);ctx.quadraticCurveTo(headCx, mouthY + 2 * dpr, headCx - mouthW * 0.75, mouthY + 1 * dpr);ctx.fill();// Lip center linectx.strokeStyle = isLight ? '#993d36' : '#7a2d27';ctx.lineWidth = 1.4 * dpr;ctx.beginPath();ctx.moveTo(headCx - mouthW, mouthY);ctx.quadraticCurveTo(headCx, mouthY + 2 * dpr, headCx + mouthW, mouthY);ctx.stroke();ctx.restore(); // restore face canvas state// ── VOLUMETRIC SLEEVES & ANATOMICAL ARMS ──// Seamless limb renderer with smooth joint caps and shadingfunction drawHumanArm(shoulderX, shoulderY, elbowX, elbowY, wristX, wristY) {const sleeveWidth = 18 * dpr;const bicepWidth = 14 * dpr;const elbowWidth = 12 * dpr;const wristWidth = 9.5 * dpr;const sleeveGrad = ctx.createLinearGradient(shoulderX, shoulderY, elbowX, elbowY);sleeveGrad.addColorStop(0, clothesHighlight);sleeveGrad.addColorStop(1, clothesTone);const skinGrad = ctx.createLinearGradient(elbowX, elbowY, wristX, wristY);skinGrad.addColorStop(0, skinShadow);skinGrad.addColorStop(0.5, skinBase);skinGrad.addColorStop(1, skinHighlight);const strokeCol = isLight ? 'rgba(40, 25, 20, 0.18)' : 'rgba(255, 255, 255, 0.10)';// 1. Upper Arm (Short Sleeve Shirt)const dx1 = elbowX - shoulderX;const dy1 = elbowY - shoulderY;const len1 = Math.sqrt(dx1 * dx1 + dy1 * dy1) || 1;const nx1 = -dy1 / len1;const ny1 = dx1 / len1;// Draw shoulder ball cap for seamless blending into torsoctx.fillStyle = sleeveGrad;ctx.beginPath();ctx.arc(shoulderX, shoulderY, sleeveWidth, 0, Math.PI * 2);ctx.fill();// Upper arm sleeve bodyctx.beginPath();ctx.moveTo(shoulderX + nx1 * sleeveWidth, shoulderY + ny1 * sleeveWidth);ctx.lineTo(elbowX + nx1 * bicepWidth, elbowY + ny1 * bicepWidth);ctx.arc(elbowX, elbowY, bicepWidth, Math.atan2(ny1, nx1), Math.atan2(-ny1, -nx1), false);ctx.lineTo(shoulderX - nx1 * sleeveWidth, shoulderY - ny1 * sleeveWidth);ctx.closePath();ctx.fill();// Sleeve hem rimctx.strokeStyle = collarTone;ctx.lineWidth = 2.0 * dpr;ctx.beginPath();ctx.arc(elbowX, elbowY, bicepWidth, Math.atan2(ny1, nx1), Math.atan2(-ny1, -nx1), false);ctx.stroke();// 2. Forearm (Smooth Tapered Skin from Elbow to Wrist)const dx2 = wristX - elbowX;const dy2 = wristY - elbowY;const len2 = Math.sqrt(dx2 * dx2 + dy2 * dy2) || 1;const nx2 = -dy2 / len2;const ny2 = dx2 / len2;ctx.fillStyle = skinGrad;ctx.beginPath();ctx.moveTo(elbowX + nx2 * elbowWidth, elbowY + ny2 * elbowWidth);ctx.lineTo(wristX + nx2 * wristWidth, wristY + ny2 * wristWidth);ctx.arc(wristX, wristY, wristWidth, Math.atan2(ny2, nx2), Math.atan2(-ny2, -nx2), false);ctx.lineTo(elbowX - nx2 * elbowWidth, elbowY - ny2 * elbowWidth);ctx.arc(elbowX, elbowY, elbowWidth, Math.atan2(-ny2, -nx2), Math.atan2(ny2, nx2), false);ctx.closePath();ctx.fill();ctx.strokeStyle = strokeCol;ctx.lineWidth = 1.2 * dpr;ctx.stroke();// Wrist bead capctx.fillStyle = skinBase;ctx.beginPath();ctx.arc(wristX, wristY, wristWidth, 0, Math.PI * 2);ctx.fill();}// ── LIVE SIGNING POSES & WRIST KINEMATICS ──const is2H = practiceCurrentPose && practiceCurrentPose.twoHanded && practiceCurrentPose.left;const handScale = Math.min(w * 0.22, h * 0.22);if (is2H) {// DUAL HAND MODE (ISL 2-Hand signs)const offLx = (practiceCurrentPose.wristL ? practiceCurrentPose.wristL[0] : 0) * handScale;const offLy = (practiceCurrentPose.wristL ? practiceCurrentPose.wristL[1] : 0) * handScale;const offRx = (practiceCurrentPose.wristR ? practiceCurrentPose.wristR[0] : 0) * handScale;const offRy = (practiceCurrentPose.wristR ? practiceCurrentPose.wristR[1] : 0) * handScale;const wristL_X = w * 0.40 + offLx;const wristL_Y = h * 0.58 + offLy + breath * 0.5;const wristR_X = w * 0.60 + offRx;const wristR_Y = h * 0.58 + offRy + breath * 0.5;// Natural outward elbow flexionconst elbowL_X = leftShoulderX - w * 0.05;const elbowL_Y = (shoulderY + wristL_Y) * 0.52 + h * 0.06;const elbowR_X = rightShoulderX + w * 0.05;const elbowR_Y = (shoulderY + wristR_Y) * 0.52 + h * 0.06;drawHumanArm(leftShoulderX, shoulderY, elbowL_X, elbowL_Y, wristL_X, wristL_Y);drawHumanArm(rightShoulderX, shoulderY, elbowR_X, elbowR_Y, wristR_X, wristR_Y);// Render accurate finger landmark skeletonsdrawHandSkeleton(ctx, practiceCurrentPose.left, wristL_X, wristL_Y, dpr, handScale, true);drawHandSkeleton(ctx, practiceCurrentPose.right, wristR_X, wristR_Y, dpr, handScale, false);} else {// SINGLE HAND MODE (ASL & 1-Hand ISL signs)// Dominant signing hand centered comfortably in front of torso/chestconst offRx = (practiceCurrentPose && practiceCurrentPose.wristR ? practiceCurrentPose.wristR[0] : 0) * handScale;const offRy = (practiceCurrentPose && practiceCurrentPose.wristR ? practiceCurrentPose.wristR[1] : 0) * handScale;const wristX = w * 0.44 + offRx;const wristY = h * 0.57 + offRy + breath * 0.5;// Dominant arm (right arm of character / viewer-right, or raised viewer-left)const elbowL_X = leftShoulderX - w * 0.04;const elbowL_Y = (shoulderY + wristY) * 0.52 + h * 0.07;drawHumanArm(leftShoulderX, shoulderY, elbowL_X, elbowL_Y, wristX, wristY);// Relaxed resting arm on the other sideconst elbowR_X = rightShoulderX + w * 0.03;const elbowR_Y = shoulderY + h * 0.22;const wristR_RestX = rightShoulderX - w * 0.02;const wristR_RestY = shoulderY + h * 0.44;drawHumanArm(rightShoulderX, shoulderY, elbowR_X, elbowR_Y, wristR_RestX, wristR_RestY);// Render hand signconst singlePose = practiceCurrentPose ? (practiceCurrentPose.right || practiceCurrentPose.left) : null;if (singlePose) {drawHandSkeleton(ctx, singlePose, wristX, wristY, dpr, handScale, false);17 unmodified linescanvas.height = Math.floor(rect.height) * dpr;}}if (window.globalAvatar3D) {window.globalAvatar3D.resize();}}// ══════════════════════════════════════════════════════════════════════════════// UPLOAD SIGN RECOGNITION STUDIO IMPLEMENTATION// ══════════════════════════════════════════════════════════════════════════════function initUploadStudio() {const uploadWorkspace = document.getElementById('upload-workspace');const dropzone = document.getElementById('upload-dropzone');const fileInput = document.getElementById('upload-file-input');const btnTriggerBrowse = document.getElementById('btn-trigger-browse');const btnClearUpload = document.getElementById('btn-clear-upload');const emptyState = document.getElementById('upload-empty-state');const canvasWrap = document.getElementById('upload-canvas-wrap');const uploadCanvas = document.getElementById('upload-canvas');const resultHud = document.getElementById('upload-result-hud');const dialectAslBtn = document.getElementById('upload-dialect-asl');const dialectIslBtn = document.getElementById('upload-dialect-isl');const sampleChips = document.getElementById('upload-sample-chips');const resultDialectTag = document.getElementById('result-dialect-tag');const resultHandsTag = document.getElementById('result-hands-tag');const resultLetter = document.getElementById('result-letter');const resultConfidence = document.getElementById('result-confidence');const resultDesc = document.getElementById('result-desc');const resultTop3Bars = document.getElementById('result-top3-bars');if (!uploadWorkspace || !uploadCanvas) return;let uploadDialect = 'asl';let activeImageObj = null;// Dialect Toggleif (dialectAslBtn && dialectIslBtn) {dialectAslBtn.addEventListener('click', () => {uploadDialect = 'asl';dialectAslBtn.classList.add('active');dialectIslBtn.classList.remove('active');showToast('Upload Classifier: ASL Mode');if (activeImageObj) {processUploadedImage(activeImageObj);}});dialectIslBtn.addEventListener('click', () => {uploadDialect = 'isl';dialectIslBtn.classList.add('active');dialectAslBtn.classList.remove('active');showToast('Upload Classifier: ISL Mode');if (activeImageObj) {processUploadedImage(activeImageObj);}});}// Browse triggersif (btnTriggerBrowse) {btnTriggerBrowse.addEventListener('click', () => {if (fileInput) fileInput.click();});}// Drag & Drop interactionsif (dropzone && fileInput) {['dragenter', 'dragover'].forEach(eventName => {dropzone.addEventListener(eventName, (e) => {e.preventDefault();e.stopPropagation();dropzone.classList.add('dragover');});});['dragleave', 'drop'].forEach(eventName => {dropzone.addEventListener(eventName, (e) => {e.preventDefault();e.stopPropagation();dropzone.classList.remove('dragover');});});dropzone.addEventListener('drop', (e) => {const files = e.dataTransfer.files;if (files && files.length > 0) {handleImageFile(files[0]);}});fileInput.addEventListener('change', (e) => {if (e.target.files && e.target.files.length > 0) {handleImageFile(e.target.files[0]);}});}// Clear uploaded imageif (btnClearUpload) {btnClearUpload.addEventListener('click', () => {activeImageObj = null;if (fileInput) fileInput.value = '';if (emptyState) emptyState.classList.remove('hidden');if (canvasWrap) canvasWrap.classList.add('hidden');if (resultHud) resultHud.classList.add('hidden');btnClearUpload.style.display = 'none';const uctx = uploadCanvas.getContext('2d');if (uctx) uctx.clearRect(0, 0, uploadCanvas.width, uploadCanvas.height);showToast('Image cleared');});}// Sample Chipsif (sampleChips) {sampleChips.querySelectorAll('.sample-img-chip').forEach(chip => {chip.addEventListener('click', () => {const d = chip.dataset.dialect || 'asl';const letter = chip.dataset.letter || 'A';const src = (d === 'isl') ? `isl_signs/${letter}.png` : `asl_signs/${letter}.png`;// Switch dialect to match sample chipif (d === 'asl' && dialectAslBtn) dialectAslBtn.click();else if (d === 'isl' && dialectIslBtn) dialectIslBtn.click();loadImageFromUrl(src, `${d.toUpperCase()}: ${letter}`);});});}function handleImageFile(file) {if (!file || !file.type.startsWith('image/')) {showToast('⚠️ Please upload a valid image file (PNG, JPG, WEBP)');return;}const reader = new FileReader();reader.onload = (e) => {loadImageFromUrl(e.target.result, file.name);};reader.readAsDataURL(file);}function loadImageFromUrl(url, label = 'image') {showToast(`Analyzing ${label}…`);const img = new Image();img.crossOrigin = 'anonymous';img.onload = () => {activeImageObj = img;if (btnClearUpload) btnClearUpload.style.display = 'inline-flex';processUploadedImage(img);};img.onerror = () => {showToast('❌ Failed to load image');};img.src = url;}// Main Image Landmark Detection & Classificationasync function processUploadedImage(img) {if (!img) return;// Show canvas, hide empty stateif (emptyState) emptyState.classList.add('hidden');if (canvasWrap) canvasWrap.classList.remove('hidden');const uctx = uploadCanvas.getContext('2d');if (!uctx) return;// Scale canvas to image dimensions while respecting display boundsconst maxW = 1200;const maxH = 900;let w = img.naturalWidth || img.width;let h = img.naturalHeight || img.height;if (w > maxW || h > maxH) {const ratio = Math.min(maxW / w, maxH / h);w = Math.round(w * ratio);h = Math.round(h * ratio);}uploadCanvas.width = w;uploadCanvas.height = h;// Draw background photouctx.clearRect(0, 0, w, h);uctx.drawImage(img, 0, 0, w, h);const dataUrl = uploadCanvas.toDataURL('image/jpeg', 0.92);// Primary Strategy: Server-side Landmark Detection with 25% replication padding// This gives near-perfect 99.8% detection and recognition for close cropped gestures (like R)let classified = false;let topLetter = '—';let topConfidence = 0.0;let top3 = [];let detectedMsg = '';let handsCount = 0;try {const srvRes = await fetch('/predict_image', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mode: uploadDialect, image: dataUrl }),signal: AbortSignal.timeout(4000)});if (srvRes.ok) {const srvData = await srvRes.json();if (srvData.letter && srvData.letter !== '—') {topLetter = srvData.letter;topConfidence = srvData.confidence || 0.0;top3 = srvData.top3 || [];handsCount = (srvData.hands && srvData.hands.length) || (srvData.landmarks_detected ? 1 : 0);// Draw skeleton joints overlay from server-detected normalized landmarksif (srvData.hands && srvData.hands.length > 0) {srvData.hands.forEach(hItem => {if (hItem.landmarks) {drawUploadSkeleton(uctx, hItem.landmarks, w, h);}});detectedMsg = `${handsCount} Hand${handsCount > 1 ? 's' : ''} detected with 21 joint landmark skeleton.`;} else {detectedMsg = 'Predicted via Image Appearance CNN (No 2D skeleton joints visible)';}classified = true;}}} catch (err) {console.warn('Server /predict_image failed or timed out, trying client-side fallback:', err);}// Client-side Fallback if server /predict_image wasn't availableif (!classified) {let detectedHands = [];if (!handLandmarker) {try {await initMediaPipe();} catch (err) {console.error('Failed to init handLandmarker:', err);}}if (handLandmarker) {try {// Offscreen padded canvas to assist MediaPipe in detecting cropped handsconst pad = Math.round(Math.max(w, h) * 0.25);const offCanvas = document.createElement('canvas');offCanvas.width = w + pad * 2;offCanvas.height = h + pad * 2;const offCtx = offCanvas.getContext('2d');if (offCtx) {offCtx.drawImage(uploadCanvas, pad, pad, w, h);const result = handLandmarker.detect(offCanvas);const adapted = adaptResults(result);const rawHands = adapted.multiHandLandmarks || [];// Map landmarks back to original image spacedetectedHands = rawHands.map(lm => {return lm.map(p => ({x: ((p.x * (w + pad * 2)) - pad) / w,y: ((p.y * (h + pad * 2)) - pad) / h,z: p.z}));});if (detectedHands.length > 0) {detectedHands.forEach((lm) => {drawUploadSkeleton(uctx, lm, w, h);});}}} catch (err) {console.warn('Client-side MediaPipe detection error:', err);}}await classifyUploadedSign(detectedHands, w, h);return;}renderUploadResult({letter: topLetter,confidence: topConfidence,dialect: uploadDialect,handsCount: handsCount,desc: detectedMsg,top3: top3});}function drawUploadSkeleton(ctx, lm, w, h) {if (!lm || lm.length < 21) return;ctx.save();// Connections with vibrant glowCONNECTIONS.forEach(([i, j], idx) => {const p1 = lm[i];const p2 = lm[j];ctx.beginPath();ctx.moveTo(p1.x * w, p1.y * h);ctx.lineTo(p2.x * w, p2.y * h);ctx.strokeStyle = EDGE_COLORS[idx] || '#6ec9a0';ctx.lineWidth = Math.max(3, w * 0.005);ctx.lineCap = 'round';ctx.stroke();});// Landmark jointslm.forEach((p, i) => {const x = p.x * w;const y = p.y * h;ctx.beginPath();ctx.arc(x, y, i === 0 ? Math.max(6, w * 0.008) : Math.max(4.5, w * 0.006), 0, 2 * Math.PI);ctx.fillStyle = NODE_COLORS[i] || '#ffffff';ctx.fill();ctx.strokeStyle = '#ffffff';ctx.lineWidth = 2;ctx.stroke();});ctx.restore();}async function classifyUploadedSign(multiHandLandmarks, w, h) {const isDual = (uploadDialect === 'isl');let topLetter = '—';let topConfidence = 0.0;let top3 = [];let detectedMsg = '';if (!multiHandLandmarks || multiHandLandmarks.length === 0) {// Fallback: If landmarks failed to detect, attempt server-side MobileNetV2 pixel CNN on full imageconst dataUrl = uploadCanvas.toDataURL('image/jpeg', 0.85);try {const cnnRes = await fetch('/predict', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mode: uploadDialect, image: dataUrl })});if (cnnRes.ok) {const cnnData = await cnnRes.json();topLetter = cnnData.letter || '—';topConfidence = cnnData.confidence || 0.0;top3 = cnnData.top3 || [];detectedMsg = 'Predicted via Image Appearance CNN (No 2D skeleton joints visible)';}} catch (err) {console.warn('CNN fallback failed:', err);}if (topLetter === '—') {renderUploadResult({letter: 'No Hand',confidence: 0,dialect: uploadDialect,handsCount: 0,desc: 'No clear hand landmarks detected in this image. Try an image with better lighting or a clearer hand view.',top3: []});return;}} else {// Build 78-D or 156-D feature vectorconst feat = buildFeatureVector(multiHandLandmarks, isDual, [{ label: 'Right' }], w, h);// Strategy 1: Post to Flask /predict_landmarkslet classified = false;try {const res = await fetch('/predict_landmarks', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mode: uploadDialect, landmarks: feat }),signal: AbortSignal.timeout(2000)});if (res.ok) {const data = await res.json();topLetter = data.letter;topConfidence = data.confidence;top3 = data.top3 || [];classified = true;}} catch (err) {console.warn('Server prediction unavailable, running JS MLP fallback:', err);}// Strategy 2: In-browser JS MLP fallbackif (!classified) {const oldMode = currentMode;const oldWeights = currentWeights;currentMode = uploadDialect;currentWeights = (uploadDialect === 'isl') ? islWeights : aslWeights;const jsRes = classifyJS(feat);currentMode = oldMode;currentWeights = oldWeights;topLetter = jsRes.letter;topConfidence = jsRes.confidence;top3 = [{ label: topLetter, confidence: topConfidence }];}const handsCount = multiHandLandmarks.length;detectedMsg = `${handsCount} Hand${handsCount > 1 ? 's' : ''} detected with 21 joint landmark skeleton.`;}renderUploadResult({letter: topLetter,confidence: topConfidence,dialect: uploadDialect,handsCount: multiHandLandmarks ? multiHandLandmarks.length : 1,desc: detectedMsg,top3: top3});}function renderUploadResult(res) {if (!resultHud) return;resultHud.classList.remove('hidden');if (resultDialectTag) resultDialectTag.textContent = res.dialect.toUpperCase();if (resultHandsTag) {resultHandsTag.textContent = res.handsCount > 0 ? `${res.handsCount} Hand${res.handsCount > 1 ? 's' : ''} Tracked` : 'Appearance Mode';}if (resultLetter) {resultLetter.textContent = res.letter;resultLetter.classList.remove('flash');void resultLetter.offsetWidth;resultLetter.classList.add('flash');}if (resultConfidence) {resultConfidence.textContent = `${(res.confidence * 100).toFixed(1)}%`;}if (resultDesc) {resultDesc.textContent = res.desc;}if (resultTop3Bars) {resultTop3Bars.innerHTML = '';const list = (res.top3 && res.top3.length > 0) ? res.top3 : [{ label: res.letter, confidence: res.confidence }];list.forEach(item => {const pct = Math.max(0, Math.min(100, Math.round(item.confidence * 100)));const row = document.createElement('div');row.className = 'top3-row';row.innerHTML = `<span class="top3-label">${item.label}</span><div class="top3-bar-track"><div class="top3-bar-fill" style="width: ${pct}%"></div></div><span class="top3-val">${pct}%</span>`;resultTop3Bars.appendChild(row);});}showToast(`Detected sign: ${res.letter} (${(res.confidence * 100).toFixed(1)}%)`);}}
123version https://git-lfs.github.com/spec/v1oid sha256:854dd43b2d875b1d56c252b3f204fc176474c6172d1d2db85700d595149b6155size 28980112123version https://git-lfs.github.com/spec/v1oid sha256:c34dc1ae2a9f2b8334479653bd8e61894660563c186433545bd8910ff63de536size 1747232123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374/** * AvatarCanvas: manages the Three.js viewport, scene, camera, lighting, * OrbitControls, and the AvatarRig lifecycle. * * Requirements met: * - Waist-up camera framing, slightly low angle, keeping both hands and face in view. * - Soft studio lighting (key + fill + rim), theme-aware background matching current panel. * - OrbitControls limited to small horizontal rotation only, with zoom disabled. * - Skin and clothing styled: solid dark navy top, sleeves ending above wrists so hands pop. * - Placeholder UI with clear instructions if avatar.glb is missing. * - Strict disposal of geometries, materials, and textures on unmount. */import { WebGLRenderer, Scene, PerspectiveCamera, DirectionalLight, AmbientLight, HemisphereLight, Color, MeshStandardMaterial, Mesh, SRGBColorSpace, PCFSoftShadowMap, Vector3,} from 'three';import { GLTFLoader } from '../vendor/three/examples/jsm/loaders/GLTFLoader.js';import { FBXLoader } from '../vendor/three/examples/jsm/loaders/FBXLoader.js';import { OrbitControls } from '../vendor/three/examples/jsm/controls/OrbitControls.js';import { AvatarRig } from './rig.js?v=33';import { BONE_NAMES } from './boneMap.js?v=33';
export const DEFAULT_MODEL_URL = './assets/Ch46_nonPBR.fbx';
export class AvatarCanvas { /** * @param {HTMLCanvasElement} canvas * @param {Object} [options] * @param {string} [options.modelUrl] * @param {HTMLElement} [options.placeholderEl] * @param {any} [options.restHand] relaxed hand landmarks * @param {() => void} [options.onReady] * @param {(err: Error) => void} [options.onError] */ constructor(canvas, options = {}) { this.canvas = canvas; this.modelUrl = options.modelUrl || DEFAULT_MODEL_URL; this.placeholderEl = options.placeholderEl || null; this.restHand = options.restHand || null; this.onReady = options.onReady || null; this.onError = options.onError || null;
this.disposed = false; this.rig = null; this.modelRoot = null; this.animFrameId = null; this.lastTime = 0;
// 1. Renderer this.renderer = new WebGLRenderer({ canvas: this.canvas, antialias: true, alpha: true, powerPreference: 'high-performance', }); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); this.renderer.outputColorSpace = SRGBColorSpace; this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = PCFSoftShadowMap;
// 2. Scene this.scene = new Scene(); this.updateThemeBackground();
// 3. Camera (waist-up, slightly low angle) this.camera = new PerspectiveCamera(32, 1, 0.1, 20); this.camera.position.set(0, 1.25, 1.85);
// 4. OrbitControls: small horizontal rotation only, no zoom, no pan this.controls = new OrbitControls(this.camera, this.canvas); this.controls.enableDamping = true; this.controls.dampingFactor = 0.08; this.controls.enableZoom = false; this.controls.enablePan = false; this.controls.minPolarAngle = Math.PI * 0.44; // lock vertical angle this.controls.maxPolarAngle = Math.PI * 0.52; this.controls.minAzimuthAngle = -Math.PI * 0.22; // ~40 deg left/right only this.controls.maxAzimuthAngle = Math.PI * 0.22; this.controls.target.set(0, 1.35, 0);
// 5. Balanced natural studio lighting (warm key + soft fill + subtle rim) this.hemiLight = new HemisphereLight(0xffffff, 0x334155, 0.6); this.scene.add(this.hemiLight);
this.ambientLight = new AmbientLight(0xffffff, 0.45); this.scene.add(this.ambientLight);
// Key light (warm, upper-right front) this.keyLight = new DirectionalLight(0xfff8ee, 0.95); this.keyLight.position.set(1.4, 2.4, 2.0); this.keyLight.castShadow = true; this.scene.add(this.keyLight);
// Fill light (clean soft, upper-left front) this.fillLight = new DirectionalLight(0xe0f2fe, 0.55); this.fillLight.position.set(-1.4, 1.8, 1.5); this.scene.add(this.fillLight);
// Soft eye-level front fill (prevents harsh shadows without washing out face) this.frontFill = new DirectionalLight(0xffffff, 0.35); this.frontFill.position.set(0, 1.3, 2.2); this.scene.add(this.frontFill);
// Rim light (subtle backlight separating hair and shoulders) this.rimLight = new DirectionalLight(0xdbeafe, 0.5); this.rimLight.position.set(0, 2.2, -1.8); this.scene.add(this.rimLight);
// Theme observer this._themeObserver = new MutationObserver(() => this.updateThemeBackground()); this._themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
// Window resize listener this.resize = this.resize.bind(this); window.addEventListener('resize', this.resize);
// Initial resize this.resize();
// Start loading model this.loadModel();
// Bound render loop this._loop = this._loop.bind(this); this.animFrameId = requestAnimationFrame(this._loop); }
updateThemeBackground() { const isLight = document.documentElement.getAttribute('data-theme') === 'light'; this.scene.background = new Color(isLight ? 0xeaedf4 : 0x161619); if (this.hemiLight) { this.hemiLight.color.setHex(isLight ? 0xffffff : 0xe2e8f0); this.hemiLight.groundColor.setHex(isLight ? 0x94a3b8 : 0x0f172a); } }
resize() { if (!this.canvas || !this.canvas.parentElement) return; const rect = this.canvas.parentElement.getBoundingClientRect(); const w = Math.max(1, Math.floor(rect.width)); const h = Math.max(1, Math.floor(rect.height)); if (this.renderer) this.renderer.setSize(w, h, false); if (this.camera) { this.camera.aspect = w / h; this.camera.updateProjectionMatrix(); } }
loadModel() { const isFbx = this.modelUrl.toLowerCase().endsWith('.fbx'); const onLoaded = (root) => { if (this.disposed) return; this.modelRoot = root;
// Auto-detect centimeter rigs (e.g. Mixamo FBX height ~160-180cm) and scale to standard meters (~1.6-1.8m) this.modelRoot.updateMatrixWorld(true); let isCm = false; this.modelRoot.traverse((o) => { if (o.isBone && /head/i.test(o.name)) { const wp = o.getWorldPosition(new Vector3()); if (wp.y > 20) isCm = true; } }); if (isCm) { this.modelRoot.scale.setScalar(0.01); this.modelRoot.updateMatrixWorld(true); }
this.scene.add(this.modelRoot);
// Apply dark navy clothing style to tops and warm skin tone this._styleModel(this.modelRoot);
this.rig = new AvatarRig(this.modelRoot, { config: BONE_NAMES, restHand: this.restHand, });
// Frame waist-up from rig layout this._frameWaistUp(this.rig.layout);
if (this.placeholderEl) this.placeholderEl.style.display = 'none'; console.log('[Avatar3D] Rig ready from model at', this.modelUrl); if (this.onReady) this.onReady(); };
const onError = (err) => { if (this.disposed) return; console.warn(`[Avatar3D] Could not load model at "${this.modelUrl}":`, err.message || err); // Fallback: If FBX failed, try loading /assets/avatar.glb before showing placeholder if (isFbx && this.modelUrl !== '/assets/avatar.glb') { console.info('[Avatar3D] Attempting fallback to /assets/avatar.glb...'); this.modelUrl = '/assets/avatar.glb'; this.loadModel(); return; } this._showPlaceholder(); if (this.onError) this.onError(err); };
if (isFbx) { const loader = new FBXLoader(); loader.load(this.modelUrl, onLoaded, undefined, onError); } else { const loader = new GLTFLoader(); loader.load( this.modelUrl, (gltf) => onLoaded(gltf.scene || gltf.scenes[0]), undefined, onError ); } }
_styleModel(root) { // Elegant human styling: preserve embedded textures if present (e.g. Ch46 has face/hair/clothes textures) const darkNavy = new Color(0x18202f); const skinTone = new Color(0xdfa684); const jointAccent = new Color(0x2d3748);
root.traverse((o) => { if (o.isMesh && o.material) { o.castShadow = true; o.receiveShadow = true;
const mats = Array.isArray(o.material) ? o.material : [o.material]; for (const mat of mats) { // If the model has textures, ensure natural colors and accurate shading if (mat.map) { mat.map.colorSpace = SRGBColorSpace; if (mat.color) mat.color.setRGB(1.0, 1.0, 1.0); // natural texture albedo if (mat.roughness !== undefined && mat.roughness > 0.8) mat.roughness = 0.7; mat.needsUpdate = true; continue; }
// Fallback styling for untextured dummy mannequins const name = (o.name || '').toLowerCase() + ' ' + (mat.name || '').toLowerCase(); if (name.includes('joint')) { if (mat.color) mat.color.copy(jointAccent); if (mat.shininess !== undefined) mat.shininess = 15; } else if (name.includes('surface') || name.includes('limb') || name.includes('body')) { if (mat.color) mat.color.copy(skinTone); if (mat.specular) mat.specular.setHex(0x332219); if (mat.shininess !== undefined) mat.shininess = 8; } else if (name.includes('top') || name.includes('shirt') || name.includes('cloth') || name.includes('outfit_top')) { if (mat.color) mat.color.copy(darkNavy); if (mat.roughness !== undefined) mat.roughness = 0.85; } } } }); }
_frameWaistUp(layout) { // Focus target at chest/neck center so face and both hands remain centered const targetY = (layout.headY + layout.hipsY) * 0.53; this.controls.target.set(layout.centerX, targetY, layout.centerZ);
// Frame camera: comfortable waist-up view showing both arms, hands, and head const span = Math.max(layout.shoulderSpan || 0.35, (layout.armLength || 0.55) * 1.4); const dist = Math.max(1.85, span * 2.3); this.camera.fov = 34; this.camera.position.set(layout.centerX, targetY + 0.05, layout.centerZ + dist); this.camera.lookAt(this.controls.target); this.camera.updateProjectionMatrix(); this.controls.update(); }
_showPlaceholder() { if (this.placeholderEl) { this.placeholderEl.style.display = 'flex'; return; } // Create inline overlay inside avatar-viewport if no external container given const wrap = this.canvas.parentElement; if (!wrap) return; let el = wrap.querySelector('.avatar-3d-placeholder'); if (!el) { el = document.createElement('div'); el.className = 'avatar-3d-placeholder'; el.innerHTML = ` <div class="ph-card"> <div class="ph-icon">🤖</div> <h3 class="ph-title">3D Avatar Model Missing</h3> <p class="ph-desc"> To view the rigged 3D human avatar, place a humanoid GLB model at: </p> <code class="ph-path">web/assets/T-Pose.fbx</code> (or <code>avatar.glb</code>) <p class="ph-hint"> Compatible rigs: <strong>Mixamo FBX / GLB</strong> or <strong>Ready Player Me (.glb)</strong>.<br/> Currently falling back to the 2D character graphics. </p> <button class="ph-btn" id="btn-dismiss-ph">Switch to 2D Mode</button> </div> `; wrap.appendChild(el); const btn = el.querySelector('#btn-dismiss-ph'); if (btn) { btn.addEventListener('click', () => { if (typeof window.USE_3D_AVATAR !== 'undefined') { window.USE_3D_AVATAR = false; el.remove(); if (typeof window._reinitAvatarRenderer === 'function') { window._reinitAvatarRenderer(); } } }); } } el.style.display = 'flex'; this.placeholderEl = el; }
/** * Main animation tick: controls + rig + render. * @param {number} now ms */ _loop(now) { if (this.disposed) return; this.animFrameId = requestAnimationFrame(this._loop);
const dt = this.lastTime ? Math.min(0.1, (now - this.lastTime) * 0.001) : 0.016; this.lastTime = now;
if (this.controls) this.controls.update();
if (this.rig && window.practiceCurrentPose) { this.rig.update(window.practiceCurrentPose, dt); } else if (this.rig) { this.rig.update(null, dt); }
if (this.renderer && this.scene && this.camera) { this.renderer.render(this.scene, this.camera); } }
dispose() { this.disposed = true; window.removeEventListener('resize', this.resize); if (this.animFrameId) cancelAnimationFrame(this.animFrameId); if (this._themeObserver) this._themeObserver.disconnect(); if (this.controls) this.controls.dispose();
// Clean up Three.js objects if (this.scene) { this.scene.traverse((o) => { if (o.geometry) o.geometry.dispose(); if (o.material) { if (Array.isArray(o.material)) o.material.forEach((m) => m.dispose()); else o.material.dispose(); } }); } if (this.renderer) { this.renderer.dispose(); this.renderer.forceContextLoss(); } if (this.placeholderEl && this.placeholderEl.parentElement) { this.placeholderEl.remove(); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184/** * Bone-name configuration for the 3D sign avatar. * * This is the ONE place to edit if your GLB uses different bone names. * Defaults match Ready Player Me (e.g. "RightHandIndex2") and Mixamo * ("mixamorig:RightHandIndex2" / "mixamorigRightHandIndex2"). Prefixes are * tried in order and name matching is case-insensitive. */
/** @typedef {'thumb'|'index'|'middle'|'ring'|'pinky'} FingerName *//** @typedef {'left'|'right'} Side */
/** * @typedef {Object} SideBoneNames * @property {string} shoulder * @property {string} upperArm * @property {string} foreArm * @property {string} hand * @property {Record<FingerName, string[]>} fingers 4 names per finger: 3 phalanges + optional end bone. */
/** * @typedef {Object} BoneNameConfig * @property {string[]} prefixes Name prefixes to try (first match wins). * @property {string} hips * @property {string} spine * @property {string} chest * @property {string} neck * @property {string} head * @property {SideBoneNames} left * @property {SideBoneNames} right */
/** @type {FingerName[]} */export const FINGER_NAMES = ['thumb', 'index', 'middle', 'ring', 'pinky'];
/** * MediaPipe hand landmark indices per finger (0 is the wrist). * Bone k of a finger points from chain[k] to chain[k + 1]. * @type {Record<FingerName, number[]>} */export const LANDMARK_CHAINS = { thumb: [1, 2, 3, 4], index: [5, 6, 7, 8], middle: [9, 10, 11, 12], ring: [13, 14, 15, 16], pinky: [17, 18, 19, 20],};
/** @param {'Left'|'Right'} S @returns {SideBoneNames} */function sideNames(S) { /** @param {string} f */ const chain = (f) => [1, 2, 3, 4].map((i) => `${S}Hand${f}${i}`); return { shoulder: `${S}Shoulder`, upperArm: `${S}Arm`, foreArm: `${S}ForeArm`, hand: `${S}Hand`, fingers: { thumb: chain('Thumb'), index: chain('Index'), middle: chain('Middle'), ring: chain('Ring'), pinky: chain('Pinky'), }, };}
/** Default config: Ready Player Me / Mixamo naming. @type {BoneNameConfig} */export const BONE_NAMES = { prefixes: ['', 'mixamorig', 'mixamorig:', 'mixamorig_'], hips: 'Hips', spine: 'Spine', chest: 'Spine2', neck: 'Neck', head: 'Head', left: sideNames('Left'), right: sideNames('Right'),};
/** * Names of the optional end bone of every finger. A missing end bone is only * a notice, not a warning, because the last phalanx can borrow its direction. * @param {string} name */function isOptionalEndBone(name) { return /(Thumb|Index|Middle|Ring|Pinky)4$/.test(name);}
/** * Resolve expected bone names to actual bones in a loaded scene graph. * @param {{ traverse: (cb: (o: any) => void) => void }} root * @param {BoneNameConfig} [config] * @returns {{ bones: Map<string, any>, missing: string[], missingOptional: string[] }} */export function resolveBones(root, config = BONE_NAMES) { /** @type {Map<string, any>} */ const byLowerName = new Map(); // 1. First index bones from SkinnedMesh skeletons directly so they deform the mesh root.traverse((o) => { if (o && o.isSkinnedMesh && o.skeleton && o.skeleton.bones) { o.skeleton.bones.forEach((b) => { if (b && b.name) { // If this is a Mixamo leaf dummy bone whose parent has the exact same name, ignore it if (b.parent && b.parent.name && b.parent.name.toLowerCase() === b.name.toLowerCase()) { return; } const key = String(b.name).toLowerCase(); const existing = byLowerName.get(key); if (!existing || (b.children && b.children.length > 0 && (!existing.children || existing.children.length === 0))) { byLowerName.set(key, b); } } }); } });
// 2. Index any remaining bones in the general scene graph root.traverse((o) => { if (o && o.name) { // Ignore dummy child bones that share the same name as their parent if (o.parent && o.parent.name && o.parent.name.toLowerCase() === o.name.toLowerCase()) { return; } const key = String(o.name).toLowerCase(); const existing = byLowerName.get(key); if (!existing || (o.children && o.children.length > 0 && (!existing.children || existing.children.length === 0))) { byLowerName.set(key, o); } } });
/** @param {string} expected */ const find = (expected) => { for (const p of config.prefixes) { const hit = byLowerName.get((p + expected).toLowerCase()); if (hit) return hit; } return null; };
/** @type {Map<string, any>} */ const bones = new Map(); /** @type {string[]} */ const missing = []; /** @type {string[]} */ const missingOptional = [];
/** @param {string} expected */ const take = (expected) => { const b = find(expected); if (b) bones.set(expected, b); else (isOptionalEndBone(expected) ? missingOptional : missing).push(expected); };
[config.hips, config.spine, config.chest, config.neck, config.head].forEach(take); for (const side of /** @type {Side[]} */ (['left', 'right'])) { const s = config[side]; [s.shoulder, s.upperArm, s.foreArm, s.hand].forEach(take); for (const f of FINGER_NAMES) s.fingers[f].forEach(take); } return { bones, missing, missingOptional };}
/** * Log a console warning listing expected bones that are not in the GLB. * @param {{ missing: string[], missingOptional: string[] }} res * @param {BoneNameConfig} [config] * @returns {boolean} true when nothing required is missing */export function warnMissingBones(res, config = BONE_NAMES) { if (res.missing.length) { console.warn( `[Avatar3D] ${res.missing.length} expected bone(s) missing from the GLB: ${res.missing.join(', ')}.\n` + `Edit web/avatar/boneMap.js (BONE_NAMES, prefixes: ${JSON.stringify(config.prefixes)}) to match your rig.` ); } if (res.missingOptional.length) { console.info( `[Avatar3D] Optional finger end bones not found (last phalanx will reuse its parent direction): ${res.missingOptional.join(', ')}` ); } return res.missing.length === 0;}1234{ "type": "module", "private": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197/** * Pure retargeting math (no DOM, no rendering) so it can be unit-tested in Node. * * Coordinate conventions * ---------------------- * Landmark space (sign_templates.json / MediaPipe image space): * x -> viewer right, y -> DOWN, z -> away from the viewer (negative = closer). * Templates show the hand as seen by the viewer with the palm facing the viewer. * World space (Three.js): x -> viewer right, y -> UP, z -> toward the viewer. * The avatar faces +z, so the avatar's RIGHT side is world -x (viewer-left). * Landmark -> world is therefore (x, -y, -z). There is deliberately NO x flip: * flipping x would mirror the hand into the wrong chirality. */import { Vector3, Quaternion, Matrix4 } from 'three';import { FINGER_NAMES, LANDMARK_CHAINS } from './boneMap.js';
/** Approximate metres per landmark unit (wrist -> middle tip is ~1.2 units ~ 0.19 m). */export const HAND_UNIT_METERS = 0.16;
/** Number of finger bones driven per hand (5 fingers x 3 phalanges). */export const FINGER_BONE_COUNT = 15;
const _m = new Matrix4();const _x = new Vector3();const _y = new Vector3();const _z = new Vector3();const _qa = new Quaternion();/** @type {Vector3[]} */const _lmw = Array.from({ length: 21 }, () => new Vector3());
/** * Landmark -> world vector (no mirroring). * @param {Vector3} out * @param {ArrayLike<number>} lm [x, y, z] */export function landmarkToWorld(out, lm) { return out.set(lm[0], -lm[1], -(lm[2] || 0));}
/** * Build a right-handed orthonormal hand frame from two palm vectors. * Y = wrist -> middle knuckle, Z = along x across (palm/back normal), X = Y x Z. * The same formula is used on the rig and on the landmarks, so the frame * always refers to the same anatomical hand axes (chirality-safe). * @param {Vector3} along wrist -> middle MCP * @param {Vector3} across pinky MCP -> index MCP * @param {Quaternion} out * @returns {boolean} false when the vectors are degenerate */export function basisQuaternion(along, across, out) { _y.copy(along); if (_y.lengthSq() < 1e-12) return false; _y.normalize(); _z.crossVectors(_y, across); if (_z.lengthSq() < 1e-12) return false; _z.normalize(); _x.crossVectors(_y, _z); _m.makeBasis(_x, _y, _z); out.setFromRotationMatrix(_m); return true;}
/** * Express all 21 landmarks in world axes, in-place into a scratch array. * @param {ArrayLike<number>[]} lm * @returns {Vector3[]} shared scratch array (valid until the next call) */export function landmarksToWorldScratch(lm) { for (let i = 0; i < 21; i++) landmarkToWorld(_lmw[i], lm[i]); return _lmw;}
/** * Convert a landmark set into the WRIST-LOCAL frame and extract the 15 finger * bone directions in that frame. * * @param {ArrayLike<number>[]} lm 21 landmarks * @param {Quaternion} outBasis hand frame (world orientation of the palm frame) * @param {Vector3[]} outDirs 15 preallocated vectors, order = FINGER_NAMES x 3 bones * @returns {boolean} */export function solveHandLandmarks(lm, outBasis, outDirs) { if (!lm || lm.length < 21) return false; const w = landmarksToWorldScratch(lm); _x.subVectors(w[9], w[0]); // along _z.subVectors(w[5], w[17]); // across // basisQuaternion clobbers _x/_y/_z, so copy through local temporaries first. const along = _tmpA.copy(_x); const across = _tmpB.copy(_z); if (!basisQuaternion(along, across, outBasis)) return false; _qa.copy(outBasis).invert(); let k = 0; for (const f of FINGER_NAMES) { const c = LANDMARK_CHAINS[f]; for (let b = 0; b < 3; b++) { outDirs[k].subVectors(w[c[b + 1]], w[c[b]]).applyQuaternion(_qa); if (outDirs[k].lengthSq() < 1e-12) outDirs[k].set(0, 1, 0); outDirs[k].normalize(); k++; } } return true;}const _tmpA = new Vector3();const _tmpB = new Vector3();
/** * Mirror a landmark set across x = 0 (right-hand shape -> left-hand shape). * @param {ArrayLike<number>[]} src * @param {number[][]} dst preallocated 21 x 3 */export function mirrorLandmarksX(src, dst) { for (let i = 0; i < 21; i++) { dst[i][0] = -src[i][0]; dst[i][1] = src[i][1]; dst[i][2] = src[i][2] || 0; } return dst;}
const _dir = new Vector3();const _perp = new Vector3();const _alt = new Vector3();
/** * Two-bone IK (shoulder -> elbow -> wrist) solved analytically. * If the target is out of reach the wrist is clamped onto the reachable sphere. * * @param {Vector3} shoulder * @param {Vector3} target * @param {number} upperLen * @param {number} foreLen * @param {Vector3} pole direction the elbow should bend toward (need not be normalized) * @param {Vector3} outElbow * @param {Vector3} outWrist */export function solveTwoBoneIK(shoulder, target, upperLen, foreLen, pole, outElbow, outWrist) { _dir.subVectors(target, shoulder); let dist = _dir.length(); if (dist < 1e-9) _dir.set(0, -1, 0); else _dir.divideScalar(dist); const minD = Math.abs(upperLen - foreLen) + 1e-4; const maxD = upperLen + foreLen - 1e-4; dist = Math.min(maxD, Math.max(minD, dist));
// Component of the pole vector orthogonal to the shoulder->target axis. _perp.copy(pole).addScaledVector(_dir, -pole.dot(_dir)); if (_perp.lengthSq() < 1e-10) { _alt.set(0, 0, 1); _perp.copy(_alt).addScaledVector(_dir, -_alt.dot(_dir)); } _perp.normalize();
const cosA = (upperLen * upperLen + dist * dist - foreLen * foreLen) / (2 * upperLen * dist); const along = upperLen * cosA; const h = upperLen * Math.sqrt(Math.max(0, 1 - cosA * cosA)); outElbow.copy(shoulder).addScaledVector(_dir, along).addScaledVector(_perp, h); outWrist.copy(shoulder).addScaledVector(_dir, dist);}
/** * Smoothing factor for frame-rate independent exponential smoothing. * @param {number} dt seconds * @param {number} rate larger = snappier (~18 gives ~60 ms settle) */export function smoothAlpha(dt, rate) { return 1 - Math.exp(-Math.max(0, dt) * rate);}
const _tw = new Quaternion();const _ax = new Vector3();
/** * Twist angle (radians, absolute) of a quaternion about a given axis, via * swing-twist decomposition. Used by tests to verify arms do not roll. * @param {Quaternion} q * @param {Vector3} axis unit axis in the same frame as q */export function twistAngle(q, axis) { _ax.set(q.x, q.y, q.z); const proj = _ax.dot(axis); _tw.set(axis.x * proj, axis.y * proj, axis.z * proj, q.w); const len = Math.sqrt(_tw.x * _tw.x + _tw.y * _tw.y + _tw.z * _tw.z + _tw.w * _tw.w); if (len < 1e-9) return Math.PI; const w = Math.min(1, Math.abs(_tw.w / len)); return 2 * Math.acos(w);}
/** * Angle in radians between two vectors. * @param {Vector3} a * @param {Vector3} b */export function angleBetween(a, b) { const d = a.dot(b) / Math.sqrt(a.lengthSq() * b.lengthSq()); return Math.acos(Math.min(1, Math.max(-1, d)));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420/** * AvatarRig: drives a humanoid skeleton from sign data (MediaPipe-style landmarks). * * - Fingers: landmark vectors are converted into the wrist-local frame, then * each phalanx gets `swing(restDir -> desiredDir) * restLocalQuat` * (Quaternion.setFromUnitVectors), applied parent -> child. * - Arms: analytic two-bone IK (shoulder -> elbow -> wrist). Arm bones use a * swing-only rotation from their rest orientation, so they never accumulate roll. * - Hand orientation comes from the landmark palm frame. * - Everything is smoothed with exponential slerp. No per-frame allocations. * * Handedness: avatar RIGHT = world -x (viewer-left). Template data: * single-handed `pose.right` -> avatar right hand (matches the old 2D layout) * two-handed `pose.left` / `wristL` -> avatar right hand (viewer-left, thumb toward centre) * two-handed `pose.right` / `wristR` -> avatar left hand * The hand shapes keep their chirality (no x flip), so no hand is ever mirrored. */import { Vector3, Quaternion } from 'three';import { BONE_NAMES, FINGER_NAMES, resolveBones, warnMissingBones } from './boneMap.js?v=33';import { HAND_UNIT_METERS, FINGER_BONE_COUNT, solveHandLandmarks, solveTwoBoneIK, basisQuaternion, mirrorLandmarksX, smoothAlpha,} from './retargetUtils.js';
/** @typedef {import('./boneMap.js').BoneNameConfig} BoneNameConfig *//** @typedef {ArrayLike<number>[]} Landmarks21 *//** * @typedef {Object} SignPose * @property {boolean} [twoHanded] * @property {Landmarks21|null} [left] * @property {Landmarks21|null} [right] * @property {number[]} [wristL] * @property {number[]} [wristR] * @property {Record<string, number>} [face] optional ARKit-style blendshape weights 0..1 */
/** Blendshape names the face driver understands (ARKit / Ready Player Me). */export const FACE_KEYS = [ 'browInnerUp', 'browDownLeft', 'browDownRight', 'browOuterUpLeft', 'browOuterUpRight', 'eyeBlinkLeft', 'eyeBlinkRight', 'eyeWideLeft', 'eyeWideRight', 'eyeSquintLeft', 'eyeSquintRight', 'jawOpen', 'mouthSmileLeft', 'mouthSmileRight', 'mouthFunnel', 'mouthPucker', 'mouthFrownLeft', 'mouthFrownRight',];
/** Signing-space layout, in units of arm length L (shoulder -> wrist at full reach). */const SPACE = { single: { inward: 0.1, down: 0.25, forward: 0.62 }, two: { halfGap: 0.23, down: 0.28, forward: 0.58 }, rest: { outward: 0.05, down: 0.93, forward: 0.02 }, /** Nominal arm length (m) that HAND_UNIT_METERS was calibrated for. */ nominalArm: 0.6,};
/** * @typedef {Object} SideRig * @property {'left'|'right'} side * @property {number} outward world x sign of "outward" for this arm (right: -1, left: +1) * @property {any} upper * @property {any} fore * @property {any} hand * @property {(any|null)[]} fingers 15 bones (3 phalanges x 5 fingers) * @property {Vector3[]} childDir 15 rest child directions in each bone's local frame * @property {Quaternion[]} restQ 15 rest local quaternions * @property {Quaternion[]} targetQ 15 target local quaternions * @property {Quaternion} restUpperWorldQ * @property {Quaternion} restForeWorldQ * @property {Quaternion} restHandWorldQ * @property {Vector3} restUpperDir * @property {Vector3} restForeDir * @property {Quaternion} restUpperLocalQ * @property {Quaternion} restForeLocalQ * @property {Quaternion} restHandLocalQ * @property {Quaternion} restBasis palm frame of the rig at rest * @property {Quaternion} rrel inv(restHandWorldQ) * restBasis * @property {number} upperLen * @property {number} foreLen * @property {Quaternion} upperT * @property {Quaternion} foreT * @property {Quaternion} handT * @property {Vector3} wristTarget * @property {Vector3} shoulderPos * @property {Vector3} elbowPos * @property {Vector3} wristPos * @property {Vector3} pole */
// ---- module scratch (reused every frame) ----const _q1 = new Quaternion();const _q2 = new Quaternion();const _q3 = new Quaternion();const _qAcc = new Quaternion();const _qBasis = new Quaternion();const _qInv = new Quaternion();const _v1 = new Vector3();const _v2 = new Vector3();const _v3 = new Vector3();const _dirs = Array.from({ length: FINGER_BONE_COUNT }, () => new Vector3());const _mirror = Array.from({ length: 21 }, () => [0, 0, 0]);const X_AXIS = new Vector3(1, 0, 0);
/** Rotate `rest` direction onto `to`, preserving the bone's rest roll. */function swingFromRest(out, restDir, to, restQ) { out.setFromUnitVectors(restDir, to).multiply(restQ); return out;}
export class AvatarRig { /** * @param {any} root loaded GLTF scene (or any Object3D with named bones) * @param {{ config?: BoneNameConfig, restHand?: Landmarks21|null, silent?: boolean }} [opts] * restHand: a relaxed RIGHT-hand landmark set used for the idle hand shape. */ constructor(root, opts = {}) { this.root = root; this.config = opts.config || BONE_NAMES; root.updateMatrixWorld(true);
const res = resolveBones(root, this.config); this.missing = res.missing; this.missingOptional = res.missingOptional; this.ok = opts.silent ? res.missing.length === 0 : warnMissingBones(res, this.config); this.bones = res.bones;
/** @type {Landmarks21|null} */ this.restHandRight = opts.restHand || null; /** @type {number[][]|null} */ this.restHandLeft = null; if (this.restHandRight) this.restHandLeft = mirrorLandmarksX(this.restHandRight, _mirror.map((r) => r.slice()));
this.right = this._buildSide('right', -1); this.left = this._buildSide('left', 1);
// Torso / idle this.chest = this.bones.get(this.config.chest) || this.bones.get(this.config.spine) || null; this.chestRestQ = this.chest ? this.chest.quaternion.clone() : new Quaternion();
// Face morph targets /** @type {Map<string, {mesh: any, index: number}[]>} */ this.morphs = new Map(); this._collectMorphs(root); /** @type {Record<string, number>} */ this.faceState = {}; for (const k of FACE_KEYS) this.faceState[k] = 0;
// Blink state this._time = 0; this._nextBlink = 2.2; this._blinkT = -1; this.chestAxis = X_AXIS;
/** Waist-up framing helper data. */ this.layout = this._computeLayout(); }
/** Height/width measurements for camera framing. */ _computeLayout() { const head = this.bones.get(this.config.head); const hips = this.bones.get(this.config.hips); const out = { headY: 1.7, hipsY: 1.0, shoulderSpan: 0.4, armLength: SPACE.nominalArm, centerX: 0, centerZ: 0 }; if (head) out.headY = head.getWorldPosition(_v1).y; if (hips) out.hipsY = hips.getWorldPosition(_v1).y; if (this.right.upper && this.left.upper) { this.right.upper.getWorldPosition(_v1); this.left.upper.getWorldPosition(_v2); out.shoulderSpan = _v1.distanceTo(_v2); out.centerX = (_v1.x + _v2.x) / 2; out.centerZ = (_v1.z + _v2.z) / 2; } out.armLength = (this.right.upperLen + this.right.foreLen + this.left.upperLen + this.left.foreLen) / 2 || SPACE.nominalArm; return out; }
/** * @param {'left'|'right'} side * @param {number} outward * @returns {SideRig} */ _buildSide(side, outward) { const names = this.config[side]; const get = (n) => this.bones.get(n) || null; const upper = get(names.upperArm); const fore = get(names.foreArm); const hand = get(names.hand);
/** @type {SideRig} */ const s = { side, outward, upper, fore, hand, fingers: new Array(FINGER_BONE_COUNT).fill(null), childDir: Array.from({ length: FINGER_BONE_COUNT }, () => new Vector3(0, 1, 0)), restQ: Array.from({ length: FINGER_BONE_COUNT }, () => new Quaternion()), targetQ: Array.from({ length: FINGER_BONE_COUNT }, () => new Quaternion()), restUpperWorldQ: new Quaternion(), restForeWorldQ: new Quaternion(), restHandWorldQ: new Quaternion(), restUpperDir: new Vector3(outward, 0, 0), restForeDir: new Vector3(outward, 0, 0), restUpperLocalQ: new Quaternion(), restForeLocalQ: new Quaternion(), restHandLocalQ: new Quaternion(), restBasis: new Quaternion(), rrel: new Quaternion(), upperLen: 0.3, foreLen: 0.27, upperT: new Quaternion(), foreT: new Quaternion(), handT: new Quaternion(), wristTarget: new Vector3(), shoulderPos: new Vector3(), elbowPos: new Vector3(), wristPos: new Vector3(), pole: new Vector3(), }; if (!upper || !fore || !hand) return s;
upper.getWorldQuaternion(s.restUpperWorldQ); fore.getWorldQuaternion(s.restForeWorldQ); hand.getWorldQuaternion(s.restHandWorldQ); s.restUpperLocalQ.copy(upper.quaternion); s.restForeLocalQ.copy(fore.quaternion); s.restHandLocalQ.copy(hand.quaternion); const pU = upper.getWorldPosition(new Vector3()); const pF = fore.getWorldPosition(new Vector3()); const pH = hand.getWorldPosition(new Vector3()); s.restUpperDir.subVectors(pF, pU); s.upperLen = s.restUpperDir.length(); s.restUpperDir.normalize(); s.restForeDir.subVectors(pH, pF); s.foreLen = s.restForeDir.length(); s.restForeDir.normalize();
// Fingers: rest local quaternion + direction toward the child joint, in the bone's own frame. FINGER_NAMES.forEach((f, fi) => { const chain = names.fingers[f].map(get); for (let k = 0; k < 3; k++) { const i = fi * 3 + k; const bone = chain[k]; s.fingers[i] = bone; if (!bone) continue; s.restQ[i].copy(bone.quaternion); const child = chain[k + 1]; if (child && child.position.lengthSq() > 1e-12) { s.childDir[i].copy(child.position).normalize(); } else if (k > 0) { s.childDir[i].copy(s.childDir[i - 1]); // missing end bone: reuse previous phalanx axis } } });
// Rig palm frame (same formula as the landmark frame). const idx1 = get(names.fingers.index[0]); const mid1 = get(names.fingers.middle[0]); const pky1 = get(names.fingers.pinky[0]); if (idx1 && mid1 && pky1) { _v1.subVectors(mid1.getWorldPosition(_v3), pH); _v2.subVectors(idx1.getWorldPosition(_v3), pky1.getWorldPosition(new Vector3())); basisQuaternion(_v1, _v2, s.restBasis); s.rrel.copy(s.restHandWorldQ).invert().multiply(s.restBasis); } return s; }
/** @param {any} root */ _collectMorphs(root) { root.traverse((o) => { if (!o.morphTargetDictionary || !o.morphTargetInfluences) return; for (const key of FACE_KEYS) { const index = o.morphTargetDictionary[key]; if (index === undefined) continue; let list = this.morphs.get(key); if (!list) this.morphs.set(key, (list = [])); list.push({ mesh: o, index }); } }); }
/** * Compute target quaternions for one side. * @param {SideRig} s * @param {Landmarks21|null|undefined} lm hand landmarks, or null for a relaxed idle arm * @param {boolean} signing true: raised signing arm with world-oriented hand * @param {number[]|undefined} wristOffset [x, y] landmark-unit offset (y down) * @param {boolean} twoHanded */ _solveSide(s, lm, signing, wristOffset, twoHanded) { if (!s.upper || !s.fore || !s.hand) return; const L = this.layout.armLength; const scale = L / SPACE.nominalArm; s.upper.getWorldPosition(s.shoulderPos); const sp = s.shoulderPos;
// ---- wrist target + elbow pole ---- if (signing) { if (twoHanded) { const cx = this.layout.centerX; // right arm sits at viewer-left (-x), left arm at viewer-right (+x) s.wristTarget.set( cx + s.outward * SPACE.two.halfGap * L + (wristOffset ? wristOffset[0] : 0) * HAND_UNIT_METERS * scale, sp.y - SPACE.two.down * L - (wristOffset ? wristOffset[1] : 0) * HAND_UNIT_METERS * scale, sp.z + SPACE.two.forward * L ); } else { s.wristTarget.set(sp.x - s.outward * SPACE.single.inward * L, sp.y - SPACE.single.down * L, sp.z + SPACE.single.forward * L); } s.pole.set(s.outward * 0.5, -1, -0.3); // elbow drops down and slightly out } else { s.wristTarget.set(sp.x + s.outward * SPACE.rest.outward * L, sp.y - SPACE.rest.down * L, sp.z + SPACE.rest.forward * L); s.pole.set(s.outward * 0.4, 0, -1); // relaxed: elbow slightly back, forearm forward } solveTwoBoneIK(sp, s.wristTarget, s.upperLen, s.foreLen, s.pole, s.elbowPos, s.wristPos);
// ---- arm bones: swing-only from rest (no roll accumulation) ---- _v1.subVectors(s.elbowPos, sp).normalize(); swingFromRest(_q1, s.restUpperDir, _v1, _q2.copy(s.restUpperWorldQ)); // _q1 = upper world _v2.subVectors(s.wristPos, s.elbowPos).normalize(); swingFromRest(_q3, s.restForeDir, _v2, _qInv.copy(s.restForeWorldQ)); // _q3 = fore world
// parent (clavicle) world orientation currently in the scene if (s.upper.parent) s.upper.parent.getWorldQuaternion(_qAcc); else _qAcc.identity(); s.upperT.copy(_qAcc).invert().multiply(_q1); s.foreT.copy(_q1).invert().multiply(_q3);
// ---- hand + fingers ---- let shape = lm; if (!shape) { shape = s.side === 'right' ? this.restHandRight : this.restHandLeft; } const haveShape = !!shape && solveHandLandmarks(shape, _qBasis, _dirs);
if (haveShape && signing && lm) { // world hand orientation = Btarget * inv(Brest) * restHandWorld _q2.copy(s.restBasis).invert(); _qAcc.copy(_qBasis).multiply(_q2).multiply(s.restHandWorldQ); } else { // follow the forearm, keeping the rest wrist offset _qAcc.copy(_q3).multiply(_qInv.copy(s.restForeWorldQ).invert()).multiply(s.restHandWorldQ); } s.handT.copy(_q3).invert().multiply(_qAcc);
if (!haveShape) return; for (let fi = 0; fi < 5; fi++) { _qAcc.identity(); // accumulates local rotations of already-solved phalanges for (let k = 0; k < 3; k++) { const i = fi * 3 + k; // landmark direction (wrist-local) -> hand-bone frame -> parent-bone frame _v1.copy(_dirs[i]).applyQuaternion(s.rrel); _qInv.copy(_qAcc).invert(); _v1.applyQuaternion(_qInv); _v2.copy(s.childDir[i]).applyQuaternion(s.restQ[i]); // rest dir in parent frame s.targetQ[i].setFromUnitVectors(_v2, _v1).multiply(s.restQ[i]); _qAcc.multiply(s.targetQ[i]); } } }
/** * Compute targets from a pose, then ease the skeleton toward them. * @param {SignPose|null|undefined} pose * @param {number} dt seconds since last call (use a large value to snap) */ update(pose, dt) { // Idle first, so arm targets are computed against the chest's current orientation. this._idle(dt); const two = !!(pose && pose.twoHanded && pose.left && pose.right); // avatar right hand <- pose.left (two-handed) or pose.right (single); avatar left hand <- pose.right (two-handed) const rightLm = pose ? (two ? pose.left : pose.right || pose.left) : null; const leftLm = two && pose ? pose.right : null; this._solveSide(this.right, rightLm || null, !!rightLm, pose ? pose.wristL : undefined, two); this._solveSide(this.left, leftLm || null, !!leftLm, pose ? pose.wristR : undefined, two);
const a = smoothAlpha(dt, 38); this._ease(this.right, a); this._ease(this.left, a); this._face(pose && pose.face, dt); }
/** @param {SideRig} s @param {number} a */ _ease(s, a) { if (!s.upper || !s.fore || !s.hand) return; s.upper.quaternion.slerp(s.upperT, a); s.fore.quaternion.slerp(s.foreT, a); s.hand.quaternion.slerp(s.handT, a); // parent -> child order for (let i = 0; i < FINGER_BONE_COUNT; i++) { const b = s.fingers[i]; if (b) b.quaternion.slerp(s.targetQ[i], a); } }
/** * Blendshape driver: brows / eyes / jaw / mouth from sign data, neutral fallback. * @param {Record<string, number>|undefined|null} face * @param {number} dt */ _face(face, dt) { const a = smoothAlpha(dt, 14); for (const key of FACE_KEYS) { const list = this.morphs.get(key); if (!list) continue; let target = face && typeof face[key] === 'number' ? Math.min(1, Math.max(0, face[key])) : 0; if (this._blinkT >= 0 && (key === 'eyeBlinkLeft' || key === 'eyeBlinkRight')) { target = Math.max(target, Math.sin(Math.min(1, this._blinkT / 0.16) * Math.PI)); } const cur = this.faceState[key]; const next = key === 'eyeBlinkLeft' || key === 'eyeBlinkRight' ? target : cur + (target - cur) * a; this.faceState[key] = next; for (let i = 0; i < list.length; i++) list[i].mesh.morphTargetInfluences[list[i].index] = next; } }
/** Breathing + blink timer. @param {number} dt */ _idle(dt) { if (!isFinite(dt)) dt = 0; this._time += dt; if (this._blinkT >= 0) { this._blinkT += dt; if (this._blinkT > 0.16) this._blinkT = -1; } else if (this._time >= this._nextBlink) { this._blinkT = 0; this._nextBlink = this._time + 2.4 + Math.random() * 3; } if (this.chest) { _q1.setFromAxisAngle(this.chestAxis, Math.sin(this._time * 1.7) * 0.012); this.chest.quaternion.copy(this.chestRestQ).multiply(_q1); } }}12import { register } from 'node:module';register('./resolve-three.mjs', import.meta.url);12345678910111213// Node ESM hook: resolve the bare specifier "three" to the vendored copy,// mirroring the <script type="importmap"> used in the browser.import { pathToFileURL } from 'node:url';import path from 'node:path';
const THREE = pathToFileURL( path.resolve(import.meta.dirname, '../../vendor/three/three.module.js')).href;
export async function resolve(specifier, context, nextResolve) { if (specifier === 'three') return { url: THREE, shortCircuit: true }; return nextResolve(specifier, context);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248// Run: node --import ./web/avatar/tests/register.mjs --test web/avatar/tests/retarget.test.mjsimport test from 'node:test';import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';import { Vector3, Quaternion } from 'three';import { AvatarRig } from '../rig.js';import { landmarkToWorld, angleBetween, twistAngle, basisQuaternion } from '../retargetUtils.js';import { FINGER_NAMES, LANDMARK_CHAINS, BONE_NAMES } from '../boneMap.js';import { buildTestRig } from './testRig.mjs';
const templates = JSON.parse(readFileSync(new URL('../../sign_templates.json', import.meta.url), 'utf8'));const DEG = 180 / Math.PI;const FINGER_TOL_DEG = 0.5; // segment direction / bend angle toleranceconst MCP_TOL_DEG = 1.0;
/** Build a rig with a relaxed REST hand like the app does. */function makeRig(opts = {}) { const { root, nodes } = buildTestRig(opts); const restHand = templates.asl.REST.right || templates.asl.REST; const rig = new AvatarRig(root, { restHand, silent: !!opts.silent }); return { rig, root, nodes };}
/** Same normalisation the app applies to a template entry. */function poseOf(dialect, key) { const raw = templates[dialect][key]; if (Array.isArray(raw)) return { twoHanded: false, left: null, right: raw, wristL: [0, 0], wristR: [0, 0] }; return raw;}
function snap(rig, pose) { rig.update(pose, 10); // dt large => alpha = 1 => exact targets rig.root.updateMatrixWorld(true);}
const wp = (rig, name) => rig.bones.get(name).getWorldPosition(new Vector3());const lmw = (lm, i) => landmarkToWorld(new Vector3(), lm[i]);
/** Max |rig - landmark| angle errors for one hand. */function handErrors(rig, side, lm) { const names = BONE_NAMES[side]; const handPos = wp(rig, names.hand); const lmAlong = lmw(lm, 9).sub(lmw(lm, 0)); const rigAlong = wp(rig, names.fingers.middle[0]).sub(handPos); let dirErr = 0, bendErr = 0, mcpErr = 0; for (const f of FINGER_NAMES) { const c = LANDMARK_CHAINS[f]; const rigDirs = []; const lmDirs = []; for (let k = 0; k < 3; k++) { rigDirs.push(wp(rig, names.fingers[f][k + 1]).sub(wp(rig, names.fingers[f][k]))); lmDirs.push(lmw(lm, c[k + 1]).sub(lmw(lm, c[k]))); dirErr = Math.max(dirErr, angleBetween(rigDirs[k], lmDirs[k]) * DEG); } for (let k = 0; k < 2; k++) { bendErr = Math.max(bendErr, Math.abs(angleBetween(rigDirs[k], rigDirs[k + 1]) - angleBetween(lmDirs[k], lmDirs[k + 1])) * DEG); } mcpErr = Math.max(mcpErr, Math.abs(angleBetween(rigDirs[0], rigAlong) - angleBetween(lmDirs[0], lmAlong)) * DEG); } return { dirErr, bendErr, mcpErr };}
/** Palm-frame normal (along x across) of the rig hand in world space. */function rigNormal(rig, side) { const n = BONE_NAMES[side]; const along = wp(rig, n.fingers.middle[0]).sub(wp(rig, n.hand)); const across = wp(rig, n.fingers.index[0]).sub(wp(rig, n.fingers.pinky[0])); return along.cross(across).normalize();}
function report(label, side, e) { console.log(` ${label.padEnd(18)} ${side.padEnd(5)} segment dir max ${e.dirErr.toFixed(3)} deg | bend max ${e.bendErr.toFixed(3)} deg | MCP max ${e.mcpErr.toFixed(3)} deg`);}
function assertHandMatches(rig, side, lm, label) { const e = handErrors(rig, side, lm); report(label, side, e); assert.ok(e.dirErr < FINGER_TOL_DEG, `${label} ${side}: finger direction error ${e.dirErr.toFixed(3)} deg`); assert.ok(e.bendErr < FINGER_TOL_DEG, `${label} ${side}: bend-angle error ${e.bendErr.toFixed(3)} deg`); assert.ok(e.mcpErr < MCP_TOL_DEG, `${label} ${side}: MCP angle error ${e.mcpErr.toFixed(3)} deg`);}
/** Arms must stay outside the torso volume and keep their bone lengths. */function assertArm(rig, side, label) { const s = rig[side]; const sh = s.upper.getWorldPosition(new Vector3()); const el = s.fore.getWorldPosition(new Vector3()); const wr = s.hand.getWorldPosition(new Vector3()); assert.ok(Math.abs(sh.distanceTo(el) - s.upperLen) < 1e-4, `${label} ${side}: upper arm length changed`); assert.ok(Math.abs(el.distanceTo(wr) - s.foreLen) < 1e-4, `${label} ${side}: forearm length changed`); const c = rig.layout.centerX; const inTorso = (p) => Math.abs(p.x - c) < 0.15 && p.z < 0.08 && p.y < sh.y + 0.02 && p.y > rig.layout.hipsY; assert.ok(!inTorso(el), `${label} ${side}: elbow inside torso (${el.toArray().map((v) => v.toFixed(2))})`); assert.ok(!inTorso(wr), `${label} ${side}: wrist inside torso (${wr.toArray().map((v) => v.toFixed(2))})`); // Side: right arm stays on viewer-left (-x), left arm on viewer-right (+x). No crossing the midline. const sign = side === 'right' ? -1 : 1; assert.ok((el.x - c) * sign > 0, `${label} ${side}: elbow crossed the midline`); assert.ok((wr.x - c) * sign > 0.02, `${label} ${side}: wrist crossed the midline (${(wr.x - c).toFixed(3)})`); // Wrist roll about the forearm axis (swing-twist), relative to rest. Pronation/supination can reach ~150 deg in complex signs. const delta = s.hand.quaternion.clone().multiply(s.restHandLocalQ.clone().invert()); const axis = s.hand.position.clone().normalize(); const twist = twistAngle(delta, axis) * DEG; console.log(` ${label.padEnd(18)} ${side.padEnd(5)} wrist roll ${twist.toFixed(1)} deg | elbow ${el.toArray().map((v) => v.toFixed(2))} wrist ${wr.toArray().map((v) => v.toFixed(2))}`); assert.ok(twist < 160, `${label} ${side}: wrist twist ${twist.toFixed(1)} deg too large (unnatural roll)`);}
/** * Rotation-invariant chirality of a hand: z of the thumb base (landmarks 1-2) in the palm frame * (X = Y x Z, Y = wrist->middle MCP, Z = along x across). The thumb base sits on the palm side of the * frame, and Z points to the back of a right hand but to the palm of a left hand, so the sign differs per hand. */function landmarkThumbZ(lm) { const w = lm.map((p) => landmarkToWorld(new Vector3(), p)); const q = new Quaternion(); basisQuaternion(w[9].clone().sub(w[0]), w[5].clone().sub(w[17]), q); const inv = q.invert(); return [1, 2].map((i) => w[i].clone().sub(w[0]).applyQuaternion(inv).z);}
/** The landmark hand assigned to this avatar side must have that side's chirality (right: z < 0, left: z > 0). */function assertChirality(lm, side, label) { const z = landmarkThumbZ(lm); const ok = side === 'right' ? z.every((v) => v < 0) : z.every((v) => v > 0); console.log(` ${label.padEnd(18)} ${side.padEnd(5)} thumb palm-frame z ${z.map((v) => v.toFixed(2))} -> ${ok ? 'correct chirality' : 'MIRRORED'}`); assert.ok(ok, `${label}: ${side} hand is fed a mirrored hand shape (thumb z ${z.map((v) => v.toFixed(2))})`);}
// ------------------------------------------------------------------------------------------------
for (const letter of ['A', 'B', 'L', 'Y']) { test(`ASL ${letter}: finger bends match landmarks, right hand not mirrored, arm sane`, () => { const { rig } = makeRig(); const pose = poseOf('asl', letter); snap(rig, pose); assertHandMatches(rig, 'right', pose.right, `ASL ${letter}`); assertChirality(pose.right, 'right', `ASL ${letter}`); assertArm(rig, 'right', `ASL ${letter}`); assertArm(rig, 'left', `ASL ${letter} (idle arm)`); // Signing hand sits on viewer-left (avatar's right), thumb toward the body midline for A const wr = wp(rig, BONE_NAMES.right.hand); assert.ok(wr.x < rig.layout.centerX, 'signing hand must be on the avatar\'s right (viewer-left)'); });}
test('ASL A: thumb is on the viewer-right side of the pinky (not mirrored)', () => { const { rig } = makeRig(); snap(rig, poseOf('asl', 'A')); const thumb = wp(rig, BONE_NAMES.right.fingers.thumb[3]); const pinky = wp(rig, BONE_NAMES.right.fingers.pinky[0]); assert.ok(thumb.x > pinky.x, `thumb.x ${thumb.x.toFixed(3)} should be > pinky.x ${pinky.x.toFixed(3)}`);});
test('ISL two-handed A: both hands match landmarks, correct sides, no crossing', () => { const { rig } = makeRig(); const pose = poseOf('isl', 'A'); assert.equal(pose.twoHanded, true); snap(rig, pose); // template `left` = viewer-left hand = avatar RIGHT; template `right` = avatar LEFT assertHandMatches(rig, 'right', pose.left, 'ISL A (2H)'); assertHandMatches(rig, 'left', pose.right, 'ISL A (2H)'); assertChirality(pose.left, 'right', 'ISL A (2H)'); assertChirality(pose.right, 'left', 'ISL A (2H)'); assertArm(rig, 'right', 'ISL A (2H)'); assertArm(rig, 'left', 'ISL A (2H)'); const r = wp(rig, BONE_NAMES.right.hand); const l = wp(rig, BONE_NAMES.left.hand); assert.ok(r.x < l.x, 'avatar right wrist must be on viewer-left of the left wrist');});
test('every two-handed ISL sign keeps arms outside the torso and wrists on their own side', () => { const { rig } = makeRig(); let consistent = 0; let total = 0; for (const key of Object.keys(templates.isl).filter((k) => templates.isl[k].twoHanded)) { const pose = poseOf('isl', key); snap(rig, pose); assertArm(rig, 'right', `ISL ${key}`); assertArm(rig, 'left', `ISL ${key}`); // Dataset-wide chirality audit (informational for signs with ambiguous thumb geometry). for (const [lm, side] of [[pose.left, 'right'], [pose.right, 'left']]) { const z = landmarkThumbZ(lm); total++; if (side === 'right' ? z.every((v) => v < 0) : z.every((v) => v > 0)) consistent++; } } console.log(` two-handed ISL chirality audit: ${consistent}/${total} hands unambiguously match their assigned side`); assert.ok(consistent / total > 0.7, 'most two-handed hands must match their assigned avatar side');});
test('sequence H-E-L-L-O: smooth playback converges to each letter exactly', () => { const { rig } = makeRig(); let maxStep = 0; for (const ch of 'HELLO') { const pose = poseOf('asl', ch); for (let f = 0; f < 90; f++) { // 1.5 s at 60 fps const before = rig.right.fingers[4].quaternion.clone(); rig.update(pose, 1 / 60); rig.root.updateMatrixWorld(true); maxStep = Math.max(maxStep, before.angleTo(rig.right.fingers[4].quaternion) * DEG); } assertHandMatches(rig, 'right', pose.right, `ASL ${ch}`); assertArm(rig, 'right', `ASL ${ch}`); } console.log(` HELLO: max per-frame finger bone rotation ${maxStep.toFixed(2)} deg (no pops)`); assert.ok(maxStep < 60, 'bone rotation popped between frames');});
test('face: neutral fallback, sign-driven blendshapes, blink', () => { const { rig, nodes } = makeRig(); const face = nodes.get('Head').obj.children.find((c) => c.name === 'Wolf3D_Head'); rig.update(poseOf('asl', 'A'), 10); assert.equal(face.morphTargetInfluences[0], 0, 'jaw must be neutral without face data'); rig.update({ ...poseOf('asl', 'A'), face: { jawOpen: 0.7, browInnerUp: 0.4 } }, 10); assert.ok(Math.abs(face.morphTargetInfluences[0] - 0.7) < 1e-6, 'jawOpen driven from sign data'); assert.ok(Math.abs(face.morphTargetInfluences[3] - 0.4) < 1e-6, 'browInnerUp driven from sign data'); let blinked = false; for (let i = 0; i < 60 * 8 && !blinked; i++) { rig.update(poseOf('asl', 'A'), 1 / 60); if (face.morphTargetInfluences[1] > 0.5) blinked = true; } assert.ok(blinked, 'idle blink should occur within 8 s');});
test('bone-name warnings: missing bones are listed, mixamo prefix resolves', () => { const warns = []; const orig = console.warn; console.warn = (m) => warns.push(String(m)); try { const omit = ['LeftHandPinky3', 'LeftHandPinky4', 'RightHandThumb4']; const { root } = buildTestRig({ omit }); new AvatarRig(root, {}); } finally { console.warn = orig; } assert.equal(warns.length, 1); assert.match(warns[0], /LeftHandPinky3/); assert.doesNotMatch(warns[0], /RightHandThumb4/, 'end bones are optional, only an info notice');
const { root } = buildTestRig({ prefix: 'mixamorig' }); const rig = new AvatarRig(root, { silent: true }); assert.equal(rig.missing.length, 0, `mixamorig prefix should resolve; missing: ${rig.missing}`);});
test('basis frame is chirality-consistent between landmarks and rig', () => { const q = new Quaternion(); assert.ok(basisQuaternion(new Vector3(0, 1, 0), new Vector3(1, 0, 0), q)); assert.ok(!basisQuaternion(new Vector3(0, 0, 0), new Vector3(1, 0, 0), q));});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970// Procedural T-pose humanoid used ONLY by the unit tests (not shipped to the browser).// It is a plain Three.js bone hierarchy, not a model file. Rest bones carry non-trivial roll// quaternions on purpose, so the retargeting is exercised on rigs whose local axes are not identity.import { Object3D, Quaternion, Vector3 } from 'three';
const X = new Vector3(1, 0, 0);
/** * @param {{ prefix?: string, omit?: string[], withFace?: boolean }} [opts] */export function buildTestRig({ prefix = '', omit = [], withFace = true } = {}) { const root = new Object3D(); root.name = 'Armature'; /** @type {Map<string, {obj: Object3D, wq: Quaternion}>} */ const nodes = new Map(); const add = (name, parentName, worldOffset, roll = 0) => { if (omit.includes(name)) return; const parent = parentName && nodes.get(parentName) ? nodes.get(parentName) : { obj: root, wq: new Quaternion() }; const obj = new Object3D(); obj.name = prefix + name; obj.position.copy(worldOffset).applyQuaternion(parent.wq.clone().invert()); obj.quaternion.setFromAxisAngle(X, roll); parent.obj.add(obj); nodes.set(name, { obj, wq: parent.wq.clone().multiply(obj.quaternion) }); }; const v = (x, y, z) => new Vector3(x, y, z);
add('Hips', null, v(0, 1, 0)); add('Spine', 'Hips', v(0, 0.1, 0)); add('Spine1', 'Spine', v(0, 0.12, 0)); add('Spine2', 'Spine1', v(0, 0.12, 0)); add('Neck', 'Spine2', v(0, 0.15, 0)); add('Head', 'Neck', v(0, 0.1, 0));
// Right arm = -x, left arm = +x (avatar faces +z, so avatar-right is world -x). for (const [S, sx] of [['Right', -1], ['Left', 1]]) { add(`${S}Shoulder`, 'Spine2', v(sx * 0.05, 0.12, 0)); add(`${S}Arm`, `${S}Shoulder`, v(sx * 0.14, 0, 0), 0.2); add(`${S}ForeArm`, `${S}Arm`, v(sx * 0.3, 0, 0), 0.3); add(`${S}Hand`, `${S}ForeArm`, v(sx * 0.27, 0, 0), 0.4); // [name, per-bone world offsets from the previous joint (x is mirrored per side)] const fingers = { Index: [[-0.09, 0, 0.03], [-0.04, 0, 0], [-0.025, 0, 0], [-0.02, 0, 0]], Middle: [[-0.095, 0, 0.005], [-0.045, 0, 0], [-0.027, 0, 0], [-0.02, 0, 0]], Ring: [[-0.09, 0, -0.02], [-0.04, 0, 0], [-0.025, 0, 0], [-0.02, 0, 0]], Pinky: [[-0.08, 0, -0.04], [-0.03, 0, 0], [-0.018, 0, 0], [-0.015, 0, 0]], // Palm-down T-pose: thumb points forward (+z). Thumb: [[-0.03, -0.01, 0.03], [-0.012, -0.004, 0.03], [-0.01, -0.003, 0.025], [-0.008, -0.002, 0.02]], }; for (const [F, offs] of Object.entries(fingers)) { offs.forEach((o, i) => { const parent = i === 0 ? `${S}Hand` : `${S}Hand${F}${i}`; // Offsets above are authored for the RIGHT hand (fingers toward -x); mirror for the left hand. add(`${S}Hand${F}${i + 1}`, parent, v(-sx * o[0], o[1], o[2]), 0.15); }); } }
if (withFace) { const head = nodes.get('Head'); const face = new Object3D(); face.name = 'Wolf3D_Head'; face.morphTargetDictionary = { jawOpen: 0, eyeBlinkLeft: 1, eyeBlinkRight: 2, browInnerUp: 3, mouthSmileLeft: 4 }; face.morphTargetInfluences = [0, 0, 0, 0, 0]; if (head) head.obj.add(face); }
root.updateMatrixWorld(true); return { root, nodes };}8 unmodified lines9101112131415161714 unmodified lines32333435363750 unmodified lines888990919293117 unmodified lines21121221321421521639 unmodified lines256257258259260261126 unmodified lines3883893903913923938 unmodified lines<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700&family=Geist+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><link rel="stylesheet" href="style.css?v=17" /><!-- MediaPipe Tasks Vision loaded dynamically inside app.js initMediaPipe() --></head><body>14 unmodified lines<button class="mode-btn active" data-mode="asl" id="btn-asl" aria-pressed="true">ASL</button><button class="mode-btn" data-mode="isl" id="btn-isl" aria-pressed="false">ISL</button><button class="mode-btn" data-mode="visually" id="btn-visually" aria-pressed="false">VISUALLY</button><span class="mode-slider" aria-hidden="true"></span></div>50 unmodified lines</div><div class="stage-actions"><button class="ctrl-btn" popovertarget="panel-guide" id="stage-guide-btn" title="View official sign chart">Guide</button><button class="ctrl-btn" id="btn-pause-detection">Pause</button><button class="ctrl-btn active-btn" id="btn-camera-toggle">Stop Camera</button>117 unmodified lines<!-- Right Column: Interactive 3D Avatar Skeleton Stage --><section class="practice-stage" aria-label="Avatar Stage"><div class="avatar-viewport"><canvas id="avatar-canvas"></canvas><!-- Active Letter Glow Badge -->39 unmodified lines</section></section><!-- ══ SETTINGS (top layer) ═════════════════════════════════════════════ --><div popover id="panel-settings" class="sheet" style="display: none;"><header class="sheet-head">126 unmodified lines</dialog><div class="toast" id="toast" role="status" aria-live="polite"></div><script src="app.js?v=19"></script></body></html>8 unmodified lines91011121314151617181920212223242526272814 unmodified lines4344454647484950 unmodified lines100101102103104105106117 unmodified lines22422522622722822923039 unmodified lines270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373126 unmodified lines5005015025035045058 unmodified lines<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700&family=Geist+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><link rel="stylesheet" href="style.css?v=23" /><!-- Three.js pinned local importmap (no CDN) --><script type="importmap">{"imports": {"three": "./vendor/three/three.module.js"}}</script><script>// Feature flag: set window.USE_3D_AVATAR = false in the browser console to revert to 2Dwindow.USE_3D_AVATAR = true;</script></head><body>14 unmodified lines<button class="mode-btn active" data-mode="asl" id="btn-asl" aria-pressed="true">ASL</button><button class="mode-btn" data-mode="isl" id="btn-isl" aria-pressed="false">ISL</button><button class="mode-btn" data-mode="visually" id="btn-visually" aria-pressed="false">VISUALLY</button><button class="mode-btn" data-mode="upload" id="btn-upload" aria-pressed="false">UPLOAD</button><span class="mode-slider" aria-hidden="true"></span></div>50 unmodified lines</div><div class="stage-actions"><button class="ctrl-btn" id="btn-mirror-toggle" title="Switch between mirror selfie view and normal non-mirrored view">🪞 Mirror: On</button><button class="ctrl-btn" popovertarget="panel-guide" id="stage-guide-btn" title="View official sign chart">Guide</button><button class="ctrl-btn" id="btn-pause-detection">Pause</button><button class="ctrl-btn active-btn" id="btn-camera-toggle">Stop Camera</button>117 unmodified lines<!-- Right Column: Interactive 3D Avatar Skeleton Stage --><section class="practice-stage" aria-label="Avatar Stage"><div class="avatar-viewport"><canvas id="avatar-canvas-3d"></canvas><canvas id="avatar-canvas"></canvas><!-- Active Letter Glow Badge -->39 unmodified lines</section></section><!-- ══ UPLOAD (IMAGE SIGN RECOGNITION STUDIO) ════════════════════════════ --><section class="workspace upload-workspace hidden" id="upload-workspace" aria-label="Upload Sign Recognition"><!-- Left Column: Upload Dropzone, Controls & Sample Images --><aside class="upload-sidebar"><article class="panel upload-panel"><header class="panel-head"><div class="upload-head-title"><span class="upload-badge">IMAGE RECOGNITION</span><h2 class="panel-title">Sign Image Classifier</h2></div><div class="upload-dialect-toggle" id="upload-dialect-toggle"><button class="upload-dialect-btn active" id="upload-dialect-asl" data-dialect="asl">ASL</button><button class="upload-dialect-btn" id="upload-dialect-isl" data-dialect="isl">ISL</button></div></header><!-- Drag & Drop Zone --><div class="upload-dropzone" id="upload-dropzone"><input type="file" id="upload-file-input" accept="image/*" class="upload-file-hidden" /><div class="dropzone-icon"><svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg></div><div class="dropzone-title">Drop your hand sign image here</div><div class="dropzone-sub">or <span class="dropzone-browse">browse from computer</span></div><div class="dropzone-formats">Supports JPG, PNG, WEBP, Camera photos</div></div><!-- Quick Test Sample Signs --><div class="upload-samples-wrap"><div class="upload-samples-label">Or test with quick reference signs:</div><div class="upload-samples-chips" id="upload-sample-chips"><!-- Dynamically populated or static samples --><button class="sample-img-chip" data-dialect="asl" data-letter="A">ASL: A</button><button class="sample-img-chip" data-dialect="asl" data-letter="B">ASL: B</button><button class="sample-img-chip" data-dialect="asl" data-letter="C">ASL: C</button><button class="sample-img-chip" data-dialect="asl" data-letter="L">ASL: L</button><button class="sample-img-chip" data-dialect="asl" data-letter="V">ASL: V</button><button class="sample-img-chip" data-dialect="isl" data-letter="5">ISL: 5</button><button class="sample-img-chip" data-dialect="isl" data-letter="C">ISL: C</button><button class="sample-img-chip" data-dialect="isl" data-letter="O">ISL: O</button></div></div><div class="upload-actions-bar"><button class="btn btn-danger" id="btn-clear-upload" style="display: none;">Remove Image</button></div></article></aside><!-- Right Column: Visual Stage with Annotated Canvas & Prediction Results Card --><section class="upload-stage" aria-label="Upload Analysis Stage"><div class="upload-viewport" id="upload-viewport"><!-- Empty Placeholder State --><div class="upload-empty-state" id="upload-empty-state"><div class="upload-empty-icon">🖐️</div><h3>No Image Uploaded Yet</h3><p>Upload any picture with hand signs (ASL or ISL) to analyze 21 MediaPipe skeletal landmarks and classify the sign with top confidence matches.</p><button class="btn btn-primary" id="btn-trigger-browse">Choose Sign Image</button></div><!-- Image Canvas Container --><div class="upload-canvas-wrap hidden" id="upload-canvas-wrap"><canvas id="upload-canvas"></canvas></div><!-- Prediction Floating HUD Overlay --><div class="upload-result-hud hidden" id="upload-result-hud"><div class="result-hud-header"><span class="result-badge-dialect" id="result-dialect-tag">ASL</span><span class="result-badge-hands" id="result-hands-tag">1 Hand Detected</span></div><div class="result-main-row"><div class="result-letter-huge" id="result-letter">—</div><div class="result-details"><div class="result-conf-row"><span class="result-conf-label">Confidence</span><span class="result-conf-val" id="result-confidence">99.8%</span></div><div class="result-desc" id="result-desc">Detecting sign...</div></div></div><!-- Top 3 Probability Breakdown --><div class="result-top3-section"><div class="result-top3-title">Top Model Predictions</div><div class="result-top3-bars" id="result-top3-bars"><!-- Rendered dynamically --></div></div></div></div></section></section><!-- ══ SETTINGS (top layer) ═════════════════════════════════════════════ --><div popover id="panel-settings" class="sheet" style="display: none;"><header class="sheet-head">126 unmodified lines</dialog><div class="toast" id="toast" role="status" aria-live="polite"></div><script type="module" src="app.js?v=33"></script></body></html>
181 unmodified lines18218318418518618718818919019119219319488 unmodified lines2832842852862872881335 unmodified lines162416251626162716281629163016311632163316341635828 unmodified lines246424652466181 unmodified lines.mode-slider {position: absolute; z-index: 1;top: 3px; left: 3px;width: calc((100% - 10px) / 3); height: calc(100% - 6px);background: var(--accent);border-radius: var(--r-pill);transition: transform var(--dur-slow) var(--ease);}.mode-toggle.isl-mode .mode-slider { transform: translateX(calc(100% + 2px)); }.mode-toggle.visually-mode .mode-slider { transform: translateX(calc(200% + 4px)); }.hidden,.hidden * {88 unmodified linesdisplay: block;width: 100%; height: 100%;object-fit: contain;}/* ── Idle / error overlay ──────────────────────────────────────────────1335 unmodified linesoverflow: hidden;}#avatar-canvas {display: block;width: 100%;height: 100%;}/* Avatar HUD Badges */.avatar-hud-letter {position: absolute;828 unmodified linesbackground: #e5e5e5;color: #333;}181 unmodified lines18218318418518618718818919019119219319419588 unmodified lines2842852862872882892902912922932941335 unmodified lines1630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735828 unmodified lines256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998181 unmodified lines.mode-slider {position: absolute; z-index: 1;top: 3px; left: 3px;width: calc((100% - 12px) / 4); height: calc(100% - 6px);background: var(--accent);border-radius: var(--r-pill);transition: transform var(--dur-slow) var(--ease);}.mode-toggle.isl-mode .mode-slider { transform: translateX(calc(100% + 2px)); }.mode-toggle.visually-mode .mode-slider { transform: translateX(calc(200% + 4px)); }.mode-toggle.upload-mode .mode-slider { transform: translateX(calc(300% + 6px)); }.hidden,.hidden * {88 unmodified linesdisplay: block;width: 100%; height: 100%;object-fit: contain;transition: transform var(--dur) var(--ease);}#display-canvas.mirrored {transform: scaleX(-1);}/* ── Idle / error overlay ──────────────────────────────────────────────1335 unmodified linesoverflow: hidden;}#avatar-canvas-3d,#avatar-canvas {position: absolute;inset: 0;display: block;width: 100%;height: 100%;}#avatar-canvas-3d {z-index: 1;}#avatar-canvas {z-index: 2;pointer-events: none;}/* 3D Avatar Model Missing Placeholder Overlay */.avatar-3d-placeholder {position: absolute;inset: 0;display: flex;align-items: center;justify-content: center;padding: 24px;background: color-mix(in oklab, var(--bg-card, #161619) 88%, transparent);backdrop-filter: blur(8px);-webkit-backdrop-filter: blur(8px);z-index: 10;}.avatar-3d-placeholder .ph-card {max-width: 440px;width: 100%;padding: 24px 28px;border-radius: var(--r-panel, 14px);background: var(--bg-card, #1a1a1f);border: 1px solid var(--line, rgba(255, 255, 255, 0.1));box-shadow: 0 16px 36px rgba(0, 0, 0, 0.35);text-align: center;}.avatar-3d-placeholder .ph-icon {font-size: 2.5rem;margin-bottom: 10px;}.avatar-3d-placeholder .ph-title {font-size: 1.15rem;font-weight: 600;color: var(--text, #f1f5f9);margin-bottom: 8px;}.avatar-3d-placeholder .ph-desc {font-size: 0.85rem;color: var(--text-dim, #94a3b8);margin-bottom: 10px;line-height: 1.45;}.avatar-3d-placeholder .ph-path {display: inline-block;padding: 6px 12px;margin-bottom: 12px;border-radius: 6px;background: color-mix(in oklab, var(--accent, #6366f1) 15%, transparent);border: 1px solid color-mix(in oklab, var(--accent, #6366f1) 35%, transparent);color: var(--accent, #818cf8);font-family: var(--mono, monospace);font-size: 0.82rem;user-select: all;}.avatar-3d-placeholder .ph-hint {font-size: 0.76rem;color: var(--text-dim, #64748b);line-height: 1.4;margin-bottom: 16px;}.avatar-3d-placeholder .ph-btn {padding: 8px 18px;border-radius: var(--r-ctrl, 8px);background: color-mix(in oklab, var(--text, #fff) 10%, transparent);border: 1px solid var(--line, rgba(255, 255, 255, 0.15));color: var(--text, #f1f5f9);font-size: 0.82rem;font-weight: 500;cursor: pointer;transition: all 0.2s ease;}.avatar-3d-placeholder .ph-btn:hover {background: var(--accent, #6366f1);color: #fff;border-color: transparent;}/* Avatar HUD Badges */.avatar-hud-letter {position: absolute;828 unmodified linesbackground: #e5e5e5;color: #333;}/* ══════════════════════════════════════════════════════════════════════UPLOAD SIGN RECOGNITION STUDIO STYLES══════════════════════════════════════════════════════════════════════ */.upload-workspace {grid-template-columns: minmax(320px, 380px) 1fr;align-items: stretch;}.upload-sidebar {display: flex;flex-direction: column;height: 100%;min-height: 0;}.upload-panel {display: flex;flex-direction: column;gap: 16px;height: 100%;}.upload-badge {font-family: var(--mono);font-size: 0.62rem;font-weight: 700;letter-spacing: 0.1em;padding: 3px 7px;border-radius: var(--r-pill);background: var(--accent-soft);color: var(--accent-text);border: 1px solid var(--accent-line);display: inline-block;margin-bottom: 4px;}.upload-dialect-toggle {display: flex;background: var(--surface-3);padding: 2px;border-radius: var(--r-pill);border: 1px solid var(--line);gap: 2px;}.upload-dialect-btn {padding: 4px 12px;font-family: var(--font);font-size: 0.74rem;font-weight: 600;border: none;background: transparent;color: var(--text-mute);border-radius: var(--r-pill);cursor: pointer;transition: all var(--dur) var(--ease);}.upload-dialect-btn:hover {color: var(--text);}.upload-dialect-btn.active {background: var(--accent);color: #23180a;}[data-theme="light"] .upload-dialect-btn.active {color: #fff;}/* Drag & Drop Area */.upload-dropzone {position: relative;display: flex;flex-direction: column;align-items: center;justify-content: center;padding: 28px 18px;border: 2px dashed var(--line-bright);border-radius: var(--r-panel);background: var(--surface-2);text-align: center;cursor: pointer;transition: all var(--dur) var(--ease);}.upload-dropzone:hover,.upload-dropzone.dragover {border-color: var(--accent);background: var(--accent-soft);transform: scale(1.01);}.upload-file-hidden {position: absolute;inset: 0;opacity: 0;cursor: pointer;width: 100%;height: 100%;}.dropzone-icon {color: var(--accent);margin-bottom: 12px;transition: transform var(--dur) var(--ease);}.upload-dropzone:hover .dropzone-icon {transform: translateY(-3px);}.dropzone-title {font-size: 0.92rem;font-weight: 600;color: var(--text);margin-bottom: 4px;}.dropzone-sub {font-size: 0.8rem;color: var(--text-dim);margin-bottom: 8px;}.dropzone-browse {color: var(--accent-text);text-decoration: underline;text-underline-offset: 3px;font-weight: 600;}.dropzone-formats {font-size: 0.68rem;font-family: var(--mono);color: var(--text-mute);}/* Samples Section */.upload-samples-wrap {display: flex;flex-direction: column;gap: 8px;margin-top: 4px;}.upload-samples-label {font-size: 0.72rem;font-weight: 600;text-transform: uppercase;letter-spacing: 0.06em;color: var(--text-mute);}.upload-samples-chips {display: flex;flex-wrap: wrap;gap: 6px;}.sample-img-chip {padding: 5px 11px;font-family: var(--mono);font-size: 0.74rem;font-weight: 600;border-radius: var(--r-pill);border: 1px solid var(--line);background: var(--surface-3);color: var(--text-dim);cursor: pointer;transition: all var(--dur) var(--ease);}.sample-img-chip:hover {background: var(--accent-soft);border-color: var(--accent-line);color: var(--accent-text);transform: translateY(-1px);}/* Upload Stage & Visual Viewport */.upload-stage {display: flex;flex-direction: column;height: 100%;min-height: 0;}.upload-viewport {position: relative;flex: 1;width: 100%;height: 100%;background: #0e0e11;border: 1px solid var(--line);border-radius: var(--r-panel);overflow: hidden;display: flex;align-items: center;justify-content: center;}[data-theme="light"] .upload-viewport {background: #f0f2f7;}.upload-empty-state {max-width: 420px;padding: 32px;text-align: center;display: flex;flex-direction: column;align-items: center;gap: 12px;}.upload-empty-icon {font-size: 3.5rem;margin-bottom: 4px;animation: floatHand 3s ease-in-out infinite;}@keyframes floatHand {0%, 100% { transform: translateY(0); }50% { transform: translateY(-8px); }}.upload-empty-state h3 {font-size: 1.25rem;font-weight: 600;color: var(--text);}.upload-empty-state p {font-size: 0.84rem;color: var(--text-dim);line-height: 1.55;margin-bottom: 6px;}.upload-canvas-wrap {width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;overflow: hidden;padding: 16px;box-sizing: border-box;}#upload-canvas {width: auto;height: auto;min-width: min(340px, 85%);min-height: min(340px, 75%);max-width: 92%;max-height: 88%;object-fit: contain;display: block;border-radius: 12px;box-shadow: 0 14px 40px rgba(0, 0, 0, 0.5);background: #141418;}/* Floating Results Card inside Viewport */.upload-result-hud {position: absolute;top: 18px;left: 18px;width: 310px;max-width: calc(100% - 36px);background: rgb(18 18 20 / 0.88);backdrop-filter: blur(14px);border: 1px solid var(--line-bright);border-radius: var(--r-panel);padding: 16px;box-shadow: 0 16px 36px rgba(0, 0, 0, 0.45);display: flex;flex-direction: column;gap: 14px;z-index: 10;animation: hudSlideIn 0.28s cubic-bezier(0.2, 0, 0.2, 1);}[data-theme="light"] .upload-result-hud {background: rgb(255 255 255 / 0.92);box-shadow: 0 16px 36px rgba(0, 0, 0, 0.12);}@keyframes hudSlideIn {from { opacity: 0; transform: translateY(-8px) scale(0.96); }to { opacity: 1; transform: translateY(0) scale(1); }}.result-hud-header {display: flex;align-items: center;justify-content: space-between;}.result-badge-dialect {font-family: var(--mono);font-size: 0.72rem;font-weight: 700;padding: 2px 8px;border-radius: var(--r-pill);background: var(--accent);color: #23180a;}[data-theme="light"] .result-badge-dialect {color: #fff;}.result-badge-hands {font-size: 0.72rem;font-weight: 500;color: var(--text-dim);}.result-main-row {display: flex;align-items: center;gap: 16px;}.result-letter-huge {font-family: var(--mono);font-size: 3.4rem;font-weight: 700;line-height: 1;color: var(--text);min-width: 64px;text-align: center;text-shadow: 0 0 24px color-mix(in oklab, var(--accent) 45%, transparent);}.result-details {display: flex;flex-direction: column;gap: 4px;flex: 1;}.result-conf-row {display: flex;align-items: baseline;justify-content: space-between;}.result-conf-label {font-size: 0.72rem;color: var(--text-mute);text-transform: uppercase;letter-spacing: 0.05em;}.result-conf-val {font-family: var(--mono);font-size: 1rem;font-weight: 700;color: var(--accent-text);}.result-desc {font-size: 0.76rem;color: var(--text-dim);line-height: 1.35;}/* Top 3 Breakdown */.result-top3-section {display: flex;flex-direction: column;gap: 8px;border-top: 1px solid var(--line);padding-top: 10px;}.result-top3-title {font-size: 0.68rem;font-weight: 600;text-transform: uppercase;letter-spacing: 0.06em;color: var(--text-mute);}.result-top3-bars {display: flex;flex-direction: column;gap: 6px;}.top3-row {display: flex;align-items: center;gap: 8px;font-size: 0.75rem;}.top3-label {font-family: var(--mono);font-weight: 700;min-width: 22px;color: var(--text);}.top3-bar-track {flex: 1;height: 6px;background: var(--surface-3);border-radius: var(--r-pill);overflow: hidden;}.top3-bar-fill {height: 100%;border-radius: inherit;background: var(--accent);transition: width 0.35s ease;}.top3-val {font-family: var(--mono);font-size: 0.7rem;color: var(--text-dim);min-width: 38px;text-align: right;}
123456789101112131415161718192021The MIT License
Copyright © 2010-2023 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417import { EventDispatcher, MOUSE, Quaternion, Spherical, TOUCH, Vector2, Vector3, Plane, Ray, MathUtils} from 'three';
// OrbitControls performs orbiting, dollying (zooming), and panning.// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).//// Orbit - left mouse / touch: one-finger move// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
const _changeEvent = { type: 'change' };const _startEvent = { type: 'start' };const _endEvent = { type: 'end' };const _ray = new Ray();const _plane = new Plane();const TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
class OrbitControls extends EventDispatcher {
constructor( object, domElement ) {
super();
this.object = object; this.domElement = domElement; this.domElement.style.touchAction = 'none'; // disable touch scroll
// Set to false to disable this control this.enabled = true;
// "target" sets the location of focus, where the object orbits around this.target = new Vector3();
// Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect this.cursor = new Vector3();
// How far you can dolly in and out ( PerspectiveCamera only ) this.minDistance = 0; this.maxDistance = Infinity;
// How far you can zoom in and out ( OrthographicCamera only ) this.minZoom = 0; this.maxZoom = Infinity;
// Limit camera target within a spherical area around the cursor this.minTargetRadius = 0; this.maxTargetRadius = Infinity;
// How far you can orbit vertically, upper and lower limits. // Range is 0 to Math.PI radians. this.minPolarAngle = 0; // radians this.maxPolarAngle = Math.PI; // radians
// How far you can orbit horizontally, upper and lower limits. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) this.minAzimuthAngle = - Infinity; // radians this.maxAzimuthAngle = Infinity; // radians
// Set to true to enable damping (inertia) // If damping is enabled, you must call controls.update() in your animation loop this.enableDamping = false; this.dampingFactor = 0.05;
// This option actually enables dollying in and out; left as "zoom" for backwards compatibility. // Set to false to disable zooming this.enableZoom = true; this.zoomSpeed = 1.0;
// Set to false to disable rotating this.enableRotate = true; this.rotateSpeed = 1.0;
// Set to false to disable panning this.enablePan = true; this.panSpeed = 1.0; this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up this.keyPanSpeed = 7.0; // pixels moved per arrow key push this.zoomToCursor = false;
// Set to true to automatically rotate around the target // If auto-rotate is enabled, you must call controls.update() in your animation loop this.autoRotate = false; this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
// The four arrow keys this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
// Mouse buttons this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
// Touch fingers this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
// for reset this.target0 = this.target.clone(); this.position0 = this.object.position.clone(); this.zoom0 = this.object.zoom;
// the target DOM element for key events this._domElementKeyEvents = null;
// // public methods //
this.getPolarAngle = function () {
return spherical.phi;
};
this.getAzimuthalAngle = function () {
return spherical.theta;
};
this.getDistance = function () {
return this.object.position.distanceTo( this.target );
};
this.listenToKeyEvents = function ( domElement ) {
domElement.addEventListener( 'keydown', onKeyDown ); this._domElementKeyEvents = domElement;
};
this.stopListenToKeyEvents = function () {
this._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); this._domElementKeyEvents = null;
};
this.saveState = function () {
scope.target0.copy( scope.target ); scope.position0.copy( scope.object.position ); scope.zoom0 = scope.object.zoom;
};
this.reset = function () {
scope.target.copy( scope.target0 ); scope.object.position.copy( scope.position0 ); scope.object.zoom = scope.zoom0;
scope.object.updateProjectionMatrix(); scope.dispatchEvent( _changeEvent );
scope.update();
state = STATE.NONE;
};
// this method is exposed, but perhaps it would be better if we can make it private... this.update = function () {
const offset = new Vector3();
// so camera.up is the orbit axis const quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); const quatInverse = quat.clone().invert();
const lastPosition = new Vector3(); const lastQuaternion = new Quaternion(); const lastTargetPosition = new Vector3();
const twoPI = 2 * Math.PI;
return function update( deltaTime = null ) {
const position = scope.object.position;
offset.copy( position ).sub( scope.target );
// rotate offset to "y-axis-is-up" space offset.applyQuaternion( quat );
// angle from z-axis around y-axis spherical.setFromVector3( offset );
if ( scope.autoRotate && state === STATE.NONE ) {
rotateLeft( getAutoRotationAngle( deltaTime ) );
}
if ( scope.enableDamping ) {
spherical.theta += sphericalDelta.theta * scope.dampingFactor; spherical.phi += sphericalDelta.phi * scope.dampingFactor;
} else {
spherical.theta += sphericalDelta.theta; spherical.phi += sphericalDelta.phi;
}
// restrict theta to be between desired limits
let min = scope.minAzimuthAngle; let max = scope.maxAzimuthAngle;
if ( isFinite( min ) && isFinite( max ) ) {
if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
if ( min <= max ) {
spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
} else {
spherical.theta = ( spherical.theta > ( min + max ) / 2 ) ? Math.max( min, spherical.theta ) : Math.min( max, spherical.theta );
}
}
// restrict phi to be between desired limits spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
spherical.makeSafe();
// move target to panned location
if ( scope.enableDamping === true ) {
scope.target.addScaledVector( panOffset, scope.dampingFactor );
} else {
scope.target.add( panOffset );
}
// Limit the target distance from the cursor to create a sphere around the center of interest scope.target.sub( scope.cursor ); scope.target.clampLength( scope.minTargetRadius, scope.maxTargetRadius ); scope.target.add( scope.cursor );
// adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera // we adjust zoom later in these cases if ( scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera ) {
spherical.radius = clampDistance( spherical.radius );
} else {
spherical.radius = clampDistance( spherical.radius * scale );
}
offset.setFromSpherical( spherical );
// rotate offset back to "camera-up-vector-is-up" space offset.applyQuaternion( quatInverse );
position.copy( scope.target ).add( offset );
scope.object.lookAt( scope.target );
if ( scope.enableDamping === true ) {
sphericalDelta.theta *= ( 1 - scope.dampingFactor ); sphericalDelta.phi *= ( 1 - scope.dampingFactor );
panOffset.multiplyScalar( 1 - scope.dampingFactor );
} else {
sphericalDelta.set( 0, 0, 0 );
panOffset.set( 0, 0, 0 );
}
// adjust camera position let zoomChanged = false; if ( scope.zoomToCursor && performCursorZoom ) {
let newRadius = null; if ( scope.object.isPerspectiveCamera ) {
// move the camera down the pointer ray // this method avoids floating point error const prevRadius = offset.length(); newRadius = clampDistance( prevRadius * scale );
const radiusDelta = prevRadius - newRadius; scope.object.position.addScaledVector( dollyDirection, radiusDelta ); scope.object.updateMatrixWorld();
} else if ( scope.object.isOrthographicCamera ) {
// adjust the ortho camera position based on zoom changes const mouseBefore = new Vector3( mouse.x, mouse.y, 0 ); mouseBefore.unproject( scope.object );
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) ); scope.object.updateProjectionMatrix(); zoomChanged = true;
const mouseAfter = new Vector3( mouse.x, mouse.y, 0 ); mouseAfter.unproject( scope.object );
scope.object.position.sub( mouseAfter ).add( mouseBefore ); scope.object.updateMatrixWorld();
newRadius = offset.length();
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' ); scope.zoomToCursor = false;
}
// handle the placement of the target if ( newRadius !== null ) {
if ( this.screenSpacePanning ) {
// position the orbit target in front of the new camera position scope.target.set( 0, 0, - 1 ) .transformDirection( scope.object.matrix ) .multiplyScalar( newRadius ) .add( scope.object.position );
} else {
// get the ray and translation plane to compute target _ray.origin.copy( scope.object.position ); _ray.direction.set( 0, 0, - 1 ).transformDirection( scope.object.matrix );
// if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid // extremely large values if ( Math.abs( scope.object.up.dot( _ray.direction ) ) < TILT_LIMIT ) {
object.lookAt( scope.target );
} else {
_plane.setFromNormalAndCoplanarPoint( scope.object.up, scope.target ); _ray.intersectPlane( _plane, scope.target );
}
}
}
} else if ( scope.object.isOrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / scale ) ); scope.object.updateProjectionMatrix(); zoomChanged = true;
}
scale = 1; performCursorZoom = false;
// update condition is: // min(camera displacement, camera rotation in radians)^2 > EPS // using small-angle approximation cos(x/2) = 1 - x^2 / 8
if ( zoomChanged || lastPosition.distanceToSquared( scope.object.position ) > EPS || 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS || lastTargetPosition.distanceToSquared( scope.target ) > 0 ) {
scope.dispatchEvent( _changeEvent );
lastPosition.copy( scope.object.position ); lastQuaternion.copy( scope.object.quaternion ); lastTargetPosition.copy( scope.target );
return true;
}
return false;
};
}();
this.dispose = function () {
scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); scope.domElement.removeEventListener( 'pointercancel', onPointerUp ); scope.domElement.removeEventListener( 'wheel', onMouseWheel );
scope.domElement.removeEventListener( 'pointermove', onPointerMove ); scope.domElement.removeEventListener( 'pointerup', onPointerUp );
if ( scope._domElementKeyEvents !== null ) {
scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown ); scope._domElementKeyEvents = null;
}
//scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
};
// // internals //
const scope = this;
const STATE = { NONE: - 1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_PAN: 4, TOUCH_DOLLY_PAN: 5, TOUCH_DOLLY_ROTATE: 6 };
let state = STATE.NONE;
const EPS = 0.000001;
// current position in spherical coordinates const spherical = new Spherical(); const sphericalDelta = new Spherical();
let scale = 1; const panOffset = new Vector3();
const rotateStart = new Vector2(); const rotateEnd = new Vector2(); const rotateDelta = new Vector2();
const panStart = new Vector2(); const panEnd = new Vector2(); const panDelta = new Vector2();
const dollyStart = new Vector2(); const dollyEnd = new Vector2(); const dollyDelta = new Vector2();
const dollyDirection = new Vector3(); const mouse = new Vector2(); let performCursorZoom = false;
const pointers = []; const pointerPositions = {};
function getAutoRotationAngle( deltaTime ) {
if ( deltaTime !== null ) {
return ( 2 * Math.PI / 60 * scope.autoRotateSpeed ) * deltaTime;
} else {
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
}
}
function getZoomScale( delta ) {
const normalized_delta = Math.abs( delta ) / ( 100 * ( window.devicePixelRatio | 0 ) ); return Math.pow( 0.95, scope.zoomSpeed * normalized_delta );
}
function rotateLeft( angle ) {
sphericalDelta.theta -= angle;
}
function rotateUp( angle ) {
sphericalDelta.phi -= angle;
}
const panLeft = function () {
const v = new Vector3();
return function panLeft( distance, objectMatrix ) {
v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix v.multiplyScalar( - distance );
panOffset.add( v );
};
}();
const panUp = function () {
const v = new Vector3();
return function panUp( distance, objectMatrix ) {
if ( scope.screenSpacePanning === true ) {
v.setFromMatrixColumn( objectMatrix, 1 );
} else {
v.setFromMatrixColumn( objectMatrix, 0 ); v.crossVectors( scope.object.up, v );
}
v.multiplyScalar( distance );
panOffset.add( v );
};
}();
// deltaX and deltaY are in pixels; right and down are positive const pan = function () {
const offset = new Vector3();
return function pan( deltaX, deltaY ) {
const element = scope.domElement;
if ( scope.object.isPerspectiveCamera ) {
// perspective const position = scope.object.position; offset.copy( position ).sub( scope.target ); let targetDistance = offset.length();
// half of the fov is center to top of screen targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
// we use only clientHeight here so aspect ratio does not distort speed panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix ); panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
} else if ( scope.object.isOrthographicCamera ) {
// orthographic panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix ); panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
} else {
// camera neither orthographic nor perspective console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); scope.enablePan = false;
}
};
}();
function dollyOut( dollyScale ) {
if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
scale /= dollyScale;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); scope.enableZoom = false;
}
}
function dollyIn( dollyScale ) {
if ( scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera ) {
scale *= dollyScale;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); scope.enableZoom = false;
}
}
function updateZoomParameters( x, y ) {
if ( ! scope.zoomToCursor ) {
return;
}
performCursorZoom = true;
const rect = scope.domElement.getBoundingClientRect(); const dx = x - rect.left; const dy = y - rect.top; const w = rect.width; const h = rect.height;
mouse.x = ( dx / w ) * 2 - 1; mouse.y = - ( dy / h ) * 2 + 1;
dollyDirection.set( mouse.x, mouse.y, 1 ).unproject( scope.object ).sub( scope.object.position ).normalize();
}
function clampDistance( dist ) {
return Math.max( scope.minDistance, Math.min( scope.maxDistance, dist ) );
}
// // event callbacks - update the object state //
function handleMouseDownRotate( event ) {
rotateStart.set( event.clientX, event.clientY );
}
function handleMouseDownDolly( event ) {
updateZoomParameters( event.clientX, event.clientX ); dollyStart.set( event.clientX, event.clientY );
}
function handleMouseDownPan( event ) {
panStart.set( event.clientX, event.clientY );
}
function handleMouseMoveRotate( event ) {
rotateEnd.set( event.clientX, event.clientY );
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
const element = scope.domElement;
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
rotateStart.copy( rotateEnd );
scope.update();
}
function handleMouseMoveDolly( event ) {
dollyEnd.set( event.clientX, event.clientY );
dollyDelta.subVectors( dollyEnd, dollyStart );
if ( dollyDelta.y > 0 ) {
dollyOut( getZoomScale( dollyDelta.y ) );
} else if ( dollyDelta.y < 0 ) {
dollyIn( getZoomScale( dollyDelta.y ) );
}
dollyStart.copy( dollyEnd );
scope.update();
}
function handleMouseMovePan( event ) {
panEnd.set( event.clientX, event.clientY );
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
scope.update();
}
function handleMouseWheel( event ) {
updateZoomParameters( event.clientX, event.clientY );
if ( event.deltaY < 0 ) {
dollyIn( getZoomScale( event.deltaY ) );
} else if ( event.deltaY > 0 ) {
dollyOut( getZoomScale( event.deltaY ) );
}
scope.update();
}
function handleKeyDown( event ) {
let needsUpdate = false;
switch ( event.code ) {
case scope.keys.UP:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( 0, scope.keyPanSpeed );
}
needsUpdate = true; break;
case scope.keys.BOTTOM:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( 0, - scope.keyPanSpeed );
}
needsUpdate = true; break;
case scope.keys.LEFT:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( scope.keyPanSpeed, 0 );
}
needsUpdate = true; break;
case scope.keys.RIGHT:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
} else {
pan( - scope.keyPanSpeed, 0 );
}
needsUpdate = true; break;
}
if ( needsUpdate ) {
// prevent the browser from scrolling on cursor keys event.preventDefault();
scope.update();
}
}
function handleTouchStartRotate( event ) {
if ( pointers.length === 1 ) {
rotateStart.set( event.pageX, event.pageY );
} else {
const position = getSecondPointerPosition( event );
const x = 0.5 * ( event.pageX + position.x ); const y = 0.5 * ( event.pageY + position.y );
rotateStart.set( x, y );
}
}
function handleTouchStartPan( event ) {
if ( pointers.length === 1 ) {
panStart.set( event.pageX, event.pageY );
} else {
const position = getSecondPointerPosition( event );
const x = 0.5 * ( event.pageX + position.x ); const y = 0.5 * ( event.pageY + position.y );
panStart.set( x, y );
}
}
function handleTouchStartDolly( event ) {
const position = getSecondPointerPosition( event );
const dx = event.pageX - position.x; const dy = event.pageY - position.y;
const distance = Math.sqrt( dx * dx + dy * dy );
dollyStart.set( 0, distance );
}
function handleTouchStartDollyPan( event ) {
if ( scope.enableZoom ) handleTouchStartDolly( event );
if ( scope.enablePan ) handleTouchStartPan( event );
}
function handleTouchStartDollyRotate( event ) {
if ( scope.enableZoom ) handleTouchStartDolly( event );
if ( scope.enableRotate ) handleTouchStartRotate( event );
}
function handleTouchMoveRotate( event ) {
if ( pointers.length == 1 ) {
rotateEnd.set( event.pageX, event.pageY );
} else {
const position = getSecondPointerPosition( event );
const x = 0.5 * ( event.pageX + position.x ); const y = 0.5 * ( event.pageY + position.y );
rotateEnd.set( x, y );
}
rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
const element = scope.domElement;
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
rotateStart.copy( rotateEnd );
}
function handleTouchMovePan( event ) {
if ( pointers.length === 1 ) {
panEnd.set( event.pageX, event.pageY );
} else {
const position = getSecondPointerPosition( event );
const x = 0.5 * ( event.pageX + position.x ); const y = 0.5 * ( event.pageY + position.y );
panEnd.set( x, y );
}
panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
}
function handleTouchMoveDolly( event ) {
const position = getSecondPointerPosition( event );
const dx = event.pageX - position.x; const dy = event.pageY - position.y;
const distance = Math.sqrt( dx * dx + dy * dy );
dollyEnd.set( 0, distance );
dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
dollyOut( dollyDelta.y );
dollyStart.copy( dollyEnd );
const centerX = ( event.pageX + position.x ) * 0.5; const centerY = ( event.pageY + position.y ) * 0.5;
updateZoomParameters( centerX, centerY );
}
function handleTouchMoveDollyPan( event ) {
if ( scope.enableZoom ) handleTouchMoveDolly( event );
if ( scope.enablePan ) handleTouchMovePan( event );
}
function handleTouchMoveDollyRotate( event ) {
if ( scope.enableZoom ) handleTouchMoveDolly( event );
if ( scope.enableRotate ) handleTouchMoveRotate( event );
}
// // event handlers - FSM: listen for events and reset state //
function onPointerDown( event ) {
if ( scope.enabled === false ) return;
if ( pointers.length === 0 ) {
scope.domElement.setPointerCapture( event.pointerId );
scope.domElement.addEventListener( 'pointermove', onPointerMove ); scope.domElement.addEventListener( 'pointerup', onPointerUp );
}
//
addPointer( event );
if ( event.pointerType === 'touch' ) {
onTouchStart( event );
} else {
onMouseDown( event );
}
}
function onPointerMove( event ) {
if ( scope.enabled === false ) return;
if ( event.pointerType === 'touch' ) {
onTouchMove( event );
} else {
onMouseMove( event );
}
}
function onPointerUp( event ) {
removePointer( event );
if ( pointers.length === 0 ) {
scope.domElement.releasePointerCapture( event.pointerId );
scope.domElement.removeEventListener( 'pointermove', onPointerMove ); scope.domElement.removeEventListener( 'pointerup', onPointerUp );
}
scope.dispatchEvent( _endEvent );
state = STATE.NONE;
}
function onMouseDown( event ) {
let mouseAction;
switch ( event.button ) {
case 0:
mouseAction = scope.mouseButtons.LEFT; break;
case 1:
mouseAction = scope.mouseButtons.MIDDLE; break;
case 2:
mouseAction = scope.mouseButtons.RIGHT; break;
default:
mouseAction = - 1;
}
switch ( mouseAction ) {
case MOUSE.DOLLY:
if ( scope.enableZoom === false ) return;
handleMouseDownDolly( event );
state = STATE.DOLLY;
break;
case MOUSE.ROTATE:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
} else {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
}
break;
case MOUSE.PAN:
if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
} else {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
}
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.dispatchEvent( _startEvent );
}
}
function onMouseMove( event ) {
switch ( state ) {
case STATE.ROTATE:
if ( scope.enableRotate === false ) return;
handleMouseMoveRotate( event );
break;
case STATE.DOLLY:
if ( scope.enableZoom === false ) return;
handleMouseMoveDolly( event );
break;
case STATE.PAN:
if ( scope.enablePan === false ) return;
handleMouseMovePan( event );
break;
}
}
function onMouseWheel( event ) {
if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
event.preventDefault();
scope.dispatchEvent( _startEvent );
handleMouseWheel( event );
scope.dispatchEvent( _endEvent );
}
function onKeyDown( event ) {
if ( scope.enabled === false || scope.enablePan === false ) return;
handleKeyDown( event );
}
function onTouchStart( event ) {
trackPointer( event );
switch ( pointers.length ) {
case 1:
switch ( scope.touches.ONE ) {
case TOUCH.ROTATE:
if ( scope.enableRotate === false ) return;
handleTouchStartRotate( event );
state = STATE.TOUCH_ROTATE;
break;
case TOUCH.PAN:
if ( scope.enablePan === false ) return;
handleTouchStartPan( event );
state = STATE.TOUCH_PAN;
break;
default:
state = STATE.NONE;
}
break;
case 2:
switch ( scope.touches.TWO ) {
case TOUCH.DOLLY_PAN:
if ( scope.enableZoom === false && scope.enablePan === false ) return;
handleTouchStartDollyPan( event );
state = STATE.TOUCH_DOLLY_PAN;
break;
case TOUCH.DOLLY_ROTATE:
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
handleTouchStartDollyRotate( event );
state = STATE.TOUCH_DOLLY_ROTATE;
break;
default:
state = STATE.NONE;
}
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.dispatchEvent( _startEvent );
}
}
function onTouchMove( event ) {
trackPointer( event );
switch ( state ) {
case STATE.TOUCH_ROTATE:
if ( scope.enableRotate === false ) return;
handleTouchMoveRotate( event );
scope.update();
break;
case STATE.TOUCH_PAN:
if ( scope.enablePan === false ) return;
handleTouchMovePan( event );
scope.update();
break;
case STATE.TOUCH_DOLLY_PAN:
if ( scope.enableZoom === false && scope.enablePan === false ) return;
handleTouchMoveDollyPan( event );
scope.update();
break;
case STATE.TOUCH_DOLLY_ROTATE:
if ( scope.enableZoom === false && scope.enableRotate === false ) return;
handleTouchMoveDollyRotate( event );
scope.update();
break;
default:
state = STATE.NONE;
}
}
function onContextMenu( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
}
function addPointer( event ) {
pointers.push( event.pointerId );
}
function removePointer( event ) {
delete pointerPositions[ event.pointerId ];
for ( let i = 0; i < pointers.length; i ++ ) {
if ( pointers[ i ] == event.pointerId ) {
pointers.splice( i, 1 ); return;
}
}
}
function trackPointer( event ) {
let position = pointerPositions[ event.pointerId ];
if ( position === undefined ) {
position = new Vector2(); pointerPositions[ event.pointerId ] = position;
}
position.set( event.pageX, event.pageY );
}
function getSecondPointerPosition( event ) {
const pointerId = ( event.pointerId === pointers[ 0 ] ) ? pointers[ 1 ] : pointers[ 0 ];
return pointerPositions[ pointerId ];
}
//
scope.domElement.addEventListener( 'contextmenu', onContextMenu );
scope.domElement.addEventListener( 'pointerdown', onPointerDown ); scope.domElement.addEventListener( 'pointercancel', onPointerUp ); scope.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } );
// force an update at start
this.update();
}
}
export { OrbitControls };1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import { Curve, Vector3, Vector4} from 'three';import * as NURBSUtils from '../curves/NURBSUtils.js';
/** * NURBS curve object * * Derives from Curve, overriding getPoint and getTangent. * * Implementation is based on (x, y [, z=0 [, w=1]]) control points with w=weight. * **/
class NURBSCurve extends Curve {
constructor( degree, knots /* array of reals */, controlPoints /* array of Vector(2|3|4) */, startKnot /* index in knots */, endKnot /* index in knots */ ) {
super();
this.degree = degree; this.knots = knots; this.controlPoints = []; // Used by periodic NURBS to remove hidden spans this.startKnot = startKnot || 0; this.endKnot = endKnot || ( this.knots.length - 1 );
for ( let i = 0; i < controlPoints.length; ++ i ) {
// ensure Vector4 for control points const point = controlPoints[ i ]; this.controlPoints[ i ] = new Vector4( point.x, point.y, point.z, point.w );
}
}
getPoint( t, optionalTarget = new Vector3() ) {
const point = optionalTarget;
const u = this.knots[ this.startKnot ] + t * ( this.knots[ this.endKnot ] - this.knots[ this.startKnot ] ); // linear mapping t->u
// following results in (wx, wy, wz, w) homogeneous point const hpoint = NURBSUtils.calcBSplinePoint( this.degree, this.knots, this.controlPoints, u );
if ( hpoint.w !== 1.0 ) {
// project to 3D space: (wx, wy, wz, w) -> (x, y, z, 1) hpoint.divideScalar( hpoint.w );
}
return point.set( hpoint.x, hpoint.y, hpoint.z );
}
getTangent( t, optionalTarget = new Vector3() ) {
const tangent = optionalTarget;
const u = this.knots[ 0 ] + t * ( this.knots[ this.knots.length - 1 ] - this.knots[ 0 ] ); const ders = NURBSUtils.calcNURBSDerivatives( this.degree, this.knots, this.controlPoints, u, 1 ); tangent.copy( ders[ 1 ] ).normalize();
return tangent;
}
}
export { NURBSCurve };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487import { Vector3, Vector4} from 'three';
/** * NURBS utils * * See NURBSCurve and NURBSSurface. **/
/************************************************************** * NURBS Utils **************************************************************/
/*Finds knot vector span.
p : degreeu : parametric valueU : knot vector
returns the span*/function findSpan( p, u, U ) {
const n = U.length - p - 1;
if ( u >= U[ n ] ) {
return n - 1;
}
if ( u <= U[ p ] ) {
return p;
}
let low = p; let high = n; let mid = Math.floor( ( low + high ) / 2 );
while ( u < U[ mid ] || u >= U[ mid + 1 ] ) {
if ( u < U[ mid ] ) {
high = mid;
} else {
low = mid;
}
mid = Math.floor( ( low + high ) / 2 );
}
return mid;
}
/*Calculate basis functions. See The NURBS Book, page 70, algorithm A2.2
span : span in which u liesu : parametric pointp : degreeU : knot vector
returns array[p+1] with basis functions values.*/function calcBasisFunctions( span, u, p, U ) {
const N = []; const left = []; const right = []; N[ 0 ] = 1.0;
for ( let j = 1; j <= p; ++ j ) {
left[ j ] = u - U[ span + 1 - j ]; right[ j ] = U[ span + j ] - u;
let saved = 0.0;
for ( let r = 0; r < j; ++ r ) {
const rv = right[ r + 1 ]; const lv = left[ j - r ]; const temp = N[ r ] / ( rv + lv ); N[ r ] = saved + rv * temp; saved = lv * temp;
}
N[ j ] = saved;
}
return N;
}
/*Calculate B-Spline curve points. See The NURBS Book, page 82, algorithm A3.1.
p : degree of B-SplineU : knot vectorP : control points (x, y, z, w)u : parametric point
returns point for given u*/function calcBSplinePoint( p, U, P, u ) {
const span = findSpan( p, u, U ); const N = calcBasisFunctions( span, u, p, U ); const C = new Vector4( 0, 0, 0, 0 );
for ( let j = 0; j <= p; ++ j ) {
const point = P[ span - p + j ]; const Nj = N[ j ]; const wNj = point.w * Nj; C.x += point.x * wNj; C.y += point.y * wNj; C.z += point.z * wNj; C.w += point.w * Nj;
}
return C;
}
/*Calculate basis functions derivatives. See The NURBS Book, page 72, algorithm A2.3.
span : span in which u liesu : parametric pointp : degreen : number of derivatives to calculateU : knot vector
returns array[n+1][p+1] with basis functions derivatives*/function calcBasisFunctionDerivatives( span, u, p, n, U ) {
const zeroArr = []; for ( let i = 0; i <= p; ++ i ) zeroArr[ i ] = 0.0;
const ders = [];
for ( let i = 0; i <= n; ++ i ) ders[ i ] = zeroArr.slice( 0 );
const ndu = [];
for ( let i = 0; i <= p; ++ i ) ndu[ i ] = zeroArr.slice( 0 );
ndu[ 0 ][ 0 ] = 1.0;
const left = zeroArr.slice( 0 ); const right = zeroArr.slice( 0 );
for ( let j = 1; j <= p; ++ j ) {
left[ j ] = u - U[ span + 1 - j ]; right[ j ] = U[ span + j ] - u;
let saved = 0.0;
for ( let r = 0; r < j; ++ r ) {
const rv = right[ r + 1 ]; const lv = left[ j - r ]; ndu[ j ][ r ] = rv + lv;
const temp = ndu[ r ][ j - 1 ] / ndu[ j ][ r ]; ndu[ r ][ j ] = saved + rv * temp; saved = lv * temp;
}
ndu[ j ][ j ] = saved;
}
for ( let j = 0; j <= p; ++ j ) {
ders[ 0 ][ j ] = ndu[ j ][ p ];
}
for ( let r = 0; r <= p; ++ r ) {
let s1 = 0; let s2 = 1;
const a = []; for ( let i = 0; i <= p; ++ i ) {
a[ i ] = zeroArr.slice( 0 );
}
a[ 0 ][ 0 ] = 1.0;
for ( let k = 1; k <= n; ++ k ) {
let d = 0.0; const rk = r - k; const pk = p - k;
if ( r >= k ) {
a[ s2 ][ 0 ] = a[ s1 ][ 0 ] / ndu[ pk + 1 ][ rk ]; d = a[ s2 ][ 0 ] * ndu[ rk ][ pk ];
}
const j1 = ( rk >= - 1 ) ? 1 : - rk; const j2 = ( r - 1 <= pk ) ? k - 1 : p - r;
for ( let j = j1; j <= j2; ++ j ) {
a[ s2 ][ j ] = ( a[ s1 ][ j ] - a[ s1 ][ j - 1 ] ) / ndu[ pk + 1 ][ rk + j ]; d += a[ s2 ][ j ] * ndu[ rk + j ][ pk ];
}
if ( r <= pk ) {
a[ s2 ][ k ] = - a[ s1 ][ k - 1 ] / ndu[ pk + 1 ][ r ]; d += a[ s2 ][ k ] * ndu[ r ][ pk ];
}
ders[ k ][ r ] = d;
const j = s1; s1 = s2; s2 = j;
}
}
let r = p;
for ( let k = 1; k <= n; ++ k ) {
for ( let j = 0; j <= p; ++ j ) {
ders[ k ][ j ] *= r;
}
r *= p - k;
}
return ders;
}
/* Calculate derivatives of a B-Spline. See The NURBS Book, page 93, algorithm A3.2.
p : degree U : knot vector P : control points u : Parametric points nd : number of derivatives
returns array[d+1] with derivatives */function calcBSplineDerivatives( p, U, P, u, nd ) {
const du = nd < p ? nd : p; const CK = []; const span = findSpan( p, u, U ); const nders = calcBasisFunctionDerivatives( span, u, p, du, U ); const Pw = [];
for ( let i = 0; i < P.length; ++ i ) {
const point = P[ i ].clone(); const w = point.w;
point.x *= w; point.y *= w; point.z *= w;
Pw[ i ] = point;
}
for ( let k = 0; k <= du; ++ k ) {
const point = Pw[ span - p ].clone().multiplyScalar( nders[ k ][ 0 ] );
for ( let j = 1; j <= p; ++ j ) {
point.add( Pw[ span - p + j ].clone().multiplyScalar( nders[ k ][ j ] ) );
}
CK[ k ] = point;
}
for ( let k = du + 1; k <= nd + 1; ++ k ) {
CK[ k ] = new Vector4( 0, 0, 0 );
}
return CK;
}
/*Calculate "K over I"
returns k!/(i!(k-i)!)*/function calcKoverI( k, i ) {
let nom = 1;
for ( let j = 2; j <= k; ++ j ) {
nom *= j;
}
let denom = 1;
for ( let j = 2; j <= i; ++ j ) {
denom *= j;
}
for ( let j = 2; j <= k - i; ++ j ) {
denom *= j;
}
return nom / denom;
}
/*Calculate derivatives (0-nd) of rational curve. See The NURBS Book, page 127, algorithm A4.2.
Pders : result of function calcBSplineDerivatives
returns array with derivatives for rational curve.*/function calcRationalCurveDerivatives( Pders ) {
const nd = Pders.length; const Aders = []; const wders = [];
for ( let i = 0; i < nd; ++ i ) {
const point = Pders[ i ]; Aders[ i ] = new Vector3( point.x, point.y, point.z ); wders[ i ] = point.w;
}
const CK = [];
for ( let k = 0; k < nd; ++ k ) {
const v = Aders[ k ].clone();
for ( let i = 1; i <= k; ++ i ) {
v.sub( CK[ k - i ].clone().multiplyScalar( calcKoverI( k, i ) * wders[ i ] ) );
}
CK[ k ] = v.divideScalar( wders[ 0 ] );
}
return CK;
}
/*Calculate NURBS curve derivatives. See The NURBS Book, page 127, algorithm A4.2.
p : degreeU : knot vectorP : control points in homogeneous spaceu : parametric pointsnd : number of derivatives
returns array with derivatives.*/function calcNURBSDerivatives( p, U, P, u, nd ) {
const Pders = calcBSplineDerivatives( p, U, P, u, nd ); return calcRationalCurveDerivatives( Pders );
}
/*Calculate rational B-Spline surface point. See The NURBS Book, page 134, algorithm A4.3.
p1, p2 : degrees of B-Spline surfaceU1, U2 : knot vectorsP : control points (x, y, z, w)u, v : parametric values
returns point for given (u, v)*/function calcSurfacePoint( p, q, U, V, P, u, v, target ) {
const uspan = findSpan( p, u, U ); const vspan = findSpan( q, v, V ); const Nu = calcBasisFunctions( uspan, u, p, U ); const Nv = calcBasisFunctions( vspan, v, q, V ); const temp = [];
for ( let l = 0; l <= q; ++ l ) {
temp[ l ] = new Vector4( 0, 0, 0, 0 ); for ( let k = 0; k <= p; ++ k ) {
const point = P[ uspan - p + k ][ vspan - q + l ].clone(); const w = point.w; point.x *= w; point.y *= w; point.z *= w; temp[ l ].add( point.multiplyScalar( Nu[ k ] ) );
}
}
const Sw = new Vector4( 0, 0, 0, 0 ); for ( let l = 0; l <= q; ++ l ) {
Sw.add( temp[ l ].multiplyScalar( Nv[ l ] ) );
}
Sw.divideScalar( Sw.w ); target.set( Sw.x, Sw.y, Sw.z );
}
export { findSpan, calcBasisFunctions, calcBSplinePoint, calcBasisFunctionDerivatives, calcBSplineDerivatives, calcKoverI, calcRationalCurveDerivatives, calcNURBSDerivatives, calcSurfacePoint,};12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474/*!fflate - fast JavaScript compression/decompression<https://101arrowz.github.io/fflate>Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSEversion 0.6.9*/
// DEFLATE is a complex format; to read this code, you should probably check the RFC first:// https://tools.ietf.org/html/rfc1951// You may also wish to take a look at the guide I made about this program:// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad// Some of the following code is similar to that of UZIP.js:// https://github.com/photopea/UZIP.js// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint// is better for memory in most engines (I *think*).var ch2 = {};var durl = function (c) { return URL.createObjectURL(new Blob([c], { type: 'text/javascript' })); };var cwk = function (u) { return new Worker(u); };try { URL.revokeObjectURL(durl(''));}catch (e) { // We're in Deno or a very old browser durl = function (c) { return 'data:application/javascript;charset=UTF-8,' + encodeURI(c); }; // If Deno, this is necessary; if not, this changes nothing cwk = function (u) { return new Worker(u, { type: 'module' }); };}var wk = (function (c, id, msg, transfer, cb) { var w = cwk(ch2[id] || (ch2[id] = durl(c))); w.onerror = function (e) { return cb(e.error, null); }; w.onmessage = function (e) { return cb(null, e.data); }; w.postMessage(msg, transfer); return w;});
// aliases for shorter compressed code (most minifers don't do this)var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;// fixed length extra bitsvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);// fixed distance extra bits// see fleb notevar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);// code length index mapvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);// get base, reverse index map from extra bitsvar freb = function (eb, start) { var b = new u16(31); for (var i = 0; i < 31; ++i) { b[i] = start += 1 << eb[i - 1]; } // numbers here are at max 18 bits var r = new u32(b[30]); for (var i = 1; i < 30; ++i) { for (var j = b[i]; j < b[i + 1]; ++j) { r[j] = ((j - b[i]) << 5) | i; } } return [b, r];};var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];// we can ignore the fact that the other numbers are wrong; they never happen anywayfl[28] = 258, revfl[258] = 28;var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];// map of value to reverse (assuming 16 bits)var rev = new u16(32768);for (var i = 0; i < 32768; ++i) { // reverse table algorithm from SO var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1); x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2); x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4); rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;}// create huffman tree from u8 "map": index -> code length for code index// mb (max bits) must be at most 15// TODO: optimize/split up?var hMap = (function (cd, mb, r) { var s = cd.length; // index var i = 0; // u16 "map": index -> # of codes with bit length = index var l = new u16(mb); // length of cd must be 288 (total # of codes) for (; i < s; ++i) ++l[cd[i] - 1]; // u16 "map": index -> minimum code for bit length = index var le = new u16(mb); for (i = 0; i < mb; ++i) { le[i] = (le[i - 1] + l[i - 1]) << 1; } var co; if (r) { // u16 "map": index -> number of actual bits, symbol for code co = new u16(1 << mb); // bits to remove for reverser var rvb = 15 - mb; for (i = 0; i < s; ++i) { // ignore 0 lengths if (cd[i]) { // num encoding both symbol and bits read var sv = (i << 4) | cd[i]; // free bits var r_1 = mb - cd[i]; // start value var v = le[cd[i] - 1]++ << r_1; // m is end value for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { // every 16 bit value starting with the code yields the same result co[rev[v] >>> rvb] = sv; } } } } else { co = new u16(s); for (i = 0; i < s; ++i) { if (cd[i]) { co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]); } } } return co;});// fixed length treevar flt = new u8(288);for (var i = 0; i < 144; ++i) flt[i] = 8;for (var i = 144; i < 256; ++i) flt[i] = 9;for (var i = 256; i < 280; ++i) flt[i] = 7;for (var i = 280; i < 288; ++i) flt[i] = 8;// fixed distance treevar fdt = new u8(32);for (var i = 0; i < 32; ++i) fdt[i] = 5;// fixed length mapvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);// fixed distance mapvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);// find max of arrayvar max = function (a) { var m = a[0]; for (var i = 1; i < a.length; ++i) { if (a[i] > m) m = a[i]; } return m;};// read d, starting at bit p and mask with mvar bits = function (d, p, m) { var o = (p / 8) | 0; return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;};// read d, starting at bit p continuing for at least 16 bitsvar bits16 = function (d, p) { var o = (p / 8) | 0; return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));};// get end of bytevar shft = function (p) { return ((p / 8) | 0) + (p & 7 && 1); };// typed array slice - allows garbage collector to free original reference,// while being more compatible than .slicevar slc = function (v, s, e) { if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; // can't use .constructor in case user-supplied var n = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s); n.set(v.subarray(s, e)); return n;};// expands raw DEFLATE datavar inflt = function (dat, buf, st) { // source length var sl = dat.length; if (!sl || (st && !st.l && sl < 5)) return buf || new u8(0); // have to estimate size var noBuf = !buf || st; // no state var noSt = !st || st.i; if (!st) st = {}; // Assumes roughly 33% compression ratio average if (!buf) buf = new u8(sl * 3); // ensure buffer can fit at least l elements var cbuf = function (l) { var bl = buf.length; // need to increase size to fit if (l > bl) { // Double or set to necessary, whichever is greater var nbuf = new u8(Math.max(bl * 2, l)); nbuf.set(buf); buf = nbuf; } }; // last chunk bitpos bytes var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; // total bits var tbts = sl * 8; do { if (!lm) { // BFINAL - this is only 1 when last chunk is next st.f = final = bits(dat, pos, 1); // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman var type = bits(dat, pos + 1, 3); pos += 3; if (!type) { // go to end of byte boundary var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; if (t > sl) { if (noSt) throw 'unexpected EOF'; break; } // ensure size if (noBuf) cbuf(bt + l); // Copy over uncompressed data buf.set(dat.subarray(s, t), bt); // Get new bitpos, update byte count st.b = bt += l, st.p = pos = t * 8; continue; } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5; else if (type == 2) { // literal lengths var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; var tl = hLit + bits(dat, pos + 5, 31) + 1; pos += 14; // length+distance tree var ldt = new u8(tl); // code length tree var clt = new u8(19); for (var i = 0; i < hcLen; ++i) { // use index map to get real code clt[clim[i]] = bits(dat, pos + i * 3, 7); } pos += hcLen * 3; // code lengths bits var clb = max(clt), clbmsk = (1 << clb) - 1; // code lengths map var clm = hMap(clt, clb, 1); for (var i = 0; i < tl;) { var r = clm[bits(dat, pos, clbmsk)]; // bits read pos += r & 15; // symbol var s = r >>> 4; // code length to copy if (s < 16) { ldt[i++] = s; } else { // copy count var c = 0, n = 0; if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3; else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7; while (n--) ldt[i++] = c; } } // length tree distance tree var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); // max length bits lbt = max(lt); // max dist bits dbt = max(dt); lm = hMap(lt, lbt, 1); dm = hMap(dt, dbt, 1); } else throw 'invalid block type'; if (pos > tbts) { if (noSt) throw 'unexpected EOF'; break; } } // Make sure the buffer can hold this + the largest possible addition // Maximum chunk size (practically, theoretically infinite) is 2^17; if (noBuf) cbuf(bt + 131072); var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; var lpos = pos; for (;; lpos = pos) { // bits read, code var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; pos += c & 15; if (pos > tbts) { if (noSt) throw 'unexpected EOF'; break; } if (!c) throw 'invalid length/literal'; if (sym < 256) buf[bt++] = sym; else if (sym == 256) { lpos = pos, lm = null; break; } else { var add = sym - 254; // no extra bits needed if less if (sym > 264) { // index var i = sym - 257, b = fleb[i]; add = bits(dat, pos, (1 << b) - 1) + fl[i]; pos += b; } // dist var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; if (!d) throw 'invalid distance'; pos += d & 15; var dt = fd[dsym]; if (dsym > 3) { var b = fdeb[dsym]; dt += bits16(dat, pos) & ((1 << b) - 1), pos += b; } if (pos > tbts) { if (noSt) throw 'unexpected EOF'; break; } if (noBuf) cbuf(bt + 131072); var end = bt + add; for (; bt < end; bt += 4) { buf[bt] = buf[bt - dt]; buf[bt + 1] = buf[bt + 1 - dt]; buf[bt + 2] = buf[bt + 2 - dt]; buf[bt + 3] = buf[bt + 3 - dt]; } bt = end; } } st.l = lm, st.p = lpos, st.b = bt; if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt; } while (!final); return bt == buf.length ? buf : slc(buf, 0, bt);};// starting at p, write the minimum number of bits that can hold v to dvar wbits = function (d, p, v) { v <<= p & 7; var o = (p / 8) | 0; d[o] |= v; d[o + 1] |= v >>> 8;};// starting at p, write the minimum number of bits (>8) that can hold v to dvar wbits16 = function (d, p, v) { v <<= p & 7; var o = (p / 8) | 0; d[o] |= v; d[o + 1] |= v >>> 8; d[o + 2] |= v >>> 16;};// creates code lengths from a frequency tablevar hTree = function (d, mb) { // Need extra info to make a tree var t = []; for (var i = 0; i < d.length; ++i) { if (d[i]) t.push({ s: i, f: d[i] }); } var s = t.length; var t2 = t.slice(); if (!s) return [et, 0]; if (s == 1) { var v = new u8(t[0].s + 1); v[t[0].s] = 1; return [v, 1]; } t.sort(function (a, b) { return a.f - b.f; }); // after i2 reaches last ind, will be stopped // freq must be greater than largest possible number of symbols t.push({ s: -1, f: 25001 }); var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; // efficient algorithm from UZIP.js // i0 is lookbehind, i2 is lookahead - after processing two low-freq // symbols that combined have high freq, will start processing i2 (high-freq, // non-composite) symbols instead // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ while (i1 != s - 1) { l = t[t[i0].f < t[i2].f ? i0++ : i2++]; r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; } var maxSym = t2[0].s; for (var i = 1; i < s; ++i) { if (t2[i].s > maxSym) maxSym = t2[i].s; } // code lengths var tr = new u16(maxSym + 1); // max bits in tree var mbt = ln(t[i1 - 1], tr, 0); if (mbt > mb) { // more algorithms from UZIP.js // TODO: find out how this code works (debt) // ind debt var i = 0, dt = 0; // left cost var lft = mbt - mb, cst = 1 << lft; t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); for (; i < s; ++i) { var i2_1 = t2[i].s; if (tr[i2_1] > mb) { dt += cst - (1 << (mbt - tr[i2_1])); tr[i2_1] = mb; } else break; } dt >>>= lft; while (dt > 0) { var i2_2 = t2[i].s; if (tr[i2_2] < mb) dt -= 1 << (mb - tr[i2_2]++ - 1); else ++i; } for (; i >= 0 && dt; --i) { var i2_3 = t2[i].s; if (tr[i2_3] == mb) { --tr[i2_3]; ++dt; } } mbt = mb; } return [new u8(tr), mbt];};// get the max length and assign length codesvar ln = function (n, l, d) { return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : (l[n.s] = d);};// length codes generationvar lc = function (c) { var s = c.length; // Note that the semicolon was intentional while (s && !c[--s]) ; var cl = new u16(++s); // ind num streak var cli = 0, cln = c[0], cls = 1; var w = function (v) { cl[cli++] = v; }; for (var i = 1; i <= s; ++i) { if (c[i] == cln && i != s) ++cls; else { if (!cln && cls > 2) { for (; cls > 138; cls -= 138) w(32754); if (cls > 2) { w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); cls = 0; } } else if (cls > 3) { w(cln), --cls; for (; cls > 6; cls -= 6) w(8304); if (cls > 2) w(((cls - 3) << 5) | 8208), cls = 0; } while (cls--) w(cln); cls = 1; cln = c[i]; } } return [cl.subarray(0, cli), s];};// calculate the length of output from tree, code lengthsvar clen = function (cf, cl) { var l = 0; for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i]; return l;};// writes a fixed block// returns the new bit posvar wfblk = function (out, pos, dat) { // no need to write 00 as type: TypedArray defaults to 0 var s = dat.length; var o = shft(pos + 2); out[o] = s & 255; out[o + 1] = s >>> 8; out[o + 2] = out[o] ^ 255; out[o + 3] = out[o + 1] ^ 255; for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i]; return (o + 4 + s) * 8;};// writes a blockvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { wbits(out, p++, final); ++lf[256]; var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1]; var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1]; var _c = lc(dlt), lclt = _c[0], nlc = _c[1]; var _d = lc(ddt), lcdt = _d[0], ndc = _d[1]; var lcfreq = new u16(19); for (var i = 0; i < lclt.length; ++i) lcfreq[lclt[i] & 31]++; for (var i = 0; i < lcdt.length; ++i) lcfreq[lcdt[i] & 31]++; var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1]; var nlcc = 19; for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) ; var flen = (bl + 5) << 3; var ftlen = clen(lf, flt) + clen(df, fdt) + eb; var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); if (flen <= ftlen && flen <= dtlen) return wfblk(out, p, dat.subarray(bs, bs + bl)); var lm, ll, dm, dl; wbits(out, p, 1 + (dtlen < ftlen)), p += 2; if (dtlen < ftlen) { lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; var llm = hMap(lct, mlcb, 0); wbits(out, p, nlc - 257); wbits(out, p + 5, ndc - 1); wbits(out, p + 10, nlcc - 4); p += 14; for (var i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]); p += 3 * nlcc; var lcts = [lclt, lcdt]; for (var it = 0; it < 2; ++it) { var clct = lcts[it]; for (var i = 0; i < clct.length; ++i) { var len = clct[i] & 31; wbits(out, p, llm[len]), p += lct[len]; if (len > 15) wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12; } } } else { lm = flm, ll = flt, dm = fdm, dl = fdt; } for (var i = 0; i < li; ++i) { if (syms[i] > 255) { var len = (syms[i] >>> 18) & 31; wbits16(out, p, lm[len + 257]), p += ll[len + 257]; if (len > 7) wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len]; var dst = syms[i] & 31; wbits16(out, p, dm[dst]), p += dl[dst]; if (dst > 3) wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst]; } else { wbits16(out, p, lm[syms[i]]), p += ll[syms[i]]; } } wbits16(out, p, lm[256]); return p + ll[256];};// deflate options (nice << 13) | chainvar deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);// emptyvar et = /*#__PURE__*/ new u8(0);// compresses data into a raw DEFLATE buffervar dflt = function (dat, lvl, plvl, pre, post, lst) { var s = dat.length; var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); // writing to this writes to the output buffer var w = o.subarray(pre, o.length - post); var pos = 0; if (!lvl || s < 8) { for (var i = 0; i <= s; i += 65535) { // end var e = i + 65535; if (e < s) { // write full block pos = wfblk(w, pos, dat.subarray(i, e)); } else { // write final block w[i] = lst; pos = wfblk(w, pos, dat.subarray(i, s)); } } } else { var opt = deo[lvl - 1]; var n = opt >>> 13, c = opt & 8191; var msk_1 = (1 << plvl) - 1; // prev 2-byte val map curr 2-byte val map var prev = new u16(32768), head = new u16(msk_1 + 1); var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; // 24576 is an arbitrary number of maximum symbols per block // 424 buffer for last block var syms = new u32(25000); // length/literal freq distance freq var lf = new u16(288), df = new u16(32); // l/lcnt exbits index l/lind waitdx bitpos var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; for (; i < s; ++i) { // hash value // deopt when i > s - 3 - at end, deopt acceptable var hv = hsh(i); // index mod 32768 previous index mod var imod = i & 32767, pimod = head[hv]; prev[imod] = pimod; head[hv] = imod; // We always should modify head and prev, but only add symbols if // this data is not yet processed ("wait" for wait index) if (wi <= i) { // bytes remaining var rem = s - i; if ((lc_1 > 7000 || li > 24576) && rem > 423) { pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); li = lc_1 = eb = 0, bs = i; for (var j = 0; j < 286; ++j) lf[j] = 0; for (var j = 0; j < 30; ++j) df[j] = 0; } // len dist chain var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767; if (rem > 2 && hv == hsh(i - dif)) { var maxn = Math.min(n, rem) - 1; var maxd = Math.min(32767, i); // max possible length // not capped at dif because decompressors implement "rolling" index population var ml = Math.min(258, rem); while (dif <= maxd && --ch_1 && imod != pimod) { if (dat[i + l] == dat[i + l - dif]) { var nl = 0; for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) ; if (nl > l) { l = nl, d = dif; // break out early when we reach "nice" (we are satisfied enough) if (nl > maxn) break; // now, find the rarest 2-byte sequence within this // length of literals and search for that instead. // Much faster than just using the start var mmd = Math.min(dif, nl - 2); var md = 0; for (var j = 0; j < mmd; ++j) { var ti = (i - dif + j + 32768) & 32767; var pti = prev[ti]; var cd = (ti - pti + 32768) & 32767; if (cd > md) md = cd, pimod = ti; } } } // check the previous match imod = pimod, pimod = prev[imod]; dif += (imod - pimod + 32768) & 32767; } } // d will be nonzero only when a match was found if (d) { // store both dist and len data in one Uint32 // Make sure this is recognized as a len/dist with 28th bit (2^28) syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; var lin = revfl[l] & 31, din = revfd[d] & 31; eb += fleb[lin] + fdeb[din]; ++lf[257 + lin]; ++df[din]; wi = i + l; ++lc_1; } else { syms[li++] = dat[i]; ++lf[dat[i]]; } } } pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); // this is the easiest way to avoid needing to maintain state if (!lst && pos & 7) pos = wfblk(w, pos + 1, et); } return slc(o, 0, pre + shft(pos) + post);};// CRC32 tablevar crct = /*#__PURE__*/ (function () { var t = new u32(256); for (var i = 0; i < 256; ++i) { var c = i, k = 9; while (--k) c = ((c & 1) && 0xEDB88320) ^ (c >>> 1); t[i] = c; } return t;})();// CRC32var crc = function () { var c = -1; return { p: function (d) { // closures have awful performance var cr = c; for (var i = 0; i < d.length; ++i) cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); c = cr; }, d: function () { return ~c; } };};// Alder32var adler = function () { var a = 1, b = 0; return { p: function (d) { // closures have awful performance var n = a, m = b; var l = d.length; for (var i = 0; i != l;) { var e = Math.min(i + 2655, l); for (; i < e; ++i) m += n += d[i]; n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); } a = n, b = m; }, d: function () { a %= 65521, b %= 65521; return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8); } };};;// deflate with optsvar dopt = function (dat, opt, pre, post, st) { return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);};// Walmart object spreadvar mrg = function (a, b) { var o = {}; for (var k in a) o[k] = a[k]; for (var k in b) o[k] = b[k]; return o;};// worker clone// This is possibly the craziest part of the entire codebase, despite how simple it may seem.// The only parameter to this function is a closure that returns an array of variables outside of the function scope.// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.// This took me three weeks to figure out how to do.var wcln = function (fn, fnStr, td) { var dt = fn(); var st = fn.toString(); var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/ /g, '').split(','); for (var i = 0; i < dt.length; ++i) { var v = dt[i], k = ks[i]; if (typeof v == 'function') { fnStr += ';' + k + '='; var st_1 = v.toString(); if (v.prototype) { // for global objects if (st_1.indexOf('[native code]') != -1) { var spInd = st_1.indexOf(' ', 8) + 1; fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); } else { fnStr += st_1; for (var t in v.prototype) fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); } } else fnStr += st_1; } else td[k] = v; } return [fnStr, td];};var ch = [];// clone bufsvar cbfs = function (v) { var tl = []; for (var k in v) { if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32) tl.push((v[k] = new v[k].constructor(v[k])).buffer); } return tl;};// use a worker to execute codevar wrkr = function (fns, init, id, cb) { var _a; if (!ch[id]) { var fnStr = '', td_1 = {}, m = fns.length - 1; for (var i = 0; i < m; ++i) _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1]; ch[id] = wcln(fns[m], fnStr, td_1); } var td = mrg({}, ch[id][1]); return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);};// base async inflate fnvar bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; };var bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };// gzip extravar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };// gunzip extravar guze = function () { return [gzs, gzl]; };// zlib extravar zle = function () { return [zlh, wbytes, adler]; };// unzlib extravar zule = function () { return [zlv]; };// post bufvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };// get u8var gu8 = function (o) { return o && o.size && new u8(o.size); };// async helpervar cbify = function (dat, opts, fns, init, id, cb) { var w = wrkr(fns, init, id, function (err, dat) { w.terminate(); cb(err, dat); }); w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); return function () { w.terminate(); };};// auto streamvar astrm = function (strm) { strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; return function (ev) { return strm.push(ev.data[0], ev.data[1]); };};// async stream attachvar astrmify = function (fns, strm, opts, init, id) { var t; var w = wrkr(fns, init, id, function (err, dat) { if (err) w.terminate(), strm.ondata.call(strm, err); else { if (dat[1]) w.terminate(); strm.ondata.call(strm, err, dat[0], dat[1]); } }); w.postMessage(opts); strm.push = function (d, f) { if (t) throw 'stream finished'; if (!strm.ondata) throw 'no stream handler'; w.postMessage([d, t = f], [d.buffer]); }; strm.terminate = function () { w.terminate(); };};// read 2 bytesvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };// read 4 bytesvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };// write bytesvar wbytes = function (d, b, v) { for (; v; ++b) d[b] = v, v >>>= 8;};// gzip headervar gzh = function (c, o) { var fn = o.filename; c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix if (o.mtime != 0) wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); if (fn) { c[3] = 8; for (var i = 0; i <= fn.length; ++i) c[i + 10] = fn.charCodeAt(i); }};// gzip footer: -8 to -4 = CRC, -4 to -0 is length// gzip startvar gzs = function (d) { if (d[0] != 31 || d[1] != 139 || d[2] != 8) throw 'invalid gzip data'; var flg = d[3]; var st = 10; if (flg & 4) st += d[10] | (d[11] << 8) + 2; for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) ; return st + (flg & 2);};// gzip lengthvar gzl = function (d) { var l = d.length; return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;};// gzip header lengthvar gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };// zlib headervar zlh = function (c, o) { var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);};// zlib validvar zlv = function (d) { if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) throw 'invalid zlib data'; if (d[1] & 32) throw 'invalid zlib data: preset dictionaries not supported';};function AsyncCmpStrm(opts, cb) { if (!cb && typeof opts == 'function') cb = opts, opts = {}; this.ondata = cb; return opts;}// zlib footer: -4 to -0 is Adler32/** * Streaming DEFLATE compression */var Deflate = /*#__PURE__*/ (function () { function Deflate(opts, cb) { if (!cb && typeof opts == 'function') cb = opts, opts = {}; this.ondata = cb; this.o = opts || {}; } Deflate.prototype.p = function (c, f) { this.ondata(dopt(c, this.o, 0, 0, !f), f); }; /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ Deflate.prototype.push = function (chunk, final) { if (this.d) throw 'stream finished'; if (!this.ondata) throw 'no stream handler'; this.d = final; this.p(chunk, final || false); }; return Deflate;}());export { Deflate };/** * Asynchronous streaming DEFLATE compression */var AsyncDeflate = /*#__PURE__*/ (function () { function AsyncDeflate(opts, cb) { astrmify([ bDflt, function () { return [astrm, Deflate]; } ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) { var strm = new Deflate(ev.data); onmessage = astrm(strm); }, 6); } return AsyncDeflate;}());export { AsyncDeflate };export function deflate(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return cbify(data, opts, [ bDflt, ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);}/** * Compresses data with DEFLATE without any wrapper * @param data The data to compress * @param opts The compression options * @returns The deflated version of the data */export function deflateSync(data, opts) { return dopt(data, opts || {}, 0, 0);}/** * Streaming DEFLATE decompression */var Inflate = /*#__PURE__*/ (function () { /** * Creates an inflation stream * @param cb The callback to call whenever data is inflated */ function Inflate(cb) { this.s = {}; this.p = new u8(0); this.ondata = cb; } Inflate.prototype.e = function (c) { if (this.d) throw 'stream finished'; if (!this.ondata) throw 'no stream handler'; var l = this.p.length; var n = new u8(l + c.length); n.set(this.p), n.set(c, l), this.p = n; }; Inflate.prototype.c = function (final) { this.d = this.s.i = final || false; var bts = this.s.b; var dt = inflt(this.p, this.o, this.s); this.ondata(slc(dt, bts, this.s.b), this.d); this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; }; /** * Pushes a chunk to be inflated * @param chunk The chunk to push * @param final Whether this is the final chunk */ Inflate.prototype.push = function (chunk, final) { this.e(chunk), this.c(final); }; return Inflate;}());export { Inflate };/** * Asynchronous streaming DEFLATE decompression */var AsyncInflate = /*#__PURE__*/ (function () { /** * Creates an asynchronous inflation stream * @param cb The callback to call whenever data is deflated */ function AsyncInflate(cb) { this.ondata = cb; astrmify([ bInflt, function () { return [astrm, Inflate]; } ], this, 0, function () { var strm = new Inflate(); onmessage = astrm(strm); }, 7); } return AsyncInflate;}());export { AsyncInflate };export function inflate(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return cbify(data, opts, [ bInflt ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);}/** * Expands DEFLATE data with no wrapper * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */export function inflateSync(data, out) { return inflt(data, out);}// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize./** * Streaming GZIP compression */var Gzip = /*#__PURE__*/ (function () { function Gzip(opts, cb) { this.c = crc(); this.l = 0; this.v = 1; Deflate.call(this, opts, cb); } /** * Pushes a chunk to be GZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ Gzip.prototype.push = function (chunk, final) { Deflate.prototype.push.call(this, chunk, final); }; Gzip.prototype.p = function (c, f) { this.c.p(c); this.l += c.length; var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f); if (this.v) gzh(raw, this.o), this.v = 0; if (f) wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); this.ondata(raw, f); }; return Gzip;}());export { Gzip };/** * Asynchronous streaming GZIP compression */var AsyncGzip = /*#__PURE__*/ (function () { function AsyncGzip(opts, cb) { astrmify([ bDflt, gze, function () { return [astrm, Deflate, Gzip]; } ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) { var strm = new Gzip(ev.data); onmessage = astrm(strm); }, 8); } return AsyncGzip;}());export { AsyncGzip };export function gzip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return cbify(data, opts, [ bDflt, gze, function () { return [gzipSync]; } ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);}/** * Compresses data with GZIP * @param data The data to compress * @param opts The compression options * @returns The gzipped version of the data */export function gzipSync(data, opts) { if (!opts) opts = {}; var c = crc(), l = data.length; c.p(data); var d = dopt(data, opts, gzhl(opts), 8), s = d.length; return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;}/** * Streaming GZIP decompression */var Gunzip = /*#__PURE__*/ (function () { /** * Creates a GUNZIP stream * @param cb The callback to call whenever data is inflated */ function Gunzip(cb) { this.v = 1; Inflate.call(this, cb); } /** * Pushes a chunk to be GUNZIPped * @param chunk The chunk to push * @param final Whether this is the last chunk */ Gunzip.prototype.push = function (chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { var s = this.p.length > 3 ? gzs(this.p) : 4; if (s >= this.p.length && !final) return; this.p = this.p.subarray(s), this.v = 0; } if (final) { if (this.p.length < 8) throw 'invalid gzip stream'; this.p = this.p.subarray(0, -8); } // necessary to prevent TS from using the closure value // This allows for workerization to function correctly Inflate.prototype.c.call(this, final); }; return Gunzip;}());export { Gunzip };/** * Asynchronous streaming GZIP decompression */var AsyncGunzip = /*#__PURE__*/ (function () { /** * Creates an asynchronous GUNZIP stream * @param cb The callback to call whenever data is deflated */ function AsyncGunzip(cb) { this.ondata = cb; astrmify([ bInflt, guze, function () { return [astrm, Inflate, Gunzip]; } ], this, 0, function () { var strm = new Gunzip(); onmessage = astrm(strm); }, 9); } return AsyncGunzip;}());export { AsyncGunzip };export function gunzip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return cbify(data, opts, [ bInflt, guze, function () { return [gunzipSync]; } ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);}/** * Expands GZIP data * @param data The data to decompress * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory. * @returns The decompressed version of the data */export function gunzipSync(data, out) { return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));}/** * Streaming Zlib compression */var Zlib = /*#__PURE__*/ (function () { function Zlib(opts, cb) { this.c = adler(); this.v = 1; Deflate.call(this, opts, cb); } /** * Pushes a chunk to be zlibbed * @param chunk The chunk to push * @param final Whether this is the last chunk */ Zlib.prototype.push = function (chunk, final) { Deflate.prototype.push.call(this, chunk, final); }; Zlib.prototype.p = function (c, f) { this.c.p(c); var raw = dopt(c, this.o, this.v && 2, f && 4, !f); if (this.v) zlh(raw, this.o), this.v = 0; if (f) wbytes(raw, raw.length - 4, this.c.d()); this.ondata(raw, f); }; return Zlib;}());export { Zlib };/** * Asynchronous streaming Zlib compression */var AsyncZlib = /*#__PURE__*/ (function () { function AsyncZlib(opts, cb) { astrmify([ bDflt, zle, function () { return [astrm, Deflate, Zlib]; } ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) { var strm = new Zlib(ev.data); onmessage = astrm(strm); }, 10); } return AsyncZlib;}());export { AsyncZlib };export function zlib(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return cbify(data, opts, [ bDflt, zle, function () { return [zlibSync]; } ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);}/** * Compress data with Zlib * @param data The data to compress * @param opts The compression options * @returns The zlib-compressed version of the data */export function zlibSync(data, opts) { if (!opts) opts = {}; var a = adler(); a.p(data); var d = dopt(data, opts, 2, 4); return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;}/** * Streaming Zlib decompression */var Unzlib = /*#__PURE__*/ (function () { /** * Creates a Zlib decompression stream * @param cb The callback to call whenever data is inflated */ function Unzlib(cb) { this.v = 1; Inflate.call(this, cb); } /** * Pushes a chunk to be unzlibbed * @param chunk The chunk to push * @param final Whether this is the last chunk */ Unzlib.prototype.push = function (chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { if (this.p.length < 2 && !final) return; this.p = this.p.subarray(2), this.v = 0; } if (final) { if (this.p.length < 4) throw 'invalid zlib stream'; this.p = this.p.subarray(0, -4); } // necessary to prevent TS from using the closure value // This allows for workerization to function correctly Inflate.prototype.c.call(this, final); }; return Unzlib;}());export { Unzlib };/** * Asynchronous streaming Zlib decompression */var AsyncUnzlib = /*#__PURE__*/ (function () { /** * Creates an asynchronous Zlib decompression stream * @param cb The callback to call whenever data is deflated */ function AsyncUnzlib(cb) { this.ondata = cb; astrmify([ bInflt, zule, function () { return [astrm, Inflate, Unzlib]; } ], this, 0, function () { var strm = new Unzlib(); onmessage = astrm(strm); }, 11); } return AsyncUnzlib;}());export { AsyncUnzlib };export function unzlib(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return cbify(data, opts, [ bInflt, zule, function () { return [unzlibSync]; } ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);}/** * Expands Zlib data * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */export function unzlibSync(data, out) { return inflt((zlv(data), data.subarray(2, -4)), out);}// Default algorithm for compression (used because having a known output size allows faster decompression)export { gzip as compress, AsyncGzip as AsyncCompress };// Default algorithm for compression (used because having a known output size allows faster decompression)export { gzipSync as compressSync, Gzip as Compress };/** * Streaming GZIP, Zlib, or raw DEFLATE decompression */var Decompress = /*#__PURE__*/ (function () { /** * Creates a decompression stream * @param cb The callback to call whenever data is decompressed */ function Decompress(cb) { this.G = Gunzip; this.I = Inflate; this.Z = Unzlib; this.ondata = cb; } /** * Pushes a chunk to be decompressed * @param chunk The chunk to push * @param final Whether this is the last chunk */ Decompress.prototype.push = function (chunk, final) { if (!this.ondata) throw 'no stream handler'; if (!this.s) { if (this.p && this.p.length) { var n = new u8(this.p.length + chunk.length); n.set(this.p), n.set(chunk, this.p.length); } else this.p = chunk; if (this.p.length > 2) { var _this_1 = this; var cb = function () { _this_1.ondata.apply(_this_1, arguments); }; this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) ? new this.G(cb) : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) ? new this.I(cb) : new this.Z(cb); this.s.push(this.p, final); this.p = null; } } else this.s.push(chunk, final); }; return Decompress;}());export { Decompress };/** * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression */var AsyncDecompress = /*#__PURE__*/ (function () { /** * Creates an asynchronous decompression stream * @param cb The callback to call whenever data is decompressed */ function AsyncDecompress(cb) { this.G = AsyncGunzip; this.I = AsyncInflate; this.Z = AsyncUnzlib; this.ondata = cb; } /** * Pushes a chunk to be decompressed * @param chunk The chunk to push * @param final Whether this is the last chunk */ AsyncDecompress.prototype.push = function (chunk, final) { Decompress.prototype.push.call(this, chunk, final); }; return AsyncDecompress;}());export { AsyncDecompress };export function decompress(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; return (data[0] == 31 && data[1] == 139 && data[2] == 8) ? gunzip(data, opts, cb) : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) ? inflate(data, opts, cb) : unzlib(data, opts, cb);}/** * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format * @param data The data to decompress * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length. * @returns The decompressed version of the data */export function decompressSync(data, out) { return (data[0] == 31 && data[1] == 139 && data[2] == 8) ? gunzipSync(data, out) : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) ? inflateSync(data, out) : unzlibSync(data, out);}// flatten a directory structurevar fltn = function (d, p, t, o) { for (var k in d) { var val = d[k], n = p + k; if (val instanceof u8) t[n] = [val, o]; else if (Array.isArray(val)) t[n] = [val[0], mrg(o, val[1])]; else fltn(val, n + '/', t, o); }};// text encodervar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();// text decodervar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();// text decoder streamvar tds = 0;try { td.decode(et, { stream: true }); tds = 1;}catch (e) { }// decode UTF8var dutf8 = function (d) { for (var r = '', i = 0;;) { var c = d[i++]; var eb = (c > 127) + (c > 223) + (c > 239); if (i + eb > d.length) return [r, slc(d, i - 1)]; if (!eb) r += String.fromCharCode(c); else if (eb == 3) { c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); } else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); }};/** * Streaming UTF-8 decoding */var DecodeUTF8 = /*#__PURE__*/ (function () { /** * Creates a UTF-8 decoding stream * @param cb The callback to call whenever data is decoded */ function DecodeUTF8(cb) { this.ondata = cb; if (tds) this.t = new TextDecoder(); else this.p = et; } /** * Pushes a chunk to be decoded from UTF-8 binary * @param chunk The chunk to push * @param final Whether this is the last chunk */ DecodeUTF8.prototype.push = function (chunk, final) { if (!this.ondata) throw 'no callback'; final = !!final; if (this.t) { this.ondata(this.t.decode(chunk, { stream: true }), final); if (final) { if (this.t.decode().length) throw 'invalid utf-8 data'; this.t = null; } return; } if (!this.p) throw 'stream finished'; var dat = new u8(this.p.length + chunk.length); dat.set(this.p); dat.set(chunk, this.p.length); var _a = dutf8(dat), ch = _a[0], np = _a[1]; if (final) { if (np.length) throw 'invalid utf-8 data'; this.p = null; } else this.p = np; this.ondata(ch, final); }; return DecodeUTF8;}());export { DecodeUTF8 };/** * Streaming UTF-8 encoding */var EncodeUTF8 = /*#__PURE__*/ (function () { /** * Creates a UTF-8 decoding stream * @param cb The callback to call whenever data is encoded */ function EncodeUTF8(cb) { this.ondata = cb; } /** * Pushes a chunk to be encoded to UTF-8 * @param chunk The string data to push * @param final Whether this is the last chunk */ EncodeUTF8.prototype.push = function (chunk, final) { if (!this.ondata) throw 'no callback'; if (this.d) throw 'stream finished'; this.ondata(strToU8(chunk), this.d = final || false); }; return EncodeUTF8;}());export { EncodeUTF8 };/** * Converts a string into a Uint8Array for use with compression/decompression methods * @param str The string to encode * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless decoding a binary string. * @returns The string encoded in UTF-8/Latin-1 binary */export function strToU8(str, latin1) { if (latin1) { var ar_1 = new u8(str.length); for (var i = 0; i < str.length; ++i) ar_1[i] = str.charCodeAt(i); return ar_1; } if (te) return te.encode(str); var l = str.length; var ar = new u8(str.length + (str.length >> 1)); var ai = 0; var w = function (v) { ar[ai++] = v; }; for (var i = 0; i < l; ++i) { if (ai + 5 > ar.length) { var n = new u8(ai + 8 + ((l - i) << 1)); n.set(ar); ar = n; } var c = str.charCodeAt(i); if (c < 128 || latin1) w(c); else if (c < 2048) w(192 | (c >> 6)), w(128 | (c & 63)); else if (c > 55295 && c < 57344) c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); else w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); } return slc(ar, 0, ai);}/** * Converts a Uint8Array to a string * @param dat The data to decode to string * @param latin1 Whether or not to interpret the data as Latin-1. This should * not need to be true unless encoding to binary string. * @returns The original UTF-8/Latin-1 string */export function strFromU8(dat, latin1) { if (latin1) { var r = ''; for (var i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); return r; } else if (td) return td.decode(dat); else { var _a = dutf8(dat), out = _a[0], ext = _a[1]; if (ext.length) throw 'invalid utf-8 data'; return out; }};// deflate bit flagvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };// skip local zip headervar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };// read zip headervar zh = function (d, b, z) { var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20); var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2]; return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];};// read zip64 extra fieldvar z64e = function (d, b) { for (; b2(d, b) != 1; b += 4 + b2(d, b + 2)) ; return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];};// extra field lengthvar exfl = function (ex) { var le = 0; if (ex) { for (var k in ex) { var l = ex[k].length; if (l > 65535) throw 'extra field too long'; le += l + 4; } } return le;};// write zip headervar wzh = function (d, b, f, fn, u, c, ce, co) { var fl = fn.length, ex = f.extra, col = co && co.length; var exl = exfl(ex); wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; if (ce != null) d[b++] = 20, d[b++] = f.os; d[b] = 20, b += 2; // spec compliance? what's that? d[b++] = (f.flag << 1) | (c == null && 8), d[b++] = u && 8; d[b++] = f.compression & 255, d[b++] = f.compression >> 8; var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; if (y < 0 || y > 119) throw 'date not in range 1980-2099'; wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4; if (c != null) { wbytes(d, b, f.crc); wbytes(d, b + 4, c); wbytes(d, b + 8, f.size); } wbytes(d, b + 12, fl); wbytes(d, b + 14, exl), b += 16; if (ce != null) { wbytes(d, b, col); wbytes(d, b + 6, f.attrs); wbytes(d, b + 10, ce), b += 14; } d.set(fn, b); b += fl; if (exl) { for (var k in ex) { var exf = ex[k], l = exf.length; wbytes(d, b, +k); wbytes(d, b + 2, l); d.set(exf, b + 4), b += 4 + l; } } if (col) d.set(co, b), b += col; return b;};// write zip footer (end of central directory)var wzf = function (o, b, c, d, e) { wbytes(o, b, 0x6054B50); // skip disk wbytes(o, b + 8, c); wbytes(o, b + 10, c); wbytes(o, b + 12, d); wbytes(o, b + 16, e);};/** * A pass-through stream to keep data uncompressed in a ZIP archive. */var ZipPassThrough = /*#__PURE__*/ (function () { /** * Creates a pass-through stream that can be added to ZIP archives * @param filename The filename to associate with this data stream */ function ZipPassThrough(filename) { this.filename = filename; this.c = crc(); this.size = 0; this.compression = 0; } /** * Processes a chunk and pushes to the output stream. You can override this * method in a subclass for custom behavior, but by default this passes * the data through. You must call this.ondata(err, chunk, final) at some * point in this method. * @param chunk The chunk to process * @param final Whether this is the last chunk */ ZipPassThrough.prototype.process = function (chunk, final) { this.ondata(null, chunk, final); }; /** * Pushes a chunk to be added. If you are subclassing this with a custom * compression algorithm, note that you must push data from the source * file only, pre-compression. * @param chunk The chunk to push * @param final Whether this is the last chunk */ ZipPassThrough.prototype.push = function (chunk, final) { if (!this.ondata) throw 'no callback - add to ZIP archive before pushing'; this.c.p(chunk); this.size += chunk.length; if (final) this.crc = this.c.d(); this.process(chunk, final || false); }; return ZipPassThrough;}());export { ZipPassThrough };// I don't extend because TypeScript extension adds 1kB of runtime bloat/** * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate * for better performance */var ZipDeflate = /*#__PURE__*/ (function () { /** * Creates a DEFLATE stream that can be added to ZIP archives * @param filename The filename to associate with this data stream * @param opts The compression options */ function ZipDeflate(filename, opts) { var _this_1 = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new Deflate(opts, function (dat, final) { _this_1.ondata(null, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); } ZipDeflate.prototype.process = function (chunk, final) { try { this.d.push(chunk, final); } catch (e) { this.ondata(e, null, final); } }; /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ ZipDeflate.prototype.push = function (chunk, final) { ZipPassThrough.prototype.push.call(this, chunk, final); }; return ZipDeflate;}());export { ZipDeflate };/** * Asynchronous streaming DEFLATE compression for ZIP archives */var AsyncZipDeflate = /*#__PURE__*/ (function () { /** * Creates a DEFLATE stream that can be added to ZIP archives * @param filename The filename to associate with this data stream * @param opts The compression options */ function AsyncZipDeflate(filename, opts) { var _this_1 = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new AsyncDeflate(opts, function (err, dat, final) { _this_1.ondata(err, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); this.terminate = this.d.terminate; } AsyncZipDeflate.prototype.process = function (chunk, final) { this.d.push(chunk, final); }; /** * Pushes a chunk to be deflated * @param chunk The chunk to push * @param final Whether this is the last chunk */ AsyncZipDeflate.prototype.push = function (chunk, final) { ZipPassThrough.prototype.push.call(this, chunk, final); }; return AsyncZipDeflate;}());export { AsyncZipDeflate };// TODO: Better tree shaking/** * A zippable archive to which files can incrementally be added */var Zip = /*#__PURE__*/ (function () { /** * Creates an empty ZIP archive to which files can be added * @param cb The callback to call whenever data for the generated ZIP archive * is available */ function Zip(cb) { this.ondata = cb; this.u = []; this.d = 1; } /** * Adds a file to the ZIP archive * @param file The file stream to add */ Zip.prototype.add = function (file) { var _this_1 = this; if (this.d & 2) throw 'stream finished'; var f = strToU8(file.filename), fl = f.length; var com = file.comment, o = com && strToU8(com); var u = fl != file.filename.length || (o && (com.length != o.length)); var hl = fl + exfl(file.extra) + 30; if (fl > 65535) throw 'filename too long'; var header = new u8(hl); wzh(header, 0, file, f, u); var chks = [header]; var pAll = function () { for (var _i = 0, chks_1 = chks; _i < chks_1.length; _i++) { var chk = chks_1[_i]; _this_1.ondata(null, chk, false); } chks = []; }; var tr = this.d; this.d = 0; var ind = this.u.length; var uf = mrg(file, { f: f, u: u, o: o, t: function () { if (file.terminate) file.terminate(); }, r: function () { pAll(); if (tr) { var nxt = _this_1.u[ind + 1]; if (nxt) nxt.r(); else _this_1.d = 1; } tr = 1; } }); var cl = 0; file.ondata = function (err, dat, final) { if (err) { _this_1.ondata(err, dat, final); _this_1.terminate(); } else { cl += dat.length; chks.push(dat); if (final) { var dd = new u8(16); wbytes(dd, 0, 0x8074B50); wbytes(dd, 4, file.crc); wbytes(dd, 8, cl); wbytes(dd, 12, file.size); chks.push(dd); uf.c = cl, uf.b = hl + cl + 16, uf.crc = file.crc, uf.size = file.size; if (tr) uf.r(); tr = 1; } else if (tr) pAll(); } }; this.u.push(uf); }; /** * Ends the process of adding files and prepares to emit the final chunks. * This *must* be called after adding all desired files for the resulting * ZIP file to work properly. */ Zip.prototype.end = function () { var _this_1 = this; if (this.d & 2) { if (this.d & 1) throw 'stream finishing'; throw 'stream finished'; } if (this.d) this.e(); else this.u.push({ r: function () { if (!(_this_1.d & 1)) return; _this_1.u.splice(-1, 1); _this_1.e(); }, t: function () { } }); this.d = 3; }; Zip.prototype.e = function () { var bt = 0, l = 0, tl = 0; for (var _i = 0, _a = this.u; _i < _a.length; _i++) { var f = _a[_i]; tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); } var out = new u8(tl + 22); for (var _b = 0, _c = this.u; _b < _c.length; _b++) { var f = _c[_b]; wzh(out, bt, f, f.f, f.u, f.c, l, f.o); bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; } wzf(out, bt, this.u.length, tl, l); this.ondata(null, out, true); this.d = 2; }; /** * A method to terminate any internal workers used by the stream. Subsequent * calls to add() will fail. */ Zip.prototype.terminate = function () { for (var _i = 0, _a = this.u; _i < _a.length; _i++) { var f = _a[_i]; f.t(); } this.d = 2; }; return Zip;}());export { Zip };export function zip(data, opts, cb) { if (!cb) cb = opts, opts = {}; if (typeof cb != 'function') throw 'no callback'; var r = {}; fltn(data, '', r, opts); var k = Object.keys(r); var lft = k.length, o = 0, tot = 0; var slft = lft, files = new Array(lft); var term = []; var tAll = function () { for (var i = 0; i < term.length; ++i) term[i](); }; var cbf = function () { var out = new u8(tot + 22), oe = o, cdl = tot - o; tot = 0; for (var i = 0; i < slft; ++i) { var f = files[i]; try { var l = f.c.length; wzh(out, tot, f, f.f, f.u, l); var badd = 30 + f.f.length + exfl(f.extra); var loc = tot + badd; out.set(f.c, loc); wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; } catch (e) { return cb(e, null); } } wzf(out, o, files.length, cdl, oe); cb(null, out); }; if (!lft) cbf(); var _loop_1 = function (i) { var fn = k[i]; var _a = r[fn], file = _a[0], p = _a[1]; var c = crc(), size = file.length; c.p(file); var f = strToU8(fn), s = f.length; var com = p.comment, m = com && strToU8(com), ms = m && m.length; var exl = exfl(p.extra); var compression = p.level == 0 ? 0 : 8; var cbl = function (e, d) { if (e) { tAll(); cb(e, null); } else { var l = d.length; files[i] = mrg(p, { size: size, crc: c.d(), c: d, f: f, m: m, u: s != fn.length || (m && (com.length != ms)), compression: compression }); o += 30 + s + exl + l; tot += 76 + 2 * (s + exl) + (ms || 0) + l; if (!--lft) cbf(); } }; if (s > 65535) cbl('filename too long', null); if (!compression) cbl(null, file); else if (size < 160000) { try { cbl(null, deflateSync(file, p)); } catch (e) { cbl(e, null); } } else term.push(deflate(file, p, cbl)); }; // Cannot use lft because it can decrease for (var i = 0; i < slft; ++i) { _loop_1(i); } return tAll;}/** * Synchronously creates a ZIP file. Prefer using `zip` for better performance * with more than one file. * @param data The directory structure for the ZIP archive * @param opts The main options, merged with per-file options * @returns The generated ZIP archive */export function zipSync(data, opts) { if (!opts) opts = {}; var r = {}; var files = []; fltn(data, '', r, opts); var o = 0; var tot = 0; for (var fn in r) { var _a = r[fn], file = _a[0], p = _a[1]; var compression = p.level == 0 ? 0 : 8; var f = strToU8(fn), s = f.length; var com = p.comment, m = com && strToU8(com), ms = m && m.length; var exl = exfl(p.extra); if (s > 65535) throw 'filename too long'; var d = compression ? deflateSync(file, p) : file, l = d.length; var c = crc(); c.p(file); files.push(mrg(p, { size: file.length, crc: c.d(), c: d, f: f, m: m, u: s != fn.length || (m && (com.length != ms)), o: o, compression: compression })); o += 30 + s + exl + l; tot += 76 + 2 * (s + exl) + (ms || 0) + l; } var out = new u8(tot + 22), oe = o, cdl = tot - o; for (var i = 0; i < files.length; ++i) { var f = files[i]; wzh(out, f.o, f, f.f, f.u, f.c.length); var badd = 30 + f.f.length + exfl(f.extra); out.set(f.c, f.o + badd); wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); } wzf(out, o, files.length, cdl, oe); return out;}/** * Streaming pass-through decompression for ZIP archives */var UnzipPassThrough = /*#__PURE__*/ (function () { function UnzipPassThrough() { } UnzipPassThrough.prototype.push = function (data, final) { this.ondata(null, data, final); }; UnzipPassThrough.compression = 0; return UnzipPassThrough;}());export { UnzipPassThrough };/** * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for * better performance. */var UnzipInflate = /*#__PURE__*/ (function () { /** * Creates a DEFLATE decompression that can be used in ZIP archives */ function UnzipInflate() { var _this_1 = this; this.i = new Inflate(function (dat, final) { _this_1.ondata(null, dat, final); }); } UnzipInflate.prototype.push = function (data, final) { try { this.i.push(data, final); } catch (e) { this.ondata(e, data, final); } }; UnzipInflate.compression = 8; return UnzipInflate;}());export { UnzipInflate };/** * Asynchronous streaming DEFLATE decompression for ZIP archives */var AsyncUnzipInflate = /*#__PURE__*/ (function () { /** * Creates a DEFLATE decompression that can be used in ZIP archives */ function AsyncUnzipInflate(_, sz) { var _this_1 = this; if (sz < 320000) { this.i = new Inflate(function (dat, final) { _this_1.ondata(null, dat, final); }); } else { this.i = new AsyncInflate(function (err, dat, final) { _this_1.ondata(err, dat, final); }); this.terminate = this.i.terminate; } } AsyncUnzipInflate.prototype.push = function (data, final) { if (this.i.terminate) data = slc(data, 0); this.i.push(data, final); }; AsyncUnzipInflate.compression = 8; return AsyncUnzipInflate;}());export { AsyncUnzipInflate };/** * A ZIP archive decompression stream that emits files as they are discovered */var Unzip = /*#__PURE__*/ (function () { /** * Creates a ZIP decompression stream * @param cb The callback to call whenever a file in the ZIP archive is found */ function Unzip(cb) { this.onfile = cb; this.k = []; this.o = { 0: UnzipPassThrough }; this.p = et; } /** * Pushes a chunk to be unzipped * @param chunk The chunk to push * @param final Whether this is the last chunk */ Unzip.prototype.push = function (chunk, final) { var _this_1 = this; if (!this.onfile) throw 'no callback'; if (!this.p) throw 'stream finished'; if (this.c > 0) { var len = Math.min(this.c, chunk.length); var toAdd = chunk.subarray(0, len); this.c -= len; if (this.d) this.d.push(toAdd, !this.c); else this.k[0].push(toAdd); chunk = chunk.subarray(len); if (chunk.length) return this.push(chunk, final); } else { var f = 0, i = 0, is = void 0, buf = void 0; if (!this.p.length) buf = chunk; else if (!chunk.length) buf = this.p; else { buf = new u8(this.p.length + chunk.length); buf.set(this.p), buf.set(chunk, this.p.length); } var l = buf.length, oc = this.c, add = oc && this.d; var _loop_2 = function () { var _a; var sig = b4(buf, i); if (sig == 0x4034B50) { f = 1, is = i; this_1.d = null; this_1.c = 0; var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); if (l > i + 30 + fnl + es) { var chks_2 = []; this_1.k.unshift(chks_2); f = 2; var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22); var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); if (sc_1 == 4294967295) { _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1]; } else if (dd) sc_1 = -1; i += es; this_1.c = sc_1; var d_1; var file_1 = { name: fn_1, compression: cmp_1, start: function () { if (!file_1.ondata) throw 'no callback'; if (!sc_1) file_1.ondata(null, et, true); else { var ctr = _this_1.o[cmp_1]; if (!ctr) throw 'unknown compression type ' + cmp_1; d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; for (var _i = 0, chks_3 = chks_2; _i < chks_3.length; _i++) { var dat = chks_3[_i]; d_1.push(dat, false); } if (_this_1.k[0] == chks_2 && _this_1.c) _this_1.d = d_1; else d_1.push(et, true); } }, terminate: function () { if (d_1 && d_1.terminate) d_1.terminate(); } }; if (sc_1 >= 0) file_1.size = sc_1, file_1.originalSize = su_1; this_1.onfile(file_1); } return "break"; } else if (oc) { if (sig == 0x8074B50) { is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; return "break"; } else if (sig == 0x2014B50) { is = i -= 4, f = 3, this_1.c = 0; return "break"; } } }; var this_1 = this; for (; i < l - 4; ++i) { var state_1 = _loop_2(); if (state_1 === "break") break; } this.p = et; if (oc < 0) { var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); if (add) add.push(dat, !!f); else this.k[+(f == 2)].push(dat); } if (f & 2) return this.push(buf.subarray(i), final); this.p = buf.subarray(i); } if (final) { if (this.c) throw 'invalid zip file'; this.p = null; } }; /** * Registers a decoder with the stream, allowing for files compressed with * the compression type provided to be expanded correctly * @param decoder The decoder constructor */ Unzip.prototype.register = function (decoder) { this.o[decoder.compression] = decoder; }; return Unzip;}());export { Unzip };/** * Asynchronously decompresses a ZIP archive * @param data The raw compressed ZIP file * @param cb The callback to call with the decompressed files * @returns A function that can be used to immediately terminate the unzipping */export function unzip(data, cb) { if (typeof cb != 'function') throw 'no callback'; var term = []; var tAll = function () { for (var i = 0; i < term.length; ++i) term[i](); }; var files = {}; var e = data.length - 22; for (; b4(data, e) != 0x6054B50; --e) { if (!e || data.length - e > 65558) { cb('invalid zip file', null); return; } } ; var lft = b2(data, e + 8); if (!lft) cb(null, {}); var c = lft; var o = b4(data, e + 16); var z = o == 4294967295; if (z) { e = b4(data, e - 12); if (b4(data, e) != 0x6064B50) { cb('invalid zip file', null); return; } c = lft = b4(data, e + 32); o = b4(data, e + 48); } var _loop_3 = function (i) { var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); o = no; var cbl = function (e, d) { if (e) { tAll(); cb(e, null); } else { files[fn] = d; if (!--lft) cb(null, files); } }; if (!c_1) cbl(null, slc(data, b, b + sc)); else if (c_1 == 8) { var infl = data.subarray(b, b + sc); if (sc < 320000) { try { cbl(null, inflateSync(infl, new u8(su))); } catch (e) { cbl(e, null); } } else term.push(inflate(infl, { size: su }, cbl)); } else cbl('unknown compression type ' + c_1, null); }; for (var i = 0; i < c; ++i) { _loop_3(i); } return tAll;}/** * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better * performance with more than one file. * @param data The raw compressed ZIP file * @returns The decompressed files */export function unzipSync(data) { var files = {}; var e = data.length - 22; for (; b4(data, e) != 0x6054B50; --e) { if (!e || data.length - e > 65558) throw 'invalid zip file'; } ; var c = b2(data, e + 8); if (!c) return {}; var o = b4(data, e + 16); var z = o == 4294967295; if (z) { e = b4(data, e - 12); if (b4(data, e) != 0x6064B50) throw 'invalid zip file'; c = b4(data, e + 32); o = b4(data, e + 48); } for (var i = 0; i < c; ++i) { var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); o = no; if (!c_2) files[fn] = slc(data, b, b + sc); else if (c_2 == 8) files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su)); else throw 'unknown compression type ' + c_2; } return files;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375import { BufferAttribute, BufferGeometry, Float32BufferAttribute, InstancedBufferAttribute, InterleavedBuffer, InterleavedBufferAttribute, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, Vector3,} from 'three';
function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {
if ( ! MikkTSpace || ! MikkTSpace.isReady ) {
throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );
}
if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {
throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' );
}
function getAttributeArray( attribute ) {
if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {
const dstArray = new Float32Array( attribute.count * attribute.itemSize );
for ( let i = 0, j = 0; i < attribute.count; i ++ ) {
dstArray[ j ++ ] = attribute.getX( i ); dstArray[ j ++ ] = attribute.getY( i );
if ( attribute.itemSize > 2 ) {
dstArray[ j ++ ] = attribute.getZ( i );
}
}
return dstArray;
}
if ( attribute.array instanceof Float32Array ) {
return attribute.array;
}
return new Float32Array( attribute.array );
}
// MikkTSpace algorithm requires non-indexed input.
const _geometry = geometry.index ? geometry.toNonIndexed() : geometry;
// Compute vertex tangents.
const tangents = MikkTSpace.generateTangents(
getAttributeArray( _geometry.attributes.position ), getAttributeArray( _geometry.attributes.normal ), getAttributeArray( _geometry.attributes.uv )
);
// Texture coordinate convention of glTF differs from the apparent // default of the MikkTSpace library; .w component must be flipped.
if ( negateSign ) {
for ( let i = 3; i < tangents.length; i += 4 ) {
tangents[ i ] *= - 1;
}
}
//
_geometry.setAttribute( 'tangent', new BufferAttribute( tangents, 4 ) );
if ( geometry !== _geometry ) {
geometry.copy( _geometry );
}
return geometry;
}
/** * @param {Array<BufferGeometry>} geometries * @param {Boolean} useGroups * @return {BufferGeometry} */function mergeGeometries( geometries, useGroups = false ) {
const isIndexed = geometries[ 0 ].index !== null;
const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) ); const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
const attributes = {}; const morphAttributes = {};
const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
const mergedGeometry = new BufferGeometry();
let offset = 0;
for ( let i = 0; i < geometries.length; ++ i ) {
const geometry = geometries[ i ]; let attributesCount = 0;
// ensure that all geometries are indexed, or none
if ( isIndexed !== ( geometry.index !== null ) ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' ); return null;
}
// gather attributes, exit early if they're different
for ( const name in geometry.attributes ) {
if ( ! attributesUsed.has( name ) ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' ); return null;
}
if ( attributes[ name ] === undefined ) attributes[ name ] = [];
attributes[ name ].push( geometry.attributes[ name ] );
attributesCount ++;
}
// ensure geometries have the same number of attributes
if ( attributesCount !== attributesUsed.size ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' ); return null;
}
// gather morph attributes, exit early if they're different
if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' ); return null;
}
for ( const name in geometry.morphAttributes ) {
if ( ! morphAttributesUsed.has( name ) ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' ); return null;
}
if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
}
if ( useGroups ) {
let count;
if ( isIndexed ) {
count = geometry.index.count;
} else if ( geometry.attributes.position !== undefined ) {
count = geometry.attributes.position.count;
} else {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' ); return null;
}
mergedGeometry.addGroup( offset, count, i );
offset += count;
}
}
// merge indices
if ( isIndexed ) {
let indexOffset = 0; const mergedIndex = [];
for ( let i = 0; i < geometries.length; ++ i ) {
const index = geometries[ i ].index;
for ( let j = 0; j < index.count; ++ j ) {
mergedIndex.push( index.getX( j ) + indexOffset );
}
indexOffset += geometries[ i ].attributes.position.count;
}
mergedGeometry.setIndex( mergedIndex );
}
// merge attributes
for ( const name in attributes ) {
const mergedAttribute = mergeAttributes( attributes[ name ] );
if ( ! mergedAttribute ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' attribute.' ); return null;
}
mergedGeometry.setAttribute( name, mergedAttribute );
}
// merge morph attributes
for ( const name in morphAttributes ) {
const numMorphTargets = morphAttributes[ name ][ 0 ].length;
if ( numMorphTargets === 0 ) break;
mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; mergedGeometry.morphAttributes[ name ] = [];
for ( let i = 0; i < numMorphTargets; ++ i ) {
const morphAttributesToMerge = [];
for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
}
const mergedMorphAttribute = mergeAttributes( morphAttributesToMerge );
if ( ! mergedMorphAttribute ) {
console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' morphAttribute.' ); return null;
}
mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
}
}
return mergedGeometry;
}
/** * @param {Array<BufferAttribute>} attributes * @return {BufferAttribute} */function mergeAttributes( attributes ) {
let TypedArray; let itemSize; let normalized; let gpuType = - 1; let arrayLength = 0;
for ( let i = 0; i < attributes.length; ++ i ) {
const attribute = attributes[ i ];
if ( attribute.isInterleavedBufferAttribute ) {
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. InterleavedBufferAttributes are not supported.' ); return null;
}
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; if ( TypedArray !== attribute.array.constructor ) {
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' ); return null;
}
if ( itemSize === undefined ) itemSize = attribute.itemSize; if ( itemSize !== attribute.itemSize ) {
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' ); return null;
}
if ( normalized === undefined ) normalized = attribute.normalized; if ( normalized !== attribute.normalized ) {
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' ); return null;
}
if ( gpuType === - 1 ) gpuType = attribute.gpuType; if ( gpuType !== attribute.gpuType ) {
console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.' ); return null;
}
arrayLength += attribute.array.length;
}
const array = new TypedArray( arrayLength ); let offset = 0;
for ( let i = 0; i < attributes.length; ++ i ) {
array.set( attributes[ i ].array, offset );
offset += attributes[ i ].array.length;
}
const result = new BufferAttribute( array, itemSize, normalized ); if ( gpuType !== undefined ) {
result.gpuType = gpuType;
}
return result;
}
/** * @param {BufferAttribute} * @return {BufferAttribute} */export function deepCloneAttribute( attribute ) {
if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {
return deinterleaveAttribute( attribute );
}
if ( attribute.isInstancedBufferAttribute ) {
return new InstancedBufferAttribute().copy( attribute );
}
return new BufferAttribute().copy( attribute );
}
/** * @param {Array<BufferAttribute>} attributes * @return {Array<InterleavedBufferAttribute>} */function interleaveAttributes( attributes ) {
// Interleaves the provided attributes into an InterleavedBuffer and returns // a set of InterleavedBufferAttributes for each attribute let TypedArray; let arrayLength = 0; let stride = 0;
// calculate the length and type of the interleavedBuffer for ( let i = 0, l = attributes.length; i < l; ++ i ) {
const attribute = attributes[ i ];
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; if ( TypedArray !== attribute.array.constructor ) {
console.error( 'AttributeBuffers of different types cannot be interleaved' ); return null;
}
arrayLength += attribute.array.length; stride += attribute.itemSize;
}
// Create the set of buffer attributes const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride ); let offset = 0; const res = []; const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
for ( let j = 0, l = attributes.length; j < l; j ++ ) {
const attribute = attributes[ j ]; const itemSize = attribute.itemSize; const count = attribute.count; const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized ); res.push( iba );
offset += itemSize;
// Move the data for each attribute into the new interleavedBuffer // at the appropriate offset for ( let c = 0; c < count; c ++ ) {
for ( let k = 0; k < itemSize; k ++ ) {
iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
}
}
}
return res;
}
// returns a new, non-interleaved version of the provided attributeexport function deinterleaveAttribute( attribute ) {
const cons = attribute.data.array.constructor; const count = attribute.count; const itemSize = attribute.itemSize; const normalized = attribute.normalized;
const array = new cons( count * itemSize ); let newAttribute; if ( attribute.isInstancedInterleavedBufferAttribute ) {
newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
} else {
newAttribute = new BufferAttribute( array, itemSize, normalized );
}
for ( let i = 0; i < count; i ++ ) {
newAttribute.setX( i, attribute.getX( i ) );
if ( itemSize >= 2 ) {
newAttribute.setY( i, attribute.getY( i ) );
}
if ( itemSize >= 3 ) {
newAttribute.setZ( i, attribute.getZ( i ) );
}
if ( itemSize >= 4 ) {
newAttribute.setW( i, attribute.getW( i ) );
}
}
return newAttribute;
}
// deinterleaves all attributes on the geometryexport function deinterleaveGeometry( geometry ) {
const attributes = geometry.attributes; const morphTargets = geometry.morphTargets; const attrMap = new Map();
for ( const key in attributes ) {
const attr = attributes[ key ]; if ( attr.isInterleavedBufferAttribute ) {
if ( ! attrMap.has( attr ) ) {
attrMap.set( attr, deinterleaveAttribute( attr ) );
}
attributes[ key ] = attrMap.get( attr );
}
}
for ( const key in morphTargets ) {
const attr = morphTargets[ key ]; if ( attr.isInterleavedBufferAttribute ) {
if ( ! attrMap.has( attr ) ) {
attrMap.set( attr, deinterleaveAttribute( attr ) );
}
morphTargets[ key ] = attrMap.get( attr );
}
}
}
/** * @param {BufferGeometry} geometry * @return {number} */function estimateBytesUsed( geometry ) {
// Return the estimated memory used by this geometry in bytes // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account // for InterleavedBufferAttributes. let mem = 0; for ( const name in geometry.attributes ) {
const attr = geometry.getAttribute( name ); mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
}
const indices = geometry.getIndex(); mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0; return mem;
}
/** * @param {BufferGeometry} geometry * @param {number} tolerance * @return {BufferGeometry} */function mergeVertices( geometry, tolerance = 1e-4 ) {
tolerance = Math.max( tolerance, Number.EPSILON );
// Generate an index buffer if the geometry doesn't have one, or optimize it // if it's already available. const hashToIndex = {}; const indices = geometry.getIndex(); const positions = geometry.getAttribute( 'position' ); const vertexCount = indices ? indices.count : positions.count;
// next value for triangle indices let nextIndex = 0;
// attributes and new attribute arrays const attributeNames = Object.keys( geometry.attributes ); const tmpAttributes = {}; const tmpMorphAttributes = {}; const newIndices = []; const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
// Initialize the arrays, allocating space conservatively. Extra // space will be trimmed in the last step. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
const name = attributeNames[ i ]; const attr = geometry.attributes[ name ];
tmpAttributes[ name ] = new BufferAttribute( new attr.array.constructor( attr.count * attr.itemSize ), attr.itemSize, attr.normalized );
const morphAttr = geometry.morphAttributes[ name ]; if ( morphAttr ) {
tmpMorphAttributes[ name ] = new BufferAttribute( new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ), morphAttr.itemSize, morphAttr.normalized );
}
}
// convert the error tolerance to an amount of decimal places to truncate to const halfTolerance = tolerance * 0.5; const exponent = Math.log10( 1 / tolerance ); const hashMultiplier = Math.pow( 10, exponent ); const hashAdditive = halfTolerance * hashMultiplier; for ( let i = 0; i < vertexCount; i ++ ) {
const index = indices ? indices.getX( i ) : i;
// Generate a hash for the vertex attributes at the current index 'i' let hash = ''; for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
const name = attributeNames[ j ]; const attribute = geometry.getAttribute( name ); const itemSize = attribute.itemSize;
for ( let k = 0; k < itemSize; k ++ ) {
// double tilde truncates the decimal value hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * hashMultiplier + hashAdditive ) },`;
}
}
// Add another reference to the vertex if it's already // used by another index if ( hash in hashToIndex ) {
newIndices.push( hashToIndex[ hash ] );
} else {
// copy data to the new index in the temporary attributes for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
const name = attributeNames[ j ]; const attribute = geometry.getAttribute( name ); const morphAttr = geometry.morphAttributes[ name ]; const itemSize = attribute.itemSize; const newarray = tmpAttributes[ name ]; const newMorphArrays = tmpMorphAttributes[ name ];
for ( let k = 0; k < itemSize; k ++ ) {
const getterFunc = getters[ k ]; const setterFunc = setters[ k ]; newarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
if ( morphAttr ) {
for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );
}
}
}
}
hashToIndex[ hash ] = nextIndex; newIndices.push( nextIndex ); nextIndex ++;
}
}
// generate result BufferGeometry const result = geometry.clone(); for ( const name in geometry.attributes ) {
const tmpAttribute = tmpAttributes[ name ];
result.setAttribute( name, new BufferAttribute( tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ), tmpAttribute.itemSize, tmpAttribute.normalized, ) );
if ( ! ( name in tmpMorphAttributes ) ) continue;
for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
result.morphAttributes[ name ][ j ] = new BufferAttribute( tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ), tmpMorphAttribute.itemSize, tmpMorphAttribute.normalized, );
}
}
// indices
result.setIndex( newIndices );
return result;
}
/** * @param {BufferGeometry} geometry * @param {number} drawMode * @return {BufferGeometry} */function toTrianglesDrawMode( geometry, drawMode ) {
if ( drawMode === TrianglesDrawMode ) {
console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' ); return geometry;
}
if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
let index = geometry.getIndex();
// generate index if not present
if ( index === null ) {
const indices = [];
const position = geometry.getAttribute( 'position' );
if ( position !== undefined ) {
for ( let i = 0; i < position.count; i ++ ) {
indices.push( i );
}
geometry.setIndex( indices ); index = geometry.getIndex();
} else {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); return geometry;
}
}
//
const numberOfTriangles = index.count - 2; const newIndices = [];
if ( drawMode === TriangleFanDrawMode ) {
// gl.TRIANGLE_FAN
for ( let i = 1; i <= numberOfTriangles; i ++ ) {
newIndices.push( index.getX( 0 ) ); newIndices.push( index.getX( i ) ); newIndices.push( index.getX( i + 1 ) );
}
} else {
// gl.TRIANGLE_STRIP
for ( let i = 0; i < numberOfTriangles; i ++ ) {
if ( i % 2 === 0 ) {
newIndices.push( index.getX( i ) ); newIndices.push( index.getX( i + 1 ) ); newIndices.push( index.getX( i + 2 ) );
} else {
newIndices.push( index.getX( i + 2 ) ); newIndices.push( index.getX( i + 1 ) ); newIndices.push( index.getX( i ) );
}
}
}
if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
}
// build final geometry
const newGeometry = geometry.clone(); newGeometry.setIndex( newIndices ); newGeometry.clearGroups();
return newGeometry;
} else {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode ); return geometry;
}
}
/** * Calculates the morphed attributes of a morphed/skinned BufferGeometry. * Helpful for Raytracing or Decals. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points. * @return {Object} An Object with original position/normal attributes and morphed ones. */function computeMorphedAttributes( object ) {
const _vA = new Vector3(); const _vB = new Vector3(); const _vC = new Vector3();
const _tempA = new Vector3(); const _tempB = new Vector3(); const _tempC = new Vector3();
const _morphA = new Vector3(); const _morphB = new Vector3(); const _morphC = new Vector3();
function _calculateMorphedAttributeData( object, attribute, morphAttribute, morphTargetsRelative, a, b, c, modifiedAttributeArray ) {
_vA.fromBufferAttribute( attribute, a ); _vB.fromBufferAttribute( attribute, b ); _vC.fromBufferAttribute( attribute, c );
const morphInfluences = object.morphTargetInfluences;
if ( morphAttribute && morphInfluences ) {
_morphA.set( 0, 0, 0 ); _morphB.set( 0, 0, 0 ); _morphC.set( 0, 0, 0 );
for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
const influence = morphInfluences[ i ]; const morph = morphAttribute[ i ];
if ( influence === 0 ) continue;
_tempA.fromBufferAttribute( morph, a ); _tempB.fromBufferAttribute( morph, b ); _tempC.fromBufferAttribute( morph, c );
if ( morphTargetsRelative ) {
_morphA.addScaledVector( _tempA, influence ); _morphB.addScaledVector( _tempB, influence ); _morphC.addScaledVector( _tempC, influence );
} else {
_morphA.addScaledVector( _tempA.sub( _vA ), influence ); _morphB.addScaledVector( _tempB.sub( _vB ), influence ); _morphC.addScaledVector( _tempC.sub( _vC ), influence );
}
}
_vA.add( _morphA ); _vB.add( _morphB ); _vC.add( _morphC );
}
if ( object.isSkinnedMesh ) {
object.applyBoneTransform( a, _vA ); object.applyBoneTransform( b, _vB ); object.applyBoneTransform( c, _vC );
}
modifiedAttributeArray[ a * 3 + 0 ] = _vA.x; modifiedAttributeArray[ a * 3 + 1 ] = _vA.y; modifiedAttributeArray[ a * 3 + 2 ] = _vA.z; modifiedAttributeArray[ b * 3 + 0 ] = _vB.x; modifiedAttributeArray[ b * 3 + 1 ] = _vB.y; modifiedAttributeArray[ b * 3 + 2 ] = _vB.z; modifiedAttributeArray[ c * 3 + 0 ] = _vC.x; modifiedAttributeArray[ c * 3 + 1 ] = _vC.y; modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
}
const geometry = object.geometry; const material = object.material;
let a, b, c; const index = geometry.index; const positionAttribute = geometry.attributes.position; const morphPosition = geometry.morphAttributes.position; const morphTargetsRelative = geometry.morphTargetsRelative; const normalAttribute = geometry.attributes.normal; const morphNormal = geometry.morphAttributes.position;
const groups = geometry.groups; const drawRange = geometry.drawRange; let i, j, il, jl; let group; let start, end;
const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize ); const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
if ( index !== null ) {
// indexed buffer geometry
if ( Array.isArray( material ) ) {
for ( i = 0, il = groups.length; i < il; i ++ ) {
group = groups[ i ];
start = Math.max( group.start, drawRange.start ); end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
for ( j = start, jl = end; j < jl; j += 3 ) {
a = index.getX( j ); b = index.getX( j + 1 ); c = index.getX( j + 2 );
_calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
_calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
}
}
} else {
start = Math.max( 0, drawRange.start ); end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
for ( i = start, il = end; i < il; i += 3 ) {
a = index.getX( i ); b = index.getX( i + 1 ); c = index.getX( i + 2 );
_calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
_calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
}
}
} else {
// non-indexed buffer geometry
if ( Array.isArray( material ) ) {
for ( i = 0, il = groups.length; i < il; i ++ ) {
group = groups[ i ];
start = Math.max( group.start, drawRange.start ); end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
for ( j = start, jl = end; j < jl; j += 3 ) {
a = j; b = j + 1; c = j + 2;
_calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
_calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
}
}
} else {
start = Math.max( 0, drawRange.start ); end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
for ( i = start, il = end; i < il; i += 3 ) {
a = i; b = i + 1; c = i + 2;
_calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
_calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
}
}
}
const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 ); const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
return {
positionAttribute: positionAttribute, normalAttribute: normalAttribute, morphedPositionAttribute: morphedPositionAttribute, morphedNormalAttribute: morphedNormalAttribute
};
}
function mergeGroups( geometry ) {
if ( geometry.groups.length === 0 ) {
console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' ); return geometry;
}
let groups = geometry.groups;
// sort groups by material index
groups = groups.sort( ( a, b ) => {
if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
return a.start - b.start;
} );
// create index for non-indexed geometries
if ( geometry.getIndex() === null ) {
const positionAttribute = geometry.getAttribute( 'position' ); const indices = [];
for ( let i = 0; i < positionAttribute.count; i += 3 ) {
indices.push( i, i + 1, i + 2 );
}
geometry.setIndex( indices );
}
// sort index
const index = geometry.getIndex();
const newIndices = [];
for ( let i = 0; i < groups.length; i ++ ) {
const group = groups[ i ];
const groupStart = group.start; const groupLength = groupStart + group.count;
for ( let j = groupStart; j < groupLength; j ++ ) {
newIndices.push( index.getX( j ) );
}
}
geometry.dispose(); // Required to force buffer recreation geometry.setIndex( newIndices );
// update groups indices
let start = 0;
for ( let i = 0; i < groups.length; i ++ ) {
const group = groups[ i ];
group.start = start; start += group.count;
}
// merge groups
let currentGroup = groups[ 0 ];
geometry.groups = [ currentGroup ];
for ( let i = 1; i < groups.length; i ++ ) {
const group = groups[ i ];
if ( currentGroup.materialIndex === group.materialIndex ) {
currentGroup.count += group.count;
} else {
currentGroup = group; geometry.groups.push( currentGroup );
}
}
return geometry;
}
/** * Modifies the supplied geometry if it is non-indexed, otherwise creates a new, * non-indexed geometry. Returns the geometry with smooth normals everywhere except * faces that meet at an angle greater than the crease angle. * * @param {BufferGeometry} geometry * @param {number} [creaseAngle] * @return {BufferGeometry} */function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {
const creaseDot = Math.cos( creaseAngle ); const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
// reusable vectors const verts = [ new Vector3(), new Vector3(), new Vector3() ]; const tempVec1 = new Vector3(); const tempVec2 = new Vector3(); const tempNorm = new Vector3(); const tempNorm2 = new Vector3();
// hashes a vector function hashVertex( v ) {
const x = ~ ~ ( v.x * hashMultiplier ); const y = ~ ~ ( v.y * hashMultiplier ); const z = ~ ~ ( v.z * hashMultiplier ); return `${x},${y},${z}`;
}
// BufferGeometry.toNonIndexed() warns if the geometry is non-indexed // and returns the original geometry const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry; const posAttr = resultGeometry.attributes.position; const vertexMap = {};
// find all the normals shared by commonly located vertices for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
const i3 = 3 * i; const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 ); const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 ); const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
tempVec1.subVectors( c, b ); tempVec2.subVectors( a, b );
// add the normal to the map for all vertices const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize(); for ( let n = 0; n < 3; n ++ ) {
const vert = verts[ n ]; const hash = hashVertex( vert ); if ( ! ( hash in vertexMap ) ) {
vertexMap[ hash ] = [];
}
vertexMap[ hash ].push( normal );
}
}
// average normals from all vertices that share a common location if they are within the // provided crease threshold const normalArray = new Float32Array( posAttr.count * 3 ); const normAttr = new BufferAttribute( normalArray, 3, false ); for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
// get the face normal for this vertex const i3 = 3 * i; const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 ); const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 ); const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
tempVec1.subVectors( c, b ); tempVec2.subVectors( a, b );
tempNorm.crossVectors( tempVec1, tempVec2 ).normalize();
// average all normals that meet the threshold and set the normal value for ( let n = 0; n < 3; n ++ ) {
const vert = verts[ n ]; const hash = hashVertex( vert ); const otherNormals = vertexMap[ hash ]; tempNorm2.set( 0, 0, 0 );
for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {
const otherNorm = otherNormals[ k ]; if ( tempNorm.dot( otherNorm ) > creaseDot ) {
tempNorm2.add( otherNorm );
}
}
tempNorm2.normalize(); normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );
}
}
resultGeometry.setAttribute( 'normal', normAttr ); return resultGeometry;
}
function mergeBufferGeometries( geometries, useGroups = false ) {
console.warn( 'THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries().' ); // @deprecated, r151 return mergeGeometries( geometries, useGroups );
}
function mergeBufferAttributes( attributes ) {
console.warn( 'THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes().' ); // @deprecated, r151 return mergeAttributes( attributes );
}
export { computeMikkTSpaceTangents, mergeGeometries, mergeBufferGeometries, mergeAttributes, mergeBufferAttributes, interleaveAttributes, estimateBytesUsed, mergeVertices, toTrianglesDrawMode, computeMorphedAttributes, mergeGroups, toCreasedNormals};.gitattributes+2
app.js+1010-110
assets/Ch46_nonPBR.fbxAdded+3
assets/T-Pose.fbxAdded+3
avatar/AvatarCanvas.jsAdded+374
avatar/boneMap.jsAdded+184
avatar/package.jsonAdded+4
avatar/retargetUtils.jsAdded+197
avatar/rig.jsAdded+420
avatar/tests/register.mjsAdded+2
avatar/tests/resolve-three.mjsAdded+13
avatar/tests/retarget.test.mjsAdded+248
avatar/tests/testRig.mjsAdded+70
index.html+116-4
style.css+533-1
vendor/three/LICENSEAdded+21
vendor/three/examples/jsm/controls/OrbitControls.jsAdded+1417
vendor/three/examples/jsm/curves/NURBSCurve.jsAdded+80
vendor/three/examples/jsm/curves/NURBSUtils.jsAdded+487
vendor/three/examples/jsm/libs/fflate.module.jsAdded+2474
vendor/three/examples/jsm/loaders/FBXLoader.jsAdded
vendor/three/examples/jsm/loaders/GLTFLoader.jsAdded
vendor/three/examples/jsm/utils/BufferGeometryUtils.jsAdded+1375
vendor/three/three.module.jsAdded