-
-
Save JackTYM/baa22f2584eab498aa4c1bb29c1fa9af to your computer and use it in GitHub Desktop.
| /** | |
| * tripo3d_model_downloader.js | |
| * ───────────────────────────────────────────────────────────────────────────── | |
| * Extracts the loaded 3D model directly from the TresJS/Three.js renderer on | |
| * studio.tripo3d.ai, bypasses the export tool entirely, and triggers a .glb | |
| * download. | |
| * | |
| * HOW IT WORKS | |
| * ───────────────────────────────────────────────────────────────────────────── | |
| * 1. The site is a Nuxt 3 / Vue 3 app using TresJS (Vue wrapper for Three.js). | |
| * 2. The Vue app is mounted on #__nuxt with __vue_app__ attached to the element. | |
| * 3. The current page component is accessible via: | |
| * vueApp → $router → currentRoute.matched[0].instances.default._ | |
| * 4. Traversing the component subTree finds the TresJS "Context" component, | |
| * whose `provides.useTres` object holds { scene, camera, renderer }. | |
| * 5. The model mesh (named "tripo_node_<operatorId>") lives inside a Group | |
| * two levels deep in the scene. | |
| * 6. Geometry buffers (position, normal, uv, indices) are raw TypedArrays. | |
| * 7. The diffuse texture is an ImageBitmap — drawn to an offscreen canvas and | |
| * exported as PNG. | |
| * 8. A valid GLB (GLTF 2.0 binary) is assembled manually and downloaded. | |
| * | |
| * USAGE | |
| * ───────────────────────────────────────────────────────────────────────────── | |
| * Paste this entire script into the browser DevTools console while on any | |
| * studio.tripo3d.ai/3d-model/<id> page and wait for the download prompt. | |
| * | |
| * TESTED ON | |
| * ───────────────────────────────────────────────────────────────────────────── | |
| * Three.js r183, TresJS, Nuxt 3, Pinia — May 2026 | |
| */ | |
| (async function extractTripoGLB() { | |
| // ── 1. Locate the Vue app ───────────────────────────────────────────────── | |
| const appEl = document.querySelector('[data-v-app]') || document.querySelector('#__nuxt'); | |
| if (!appEl || !appEl.__vue_app__) { | |
| throw new Error('Vue app not found. Are you on a Tripo Studio model page?'); | |
| } | |
| const vueApp = appEl.__vue_app__; | |
| // ── 2. Locate the current page component instance ──────────────────────── | |
| const router = vueApp.config?.globalProperties?.$router; | |
| const route = router?.currentRoute?.value; | |
| const matched = route?.matched?.[0]; | |
| if (!matched) throw new Error('No matched route found.'); | |
| const pageInternal = matched.instances?.default?._; | |
| if (!pageInternal) throw new Error('Page component internal instance not found.'); | |
| // ── 3. Walk the vnode subTree to find a component by display name ───────── | |
| function findComponentByName(vnode, targetName, depth = 0) { | |
| if (!vnode || depth > 40) return null; | |
| if (vnode.component) { | |
| const inst = vnode.component; | |
| const name = inst.type?.name || inst.type?.__name || ''; | |
| if (name === targetName) return inst; | |
| const found = findComponentByName(inst.subTree, targetName, depth + 1); | |
| if (found) return found; | |
| return null; | |
| } | |
| if (Array.isArray(vnode.children)) { | |
| for (const child of vnode.children) { | |
| if (child && typeof child === 'object') { | |
| const found = findComponentByName(child, targetName, depth); | |
| if (found) return found; | |
| } | |
| } | |
| } | |
| return null; | |
| } | |
| // ── 4. Get TresJS context (scene / camera / renderer) ──────────────────── | |
| // TresJS v2+ exposes context via a "Context" component's provide key "useTres" | |
| const contextComp = findComponentByName(pageInternal.subTree, 'Context'); | |
| if (!contextComp) throw new Error('"Context" TresJS component not found in vnode tree.'); | |
| const tres = contextComp.provides?.useTres; | |
| if (!tres) throw new Error('"useTres" not found in Context provides.'); | |
| const scene = tres.scene?.value ?? tres.scene; | |
| if (!scene?.isScene) throw new Error('THREE.Scene not found in useTres.scene.'); | |
| console.log('[tripo-extract] Scene found:', scene.type, '— children:', scene.children.length); | |
| // ── 5. Find the model mesh in the scene ─────────────────────────────────── | |
| function findMeshes(obj, results = []) { | |
| if (!obj) return results; | |
| if (obj.isMesh) results.push(obj); | |
| if (obj.children) for (const c of obj.children) findMeshes(c, results); | |
| return results; | |
| } | |
| const allMeshes = findMeshes(scene); | |
| // The model mesh has the most vertices; filter out tiny background quads | |
| const modelMesh = allMeshes.reduce((best, m) => | |
| (m.geometry?.attributes?.position?.count ?? 0) > | |
| (best.geometry?.attributes?.position?.count ?? 0) ? m : best | |
| , allMeshes[0]); | |
| if (!modelMesh) throw new Error('No mesh found in scene.'); | |
| const vCount = modelMesh.geometry.attributes.position.count; | |
| const iCount = modelMesh.geometry.index?.count ?? 0; | |
| console.log(`[tripo-extract] Model mesh: "${modelMesh.name}" — ${vCount} vertices, ${iCount} indices`); | |
| // ── 6. Extract geometry typed arrays ───────────────────────────────────── | |
| const geo = modelMesh.geometry; | |
| const positions = geo.attributes.position.array; // Float32Array | |
| // Skip normals — Tripo's AI-generated normals are inconsistent (random directions). | |
| // By omitting them, Blender will calculate smooth normals from face winding order. | |
| const normals = null; | |
| const uvs = geo.attributes.uv?.array; // Float32Array (may be absent) | |
| const indices = geo.index?.array; // Uint32Array (may be absent) | |
| console.log('[tripo-extract] Skipping original normals — Blender will recalculate smooth normals'); | |
| // ── 7. Extract diffuse texture → PNG ArrayBuffer ───────────────────────── | |
| let texturePNGBytes = null; | |
| const texImage = modelMesh.material?.map?.image; | |
| if (texImage) { | |
| const offscreen = document.createElement('canvas'); | |
| offscreen.width = texImage.width ?? texImage.naturalWidth ?? 1024; | |
| offscreen.height = texImage.height ?? texImage.naturalHeight ?? 1024; | |
| const ctx2d = offscreen.getContext('2d'); | |
| ctx2d.drawImage(texImage, 0, 0); | |
| const pngBlob = await new Promise(res => offscreen.toBlob(res, 'image/png')); | |
| texturePNGBytes = new Uint8Array(await pngBlob.arrayBuffer()); | |
| console.log(`[tripo-extract] Texture: ${offscreen.width}×${offscreen.height} → ${(texturePNGBytes.byteLength/1024).toFixed(0)} KB PNG`); | |
| } else { | |
| console.warn('[tripo-extract] No diffuse texture found; exporting geometry only.'); | |
| } | |
| // ── 8. Build binary buffer layout (4-byte aligned) ──────────────────────── | |
| const align4 = n => Math.ceil(n / 4) * 4; | |
| const vertexCount = positions.length / 3; | |
| const posBytes = positions.byteLength; | |
| const normBytes = normals ? align4(vertexCount * 3 * 4) : 0; | |
| const uvBytes = uvs ? align4(uvs.byteLength) : 0; | |
| const idxBytes = indices ? align4(indices.byteLength) : 0; | |
| const texBytes = texturePNGBytes ? align4(texturePNGBytes.byteLength) : 0; | |
| const normOffset = align4(posBytes); | |
| const uvOffset = normOffset + normBytes; | |
| const idxOffset = uvOffset + uvBytes; | |
| const texOffset = idxOffset + idxBytes; | |
| const totalBin = align4(texOffset + texBytes); | |
| // ── 9. Build GLTF JSON ──────────────────────────────────────────────────── | |
| // Compute AABB for position accessor (required by spec) | |
| let minPos = [Infinity, Infinity, Infinity]; | |
| let maxPos = [-Infinity, -Infinity, -Infinity]; | |
| for (let i = 0; i < positions.length; i += 3) { | |
| minPos[0] = Math.min(minPos[0], positions[i]); | |
| minPos[1] = Math.min(minPos[1], positions[i+1]); | |
| minPos[2] = Math.min(minPos[2], positions[i+2]); | |
| maxPos[0] = Math.max(maxPos[0], positions[i]); | |
| maxPos[1] = Math.max(maxPos[1], positions[i+1]); | |
| maxPos[2] = Math.max(maxPos[2], positions[i+2]); | |
| } | |
| const accessors = []; | |
| const bufferViews = []; | |
| const primitiveAttr = {}; | |
| // POSITION accessor (index 0) | |
| bufferViews.push({ buffer: 0, byteOffset: 0, byteLength: posBytes, target: 34962 }); | |
| accessors.push({ | |
| bufferView: 0, byteOffset: 0, componentType: 5126, count: positions.length / 3, | |
| type: 'VEC3', min: minPos, max: maxPos | |
| }); | |
| primitiveAttr.POSITION = 0; | |
| // NORMAL accessor | |
| if (normals) { | |
| const normBvIdx = bufferViews.length; | |
| bufferViews.push({ buffer: 0, byteOffset: normOffset, byteLength: vertexCount * 3 * 4, target: 34962 }); | |
| const normAccIdx = accessors.length; | |
| accessors.push({ bufferView: normBvIdx, byteOffset: 0, componentType: 5126, count: vertexCount, type: 'VEC3' }); | |
| primitiveAttr.NORMAL = normAccIdx; | |
| } | |
| // TEXCOORD_0 accessor | |
| if (uvs) { | |
| const uvBvIdx = bufferViews.length; | |
| bufferViews.push({ buffer: 0, byteOffset: uvOffset, byteLength: uvs.byteLength, target: 34962 }); | |
| const uvAccIdx = accessors.length; | |
| accessors.push({ bufferView: uvBvIdx, byteOffset: 0, componentType: 5126, count: uvs.length / 2, type: 'VEC2' }); | |
| primitiveAttr.TEXCOORD_0 = uvAccIdx; | |
| } | |
| // INDEX accessor | |
| let indicesAccessorIdx = null; | |
| if (indices) { | |
| const bvIdx = bufferViews.length; | |
| bufferViews.push({ buffer: 0, byteOffset: idxOffset, byteLength: indices.byteLength, target: 34963 }); | |
| indicesAccessorIdx = accessors.length; | |
| accessors.push({ bufferView: bvIdx, byteOffset: 0, componentType: 5125, count: indices.length, type: 'SCALAR' }); | |
| } | |
| // IMAGE buffer view | |
| let imageBufferView = null; | |
| if (texturePNGBytes) { | |
| imageBufferView = bufferViews.length; | |
| bufferViews.push({ buffer: 0, byteOffset: texOffset, byteLength: texturePNGBytes.byteLength }); | |
| } | |
| // Primitive | |
| const primitive = { attributes: primitiveAttr }; | |
| if (indicesAccessorIdx !== null) primitive.indices = indicesAccessorIdx; | |
| if (imageBufferView !== null) primitive.material = 0; | |
| // Full GLTF JSON | |
| const gltf = { | |
| asset: { version: '2.0', generator: 'tripo3d-browser-extractor' }, | |
| scene: 0, | |
| scenes: [{ name: 'Scene', nodes: [0] }], | |
| nodes: [{ name: modelMesh.name || 'tripo_model', mesh: 0 }], | |
| meshes: [{ name: 'tripo_mesh', primitives: [primitive] }], | |
| accessors, | |
| bufferViews, | |
| buffers: [{ byteLength: totalBin }], | |
| ...(imageBufferView !== null ? { | |
| materials: [{ | |
| name: 'tripo_mat', | |
| pbrMetallicRoughness: { | |
| baseColorTexture: { index: 0 }, | |
| metallicFactor: 0.0, | |
| roughnessFactor: 0.5 | |
| }, | |
| doubleSided: true // Match Tripo's web renderer — renders both face directions | |
| }], | |
| textures: [{ source: 0 }], | |
| images: [{ mimeType: 'image/png', bufferView: imageBufferView }] | |
| } : {}) | |
| }; | |
| // ── 10. Assemble GLB binary ─────────────────────────────────────────────── | |
| const jsonEncoded = new TextEncoder().encode(JSON.stringify(gltf)); | |
| const jsonPadded = align4(jsonEncoded.length); | |
| const totalSize = 12 // GLB header | |
| + 8 + jsonPadded // JSON chunk | |
| + 8 + totalBin; // BIN chunk | |
| const glb = new ArrayBuffer(totalSize); | |
| const dv = new DataView(glb); | |
| const buf = new Uint8Array(glb); | |
| let off = 0; | |
| // GLB header | |
| dv.setUint32(off, 0x46546C67, true); off += 4; // magic "glTF" | |
| dv.setUint32(off, 2, true); off += 4; // version 2 | |
| dv.setUint32(off, totalSize, true); off += 4; // total length | |
| // JSON chunk | |
| dv.setUint32(off, jsonPadded, true); off += 4; // chunk length | |
| dv.setUint32(off, 0x4E4F534A, true); off += 4; // "JSON" | |
| buf.set(jsonEncoded, off); | |
| for (let i = jsonEncoded.length; i < jsonPadded; i++) buf[off + i] = 0x20; // pad with spaces | |
| off += jsonPadded; | |
| // BIN chunk | |
| dv.setUint32(off, totalBin, true); off += 4; // chunk length | |
| dv.setUint32(off, 0x004E4942, true); off += 4; // "BIN\0" | |
| const binStart = off; | |
| buf.set(new Uint8Array(positions.buffer, positions.byteOffset, positions.byteLength), binStart); | |
| if (normals) buf.set(new Uint8Array(normals.buffer, normals.byteOffset, vertexCount * 3 * 4), binStart + normOffset); | |
| if (uvs) buf.set(new Uint8Array(uvs.buffer, uvs.byteOffset, uvs.byteLength), binStart + uvOffset); | |
| if (indices) buf.set(new Uint8Array(indices.buffer, indices.byteOffset, indices.byteLength), binStart + idxOffset); | |
| if (texturePNGBytes) buf.set(texturePNGBytes, binStart + texOffset); | |
| // ── 11. Verify & download ───────────────────────────────────────────────── | |
| const magic = dv.getUint32(0, true); | |
| const fileMB = (totalSize / 1024 / 1024).toFixed(2); | |
| if (magic !== 0x46546C67) throw new Error('GLB magic header mismatch — build failed.'); | |
| console.log(`[tripo-extract] ✓ GLB valid — ${fileMB} MB`); | |
| const modelId = window.location.pathname.split('/').filter(Boolean).pop() || 'model'; | |
| const filename = `tripo_${modelId}.glb`; | |
| const blobUrl = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' })); | |
| const anchor = document.createElement('a'); | |
| anchor.href = blobUrl; | |
| anchor.download = filename; | |
| anchor.click(); | |
| // Revoke after a short delay to free memory | |
| setTimeout(() => URL.revokeObjectURL(blobUrl), 10_000); | |
| console.log(`[tripo-extract] ✓ Download triggered: ${filename} (${fileMB} MB)`); | |
| return { filename, fileMB, vertices: vCount, indices: iCount }; | |
| })(); |
@LSDCracker @huemadecret @luarsiarb-web @railroadman @dorPXP Sorry for mentioning everyone good news is i bypassed everything again took me a few hours but worth it just wanted to help you guys also now rigs are included too if anyone interested maybe this will be my final update here in comments have fun guys for future updates just dm me on discord my username is : DGDF
Heres the tempermonkey script:
// ==UserScript== // @name Tripo3D Auto-Downloader (Textured Models) // @namespace https://studio.tripo3d.ai/ // @Version 5.0.0 // @description Automatically intercepts network traffic to capture fully textured files, no DevTools required. // @author You // @match https://studio.tripo3d.ai/* // @run-at document-start // @grant none // ==/UserScript==
(function() { 'use strict';
let capturedUrl = null; let capturedExt = 'fbx'; // ───────────────────────────────────────────────────────────────────────────── // 1. Inject the Floating UI (Now with a Reload Button) // ───────────────────────────────────────────────────────────────────────────── function injectUI() { if (document.getElementById('tripo-gui-container')) return; const container = document.createElement('div'); container.id = 'tripo-gui-container'; container.style.cssText = ` position: fixed; top: 80px; right: 20px; z-index: 999999; display: flex; gap: 8px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; `; // The Reload / Cache-Bust Button const reloadBtn = document.createElement('button'); reloadBtn.innerHTML = '↻ Reload'; reloadBtn.title = 'Force reload the viewer if the model was missed'; reloadBtn.style.cssText = ` padding: 10px 14px; background: rgba(15, 23, 42, 0.94); color: #e2e8f0; border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; backdrop-filter: blur(10px); transition: all 0.2s ease; `; reloadBtn.onmouseover = () => reloadBtn.style.background = 'rgba(30, 41, 59, 0.94)'; reloadBtn.onmouseout = () => reloadBtn.style.background = 'rgba(15, 23, 42, 0.94)'; reloadBtn.onclick = () => { // Appending a random timestamp forces the browser to ignore the cache for the page HTML const url = new URL(window.location.href); url.searchParams.set('force_refresh', Date.now()); window.location.href = url.toString(); }; // The Main Download Button const dlBtn = document.createElement('button'); dlBtn.id = 'tripo-net-dl'; dlBtn.innerText = 'Scanning Traffic...'; dlBtn.disabled = true; dlBtn.style.cssText = ` padding: 10px 18px; background: rgba(15, 23, 42, 0.94); color: #94a3b8; border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 8px; font-weight: 600; font-size: 13px; cursor: not-allowed; backdrop-filter: blur(10px); box-shadow: 0 10px 30px rgba(0,0,0,0.6); transition: all 0.3s ease; user-select: none; `; dlBtn.onclick = () => { if (capturedUrl) { const a = document.createElement('a'); a.href = capturedUrl; a.download = `tripo_textured_model.${capturedExt}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); } }; container.appendChild(reloadBtn); container.appendChild(dlBtn); document.body.appendChild(container); // If we already captured a URL before the UI loaded, update it immediately if (capturedUrl) updateButtonUI(); } function updateButtonUI() { const btn = document.getElementById('tripo-net-dl'); if (btn && capturedUrl) { btn.innerText = `Download Textured .${capturedExt.toUpperCase()}`; btn.style.background = "linear-gradient(135deg, #10b981 0%, #059669 100%)"; btn.style.color = "white"; btn.style.cursor = "pointer"; btn.style.border = "none"; btn.disabled = false; } } // ───────────────────────────────────────────────────────────────────────────── // 2. Intercept Fetch API // ───────────────────────────────────────────────────────────────────────────── const originalFetch = window.fetch; window.fetch = async function(...args) { const url = typeof args[0] === 'string' ? args[0] : (args[0]?.url || ''); const urlLower = url.split('?')[0].toLowerCase(); // Ignore query parameters for extension check if (urlLower.endsWith('.fbx')) { capturedUrl = url; capturedExt = 'fbx'; updateButtonUI(); } else if (urlLower.endsWith('.glb')) { capturedUrl = url; capturedExt = 'glb'; updateButtonUI(); } else if (urlLower.endsWith('.gltf')) { capturedUrl = url; capturedExt = 'gltf'; updateButtonUI(); } else if (urlLower.endsWith('.obj')) { capturedUrl = url; capturedExt = 'obj'; updateButtonUI(); } const response = await originalFetch.apply(this, args); if (!capturedUrl) { const clone = response.clone(); const contentType = clone.headers.get('content-type') || ''; const contentLength = clone.headers.get('content-length') || '0'; if ((contentType.includes('octet-stream') || contentType.includes('gltf') || contentType.includes('json')) && parseInt(contentLength) > 1000000) { capturedUrl = url; capturedExt = contentType.includes('gltf') ? 'glb' : 'fbx'; updateButtonUI(); } } return response; }; // ───────────────────────────────────────────────────────────────────────────── // 3. Intercept XMLHttpRequest // ───────────────────────────────────────────────────────────────────────────── const originalOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { this.addEventListener('load', function() { if (typeof url === 'string') { const urlLower = url.split('?')[0].toLowerCase(); if (urlLower.endsWith('.fbx')) { capturedUrl = url; capturedExt = 'fbx'; updateButtonUI(); } else if (urlLower.endsWith('.glb')) { capturedUrl = url; capturedExt = 'glb'; updateButtonUI(); } else if (urlLower.endsWith('.gltf')) { capturedUrl = url; capturedExt = 'gltf'; updateButtonUI(); } } }); originalOpen.apply(this, arguments); }; // Initialize UI if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', injectUI); } else { injectUI(); } // Failsafe injection check setInterval(injectUI, 2000);})();
I'ts work very cool! Thank you a lot!
Got this error
VM21064:75 Uncaught (in promise) Error: "Context" TresJS component not found in vnode tree.
at extractTripoGLB (:75:27)
at :291:3
The newest changes to the site broke this script. Chatgpt coded up this version for me and it worked flawlessly.
'use strict';
const TAG = '[tripo-extract]';
const log = (...args) => console.log(TAG, ...args);
const warn = (...args) => console.warn(TAG, ...args);
function isObjectLike(v) {
return v !== null && (typeof v === 'object' || typeof v === 'function');
}
function unwrap(v) {
try {
if (v && typeof v === 'object' && v.__v_isRef === true && 'value' in v) {
return v.value;
}
} catch (_) {}
return v;
}
function looksLikeScene(v) {
try {
v = unwrap(v);
if (!v || typeof v !== 'object') return null;
if (v.isScene === true) return v;
if (
v.type === 'Scene' &&
v.isObject3D === true &&
Array.isArray(v.children)
) {
return v;
}
} catch (_) {}
return null;
}
function sceneFromContainer(v) {
try {
v = unwrap(v);
if (!v || typeof v !== 'object') return null;
const direct = looksLikeScene(v);
if (direct) return direct;
const names = [
'scene',
'_scene',
'threeScene',
'rootScene',
'currentScene',
'tresScene'
];
for (const name of names) {
let candidate;
try {
candidate = unwrap(v[name]);
} catch (_) {
continue;
}
const found = looksLikeScene(candidate);
if (found) return found;
}
const wrappers = [
'context',
'tres',
'tresContext',
'state',
'store',
'rendererState'
];
for (const name of wrappers) {
let candidate;
try {
candidate = unwrap(v[name]);
} catch (_) {
continue;
}
if (!candidate || typeof candidate !== 'object') continue;
const directWrapped = looksLikeScene(candidate);
if (directWrapped) return directWrapped;
for (const sceneName of names) {
let nested;
try {
nested = unwrap(candidate[sceneName]);
} catch (_) {
continue;
}
const found = looksLikeScene(nested);
if (found) return found;
}
}
} catch (_) {}
return null;
}
function safeOwnEntries(obj) {
const out = [];
if (!isObjectLike(obj)) return out;
let keys;
try {
keys = Reflect.ownKeys(obj);
} catch (_) {
return out;
}
for (const key of keys) {
let desc;
try {
desc = Object.getOwnPropertyDescriptor(obj, key);
} catch (_) {
continue;
}
// Avoid invoking getters while crawling the app graph.
if (!desc || !('value' in desc)) continue;
out.push([key, desc.value]);
}
return out;
}
function deepFindScene(roots, options = {}) {
const maxDepth = options.maxDepth ?? 18;
const maxNodes = options.maxNodes ?? 120000;
const queue = [];
const seen = new WeakSet();
let visited = 0;
function push(value, path, depth) {
value = unwrap(value);
if (!isObjectLike(value)) return;
if (depth > maxDepth) return;
queue.push({
value,
path,
depth
});
}
roots.forEach((root, i) => {
push(root, `root[${i}]`, 0);
});
while (queue.length && visited < maxNodes) {
const item = queue.shift();
const obj = item.value;
if (!isObjectLike(obj)) continue;
if (seen.has(obj)) continue;
seen.add(obj);
visited += 1;
const direct = sceneFromContainer(obj);
if (direct) {
log(
`Scene found by deep graph scan at ${item.path} after ${visited} objects`
);
return direct;
}
if (item.depth >= maxDepth) continue;
if (obj instanceof Map) {
let n = 0;
for (const [k, v] of obj.entries()) {
if (n++ > 200) break;
push(
k,
`${item.path}.<map-key>`,
item.depth + 1
);
push(
v,
`${item.path}.<map-value>`,
item.depth + 1
);
}
}
if (obj instanceof Set) {
let n = 0;
for (const v of obj.values()) {
if (n++ > 200) break;
push(
v,
`${item.path}.<set-value>`,
item.depth + 1
);
}
}
const entries = safeOwnEntries(obj);
for (const [key, value] of entries) {
if (!isObjectLike(value)) continue;
const keyText =
typeof key === 'symbol'
? key.toString()
: String(key);
// Avoid exploding into the whole browser global object graph.
if (
keyText === 'window' ||
keyText === 'self' ||
keyText === 'globalThis' ||
keyText === 'ownerDocument' ||
keyText === 'document' ||
keyText === 'defaultView'
) {
continue;
}
push(
value,
`${item.path}.${keyText}`,
item.depth + 1
);
}
}
warn(
`Deep graph scan visited ${visited} objects and did not find THREE.Scene.`
);
return null;
}
function collectDiscoveryRoots(vueApp, appEl) {
const roots = [];
const add = (v) => {
v = unwrap(v);
if (
isObjectLike(v) &&
!roots.includes(v)
) {
roots.push(v);
}
};
add(vueApp);
add(vueApp?._instance);
add(vueApp?._context);
add(vueApp?._context?.provides);
add(vueApp?._instance?.appContext);
add(vueApp?._instance?.appContext?.provides);
add(vueApp?._instance?.subTree);
add(appEl);
add(appEl?.__vueParentComponent);
add(appEl?.__vnode);
try {
const router =
vueApp
?.config
?.globalProperties
?.$router;
const route =
router
?.currentRoute
?.value;
add(router);
add(route);
for (const matched of route?.matched ?? []) {
add(matched);
add(matched?.instances?.default);
add(matched?.instances?.default?._);
}
} catch (_) {}
const canvases =
Array.from(
document.querySelectorAll('canvas')
);
log(
`Canvas elements found: ${canvases.length}`
);
for (const canvas of canvases) {
add(canvas);
add(canvas.__vueParentComponent);
add(canvas.__vnode);
let el = canvas.parentElement;
for (
let i = 0;
el && i < 12;
i += 1, el = el.parentElement
) {
add(el.__vueParentComponent);
add(el.__vnode);
}
}
// Renderer components may live under Teleport/portal DOM nodes rather
// than beneath the apparent Nuxt page component.
try {
const all =
document.querySelectorAll('*');
let foundVueNodes = 0;
for (const el of all) {
if (foundVueNodes >= 500) break;
if (
el.__vueParentComponent ||
el.__vnode
) {
add(el.__vueParentComponent);
add(el.__vnode);
foundVueNodes += 1;
}
}
log(
`Vue-owned DOM nodes sampled: ${foundVueNodes}`
);
} catch (_) {}
return roots;
}
function collectMeshes(root) {
const meshes = [];
const seen = new WeakSet();
function walk(obj) {
if (
!obj ||
typeof obj !== 'object' ||
seen.has(obj)
) {
return;
}
seen.add(obj);
if (
obj.isMesh === true &&
obj.geometry?.attributes?.position
) {
meshes.push(obj);
}
if (Array.isArray(obj.children)) {
for (const child of obj.children) {
walk(child);
}
}
}
walk(root);
return meshes;
}
function attributeToFloat32(attr, itemSize) {
if (!attr || !attr.count) return null;
if (
attr.isInterleavedBufferAttribute !== true &&
attr.array instanceof Float32Array &&
attr.itemSize === itemSize
) {
return new Float32Array(
attr.array.buffer.slice(
attr.array.byteOffset,
attr.array.byteOffset + attr.array.byteLength
)
);
}
const out =
new Float32Array(
attr.count * itemSize
);
for (
let i = 0;
i < attr.count;
i += 1
) {
if (itemSize >= 1) {
out[i * itemSize] =
attr.getX(i);
}
if (itemSize >= 2) {
out[i * itemSize + 1] =
attr.getY(i);
}
if (itemSize >= 3) {
out[i * itemSize + 2] =
attr.getZ(i);
}
if (itemSize >= 4) {
out[i * itemSize + 3] =
attr.getW(i);
}
}
return out;
}
function copyIndexArray(indexAttr) {
if (!indexAttr?.array) return null;
const src = indexAttr.array;
if (src instanceof Uint8Array) {
return new Uint8Array(src);
}
if (src instanceof Uint16Array) {
return new Uint16Array(src);
}
if (src instanceof Uint32Array) {
return new Uint32Array(src);
}
let max = 0;
for (
let i = 0;
i < indexAttr.count;
i += 1
) {
max = Math.max(
max,
indexAttr.getX(i)
);
}
const OutType =
max <= 65535
? Uint16Array
: Uint32Array;
const out =
new OutType(
indexAttr.count
);
for (
let i = 0;
i < indexAttr.count;
i += 1
) {
out[i] =
indexAttr.getX(i);
}
return out;
}
function indexComponentType(indices) {
if (indices instanceof Uint8Array) {
return 5121;
}
if (indices instanceof Uint16Array) {
return 5123;
}
if (indices instanceof Uint32Array) {
return 5125;
}
throw new Error(
`Unsupported index type: ${
indices?.constructor?.name ?? 'unknown'
}`
);
}
async function imageToPNGBytes(image) {
const width =
image?.width ??
image?.videoWidth ??
image?.naturalWidth ??
0;
const height =
image?.height ??
image?.videoHeight ??
image?.naturalHeight ??
0;
if (!width || !height) {
throw new Error(
'Texture image has no usable dimensions.'
);
}
const canvas =
document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx =
canvas.getContext('2d');
if (!ctx) {
throw new Error(
'Could not create 2D canvas context.'
);
}
ctx.drawImage(
image,
0,
0,
width,
height
);
const blob =
await new Promise(
(resolve, reject) => {
canvas.toBlob(
(b) =>
b
? resolve(b)
: reject(
new Error(
'Canvas PNG conversion failed.'
)
),
'image/png'
);
}
);
return new Uint8Array(
await blob.arrayBuffer()
);
}
// ─────────────────────────────────────────────
// 1. Locate Vue app
// ─────────────────────────────────────────────
const appEl =
document.querySelector('[data-v-app]') ||
document.querySelector('#__nuxt');
const vueApp =
appEl?.__vue_app__;
if (!vueApp) {
throw new Error(
'Vue app not found. Open a loaded Tripo Studio model page first.'
);
}
log('Vue app found');
// ─────────────────────────────────────────────
// 2. Find actual live Three.js scene
// ─────────────────────────────────────────────
const roots =
collectDiscoveryRoots(
vueApp,
appEl
);
log(
`Discovery roots collected: ${roots.length}`
);
const scene =
deepFindScene(
roots,
{
maxDepth: 18,
maxNodes: 120000
}
);
if (
!scene?.isScene &&
!(
scene?.type === 'Scene' &&
scene?.isObject3D
)
) {
// Keep useful references accessible from the console so we can inspect
// the actual Tripo renderer structure if this still fails.
window.__TRIPO_EXTRACT_DEBUG__ = {
vueApp,
appEl,
roots,
canvases:
Array.from(
document.querySelectorAll(
'canvas'
)
)
};
throw new Error(
'Three.js scene still not reachable from Vue/DOM object graph. ' +
'Saved diagnostic roots to window.__TRIPO_EXTRACT_DEBUG__.'
);
}
log(
'Scene found:',
scene.type,
'— children:',
scene.children?.length ?? 0
);
try {
scene.updateMatrixWorld?.(true);
} catch (_) {}
// ─────────────────────────────────────────────
// 3. Locate likely generated model
// ─────────────────────────────────────────────
const allMeshes =
collectMeshes(scene);
if (!allMeshes.length) {
throw new Error(
'Scene was found, but it contains no usable meshes.'
);
}
log(
'Usable meshes found:',
allMeshes.length
);
const rankedMeshes =
allMeshes
.map((mesh) => ({
mesh,
vertices:
mesh.geometry
?.attributes
?.position
?.count ?? 0,
indices:
mesh.geometry
?.index
?.count ?? 0,
hasUV:
!!mesh.geometry
?.attributes
?.uv,
hasTexture:
Array.isArray(
mesh.material
)
? mesh.material.some(
(m) =>
!!m?.map?.image
)
: !!mesh.material
?.map
?.image
}))
.sort(
(a, b) =>
b.vertices -
a.vertices
);
console.table(
rankedMeshes
.slice(0, 12)
.map(
(entry, i) => ({
rank:
i + 1,
name:
entry.mesh.name ||
'(unnamed)',
vertices:
entry.vertices,
indices:
entry.indices,
uv:
entry.hasUV,
texture:
entry.hasTexture
})
)
);
const modelMesh =
rankedMeshes[0].mesh;
const geometry =
modelMesh.geometry;
const positions =
attributeToFloat32(
geometry.attributes.position,
3
);
const uvs =
attributeToFloat32(
geometry.attributes.uv,
2
);
const indices =
copyIndexArray(
geometry.index
);
if (!positions?.length) {
throw new Error(
'Selected model mesh has no usable position data.'
);
}
const vertexCount =
positions.length / 3;
const indexCount =
indices?.length ?? 0;
log(
`Selected mesh: "${
modelMesh.name ||
'(unnamed)'
}" — ` +
`${vertexCount} vertices, ` +
`${indexCount} indices`
);
// ─────────────────────────────────────────────
// 4. Extract base-color texture
// ─────────────────────────────────────────────
let material =
modelMesh.material;
if (Array.isArray(material)) {
material =
material.find(
(m) =>
m?.map?.image
) ||
material[0] ||
null;
}
let texturePNGBytes =
null;
if (material?.map?.image) {
try {
texturePNGBytes =
await imageToPNGBytes(
material.map.image
);
log(
`Texture extracted: ${
(
texturePNGBytes.byteLength /
1024
).toFixed(0)
} KB PNG`
);
} catch (err) {
warn(
'Texture extraction failed; exporting geometry without texture.',
err
);
}
} else {
warn(
'No diffuse/base-color texture image found on selected mesh.'
);
}
// ─────────────────────────────────────────────
// 5. Binary buffer layout
// ─────────────────────────────────────────────
const align4 =
(n) =>
(n + 3) & ~3;
const posBytes =
positions.byteLength;
const uvBytes =
uvs
? uvs.byteLength
: 0;
const idxBytes =
indices
? indices.byteLength
: 0;
const texBytes =
texturePNGBytes
? texturePNGBytes.byteLength
: 0;
const posOffset =
0;
const uvOffset =
align4(
posOffset +
posBytes
);
const idxOffset =
align4(
uvOffset +
uvBytes
);
const texOffset =
align4(
idxOffset +
idxBytes
);
const totalBin =
align4(
texOffset +
texBytes
);
// ─────────────────────────────────────────────
// 6. Position bounds
// ─────────────────────────────────────────────
const minPos = [
Infinity,
Infinity,
Infinity
];
const maxPos = [
-Infinity,
-Infinity,
-Infinity
];
for (
let i = 0;
i < positions.length;
i += 3
) {
const x =
positions[i];
const y =
positions[i + 1];
const z =
positions[i + 2];
if (x < minPos[0]) {
minPos[0] = x;
}
if (y < minPos[1]) {
minPos[1] = y;
}
if (z < minPos[2]) {
minPos[2] = z;
}
if (x > maxPos[0]) {
maxPos[0] = x;
}
if (y > maxPos[1]) {
maxPos[1] = y;
}
if (z > maxPos[2]) {
maxPos[2] = z;
}
}
// ─────────────────────────────────────────────
// 7. glTF structures
// ─────────────────────────────────────────────
const accessors = [];
const bufferViews = [];
const attributes = {};
const positionBufferView =
bufferViews.length;
bufferViews.push({
buffer: 0,
byteOffset: posOffset,
byteLength: posBytes,
target: 34962
});
const positionAccessor =
accessors.length;
accessors.push({
bufferView:
positionBufferView,
byteOffset:
0,
componentType:
5126,
count:
vertexCount,
type:
'VEC3',
min:
minPos,
max:
maxPos
});
attributes.POSITION =
positionAccessor;
if (uvs) {
const uvBufferView =
bufferViews.length;
bufferViews.push({
buffer:
0,
byteOffset:
uvOffset,
byteLength:
uvBytes,
target:
34962
});
const uvAccessor =
accessors.length;
accessors.push({
bufferView:
uvBufferView,
byteOffset:
0,
componentType:
5126,
count:
uvs.length / 2,
type:
'VEC2'
});
attributes.TEXCOORD_0 =
uvAccessor;
}
let indicesAccessor =
null;
if (indices) {
const indexBufferView =
bufferViews.length;
bufferViews.push({
buffer:
0,
byteOffset:
idxOffset,
byteLength:
idxBytes,
target:
34963
});
indicesAccessor =
accessors.length;
accessors.push({
bufferView:
indexBufferView,
byteOffset:
0,
componentType:
indexComponentType(
indices
),
count:
indices.length,
type:
'SCALAR'
});
}
let imageBufferView =
null;
if (texturePNGBytes) {
imageBufferView =
bufferViews.length;
bufferViews.push({
buffer:
0,
byteOffset:
texOffset,
byteLength:
texBytes
});
}
const primitive = {
attributes,
mode: 4
};
if (indicesAccessor !== null) {
primitive.indices =
indicesAccessor;
}
if (imageBufferView !== null) {
primitive.material =
0;
}
const gltf = {
asset: {
version:
'2.0',
generator:
'tripo3d-browser-extractor-deep-scan'
},
scene:
0,
scenes: [
{
name:
'Scene',
nodes:
[0]
}
],
nodes: [
{
name:
modelMesh.name ||
'tripo_model',
mesh:
0,
...(
modelMesh
.matrixWorld
?.elements
?.length === 16
? {
matrix:
Array.from(
modelMesh
.matrixWorld
.elements
)
}
: {}
)
}
],
meshes: [
{
name:
'tripo_mesh',
primitives:
[primitive]
}
],
accessors,
bufferViews,
buffers: [
{
byteLength:
totalBin
}
]
};
if (imageBufferView !== null) {
gltf.materials = [
{
name:
'tripo_mat',
pbrMetallicRoughness: {
baseColorTexture: {
index: 0
},
metallicFactor:
0.0,
roughnessFactor:
0.5
},
doubleSided:
true
}
];
gltf.textures = [
{
source: 0
}
];
gltf.images = [
{
mimeType:
'image/png',
bufferView:
imageBufferView
}
];
}
// ─────────────────────────────────────────────
// 8. Assemble GLB
// ─────────────────────────────────────────────
const jsonBytes =
new TextEncoder()
.encode(
JSON.stringify(gltf)
);
const jsonPaddedLength =
align4(
jsonBytes.length
);
const totalSize =
12
+ 8
+ jsonPaddedLength
+ 8
+ totalBin;
const glb =
new ArrayBuffer(
totalSize
);
const view =
new DataView(glb);
const bytes =
new Uint8Array(glb);
let offset =
0;
// GLB header
view.setUint32(
offset,
0x46546c67,
true
);
offset += 4;
view.setUint32(
offset,
2,
true
);
offset += 4;
view.setUint32(
offset,
totalSize,
true
);
offset += 4;
// JSON chunk
view.setUint32(
offset,
jsonPaddedLength,
true
);
offset += 4;
view.setUint32(
offset,
0x4e4f534a,
true
);
offset += 4;
bytes.set(
jsonBytes,
offset
);
for (
let i = jsonBytes.length;
i < jsonPaddedLength;
i += 1
) {
bytes[offset + i] =
0x20;
}
offset +=
jsonPaddedLength;
// BIN chunk
view.setUint32(
offset,
totalBin,
true
);
offset += 4;
view.setUint32(
offset,
0x004e4942,
true
);
offset += 4;
const binStart =
offset;
bytes.set(
new Uint8Array(
positions.buffer,
positions.byteOffset,
positions.byteLength
),
binStart +
posOffset
);
if (uvs) {
bytes.set(
new Uint8Array(
uvs.buffer,
uvs.byteOffset,
uvs.byteLength
),
binStart +
uvOffset
);
}
if (indices) {
bytes.set(
new Uint8Array(
indices.buffer,
indices.byteOffset,
indices.byteLength
),
binStart +
idxOffset
);
}
if (texturePNGBytes) {
bytes.set(
texturePNGBytes,
binStart +
texOffset
);
}
// ─────────────────────────────────────────────
// 9. Validate
// ─────────────────────────────────────────────
if (
view.getUint32(
0,
true
) !== 0x46546c67
) {
throw new Error(
'GLB validation failed: bad magic header.'
);
}
if (
view.getUint32(
8,
true
) !== totalSize
) {
throw new Error(
'GLB validation failed: file length mismatch.'
);
}
// ─────────────────────────────────────────────
// 10. Trigger browser save
// ─────────────────────────────────────────────
const modelId =
window.location.pathname
.split('/')
.filter(Boolean)
.pop() ||
'model';
const filename =
`tripo_${modelId}.glb`;
const fileMB =
(
totalSize /
1024 /
1024
).toFixed(2);
const blob =
new Blob(
[glb],
{
type:
'model/gltf-binary'
}
);
const url =
URL.createObjectURL(
blob
);
const a =
document.createElement(
'a'
);
a.href =
url;
a.download =
filename;
a.style.display =
'none';
document.body.appendChild(
a
);
a.click();
a.remove();
setTimeout(
() => {
URL.revokeObjectURL(
url
);
},
10000
);
log(
`✓ Download triggered: ${filename} (${fileMB} MB)`
);
return {
filename,
fileMB,
meshName:
modelMesh.name ||
'(unnamed)',
vertices:
vertexCount,
indices:
indexCount,
meshesFound:
allMeshes.length,
textureIncluded:
!!texturePNGBytes
};
})();```
i am getting this error VM1056:388 Uncaught (in promise) Error: Scene was found, but it contains no usable meshes.
at :388:32
used the updated code of 28-09 -2026
i tried to fix with the claude it seems to work .. i didnt gone in detail 😭 . just wanted a model to download and use in my portfolio . btw thanks for the script
Promise {: Error: "Context" TresJS component not found in vnode tree.
at extractTripoGLB (:75:2…}
VM390:75 Uncaught (in promise) Error: "Context" TresJS component not found in vnode tree.
at extractTripoGLB (:75:27)
at :291:3
Hey i am getting this error, i dont even know what is wrong
Is this a Chrome issue or something, because every one of these scripts returns an error. Someone just needs to make a Chrome extension for this.
someone pls update this
/**
- Tripo Studio local GLB exporter - all in one
- Paste into DevTools Console while your model is visible.
- Finds an accessible Three.js scene and exports meshes/textures already
- loaded by the browser. It cannot unlock assets absent from the viewer.
- No third-party imports or network requests.
*/
(async () => {
'use strict';
const TAG = '[tripo-export]';
const log = (...x) => console.log(TAG, ...x);
const warn = (...x) => console.warn(TAG, ...x);
const align = n => Math.ceil(n / 4) * 4;
const unwrap = x => { try { return x?.__v_isRef === true ? x.value : x; } catch { return x; } };
const isScene = x => {
x = unwrap(x);
return !!x && (x.isScene === true || (x.type === 'Scene' && x.isObject3D === true && Array.isArray(x.children)));
};
const walk3D = root => {
const out = [], stack = [root], seen = new Set();
while (stack.length) {
const x = stack.pop();
if (!x || seen.has(x)) continue;
seen.add(x); out.push(x);
for (const c of [...(x.children || [])].reverse()) stack.push(c);
}
return out;
};
const meshesOf = obj => walk3D(obj).filter(x => x.isMesh && x.geometry?.attributes?.position?.count > 0);
const verticesOf = obj => meshesOf(obj).reduce((n, m) => n + m.geometry.attributes.position.count, 0);
function findScene() {
const roots = [], seenRoots = new Set(), found = new Set();
const add = v => {
if (v && (typeof v === 'object' || typeof v === 'function') && !seenRoots.has(v)) {
roots.push(v); seenRoots.add(v);
}
};
add(window.TRIPO_SCENE);
add(window.tripoScene);
add(window.tres);
for (const el of document.querySelectorAll('#__nuxt, [data-v-app], canvas')) {
add(el.__vueParentComponent);
add(el.__vnode);
const app = el.vue_app;
if (!app) continue;
add(app); add(app._instance); add(app._context); add(app._container?.vnode);
const router = app.config?.globalProperties?.$router;
add(router); add(router?.currentRoute?.value);
for (const route of router?.currentRoute?.value?.matched || []) {
add(route);
for (const v of Object.values(route.instances || {})) { add(v); add(v?.); }
}
}
// Teleported viewer components may be outside the #__nuxt DOM subtree.
let domVue = 0;
for (const el of document.querySelectorAll('*')) {
if (domVue >= 600) break;
if (el.__vueParentComponent || el.__vnode) {
add(el.__vueParentComponent); add(el.__vnode); domVue++;
}
}
const seen = new WeakSet(), queue = roots.map(v => [v, 0]);
let head = 0, scanned = 0;
const put = (v, d) => {
v = unwrap(v);
if (v && (typeof v === 'object' || typeof v === 'function') && d <= 24 && queue.length < 250000)
queue.push([v, d]);
};
while (head < queue.length && scanned < 100000) {
const [raw, d] = queue[head++], obj = unwrap(raw);
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function') || seen.has(obj)) continue;
seen.add(obj); scanned++;
if (isScene(obj)) { found.add(obj); continue; }
if (d >= 24 || obj === window || obj === document ||
(typeof Node !== 'undefined' && obj instanceof Node) ||
ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer) continue;
if (Array.isArray(obj)) {
for (const v of obj.slice(0, 600)) put(v, d + 1);
continue;
}
if (obj instanceof Map || obj instanceof Set) {
let count = 0;
for (const v of obj instanceof Map ? obj.entries() : obj.values()) {
if (++count > 400) break;
if (obj instanceof Map) { put(v[0], d + 1); put(v[1], d + 1); }
else put(v, d + 1);
}
continue;
}
try {
if (obj.provides) {
let p = obj.provides;
for (let n = 0; p && n < 8; n++, p = Object.getPrototypeOf(p)) put(p, d + 1);
}
} catch {}
let keys;
try { keys = Reflect.ownKeys(obj); } catch { continue; }
for (const key of keys.slice(0, 600)) {
if (['window','self','globalThis','document','ownerDocument','defaultView','parentNode','parentElement','nextSibling','previousSibling'].includes(String(key))) continue;
try {
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor && 'value' in descriptor) put(descriptor.value, d + 1);
} catch {}
}
}
const candidates = [...found].sort((a, b) => verticesOf(b) - verticesOf(a));
log('Scene search:', { vueRoots: roots.length, vueNodes: domVue, objectsScanned: scanned,
scenesFound: candidates.length, vertexCounts: candidates.map(verticesOf) });
if (!candidates.length) throw new Error('No Three.js scene found. The viewer may not expose it through Vue; check the scene-search diagnostics above.');
window.TRIPO_SCENE = candidates[0];
return candidates[0];
}
function selectModel(scene, opts = {}) {
const all = walk3D(scene), meshes = all.filter(x => x.isMesh && x.geometry?.attributes?.position?.count);
if (!meshes.length) throw new Error('A scene was found, but contains no loaded meshes.');
const pattern = opts.nameIncludes ? String(opts.nameIncludes) : 'tripo[_ -]?node';
const reg = new RegExp(pattern.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'i');
const matches = all.filter(x => x !== scene && (opts.nameIncludes ? reg.test(x.name || '') : /tripo[_ -]?node/i.test(x.name || '')) && verticesOf(x));
if (matches.length) return matches.sort((a, b) => verticesOf(b) - verticesOf(a))[0];
if (opts.nameIncludes) throw new Error('No object matched: ' + opts.nameIncludes);
meshes.sort((a, b) => b.geometry.attributes.position.count - a.geometry.attributes.position.count);
const main = meshes[0];
let root = main;
for (let p = main.parent; p && p !== scene; p = p.parent) {
const kids = meshesOf(p);
if (kids.length > 24 || verticesOf(p) > verticesOf(main) * 5) break;
root = p;
}
return root;
}
function attributeData(attr, dims) {
if (!attr || attr.itemSize < dims || !Number.isFinite(attr.count)) return null;
const get = ['getX','getY','getZ','getW'];
const out = new Float32Array(attr.count * dims);
for (let i = 0; i < attr.count; i++) for (let d = 0; d < dims; d++) {
const n = attrget[d];
out[i * dims + d] = Number.isFinite(n) ? n : 0;
}
return out;
}
function smoothNormals(pos, geom) {
const out = new Float32Array(pos.length), idx = geom.index, count = idx ? idx.count : pos.length / 3;
for (let i = 0; i + 2 < count; i += 3) {
const a = (idx ? idx.getX(i) : i) * 3;
const b = (idx ? idx.getX(i+1) : i+1) * 3;
const c = (idx ? idx.getX(i+2) : i+2) * 3;
if (a < 0 || b < 0 || c < 0 || a+2 >= pos.length || b+2 >= pos.length || c+2 >= pos.length) continue;
const ux=pos[b]-pos[a], uy=pos[b+1]-pos[a+1], uz=pos[b+2]-pos[a+2];
const vx=pos[c]-pos[a], vy=pos[c+1]-pos[a+1], vz=pos[c+2]-pos[a+2];
const nx=uyvz-uzvy, ny=uzvx-uxvz, nz=uxvy-uyvx;
for (const j of [a,b,c]) { out[j]+=nx; out[j+1]+=ny; out[j+2]+=nz; }
}
for (let i=0;i<out.length;i+=3) {
const length=Math.hypot(out[i],out[i+1],out[i+2]);
if (length > 1e-9) { out[i]/=length; out[i+1]/=length; out[i+2]/=length; }
else out[i+2]=1;
}
return out;
}
async function pngBytes(texture) {
const image = texture?.source?.data || texture?.image;
const w = image?.width || image?.naturalWidth, h = image?.height || image?.naturalHeight;
if (!w || !h) throw new Error('texture pixel data unavailable');
const canvas = document.createElement('canvas');
canvas.width = w; canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('cannot create canvas');
if (image.data && ArrayBuffer.isView(image.data)) {
if (image.data.length !== wh4) throw new Error('unsupported texture data layout');
ctx.putImageData(new ImageData(new Uint8ClampedArray(image.data), w, h), 0, 0);
if (texture.flipY) {
const flipped = document.createElement('canvas');
flipped.width = w; flipped.height = h;
const fc = flipped.getContext('2d');
fc.translate(0,h); fc.scale(1,-1); fc.drawImage(canvas,0,0);
const blob = await new Promise(ok => flipped.toBlob(ok,'image/png'));
if (!blob) throw new Error('PNG conversion failed');
return new Uint8Array(await blob.arrayBuffer());
}
} else {
if (texture.flipY) { ctx.translate(0,h); ctx.scale(1,-1); }
ctx.drawImage(image,0,0,w,h);
}
const blob = await new Promise(ok => canvas.toBlob(ok,'image/png'));
if (!blob) throw new Error('PNG conversion failed (possibly cross-origin image)');
return new Uint8Array(await blob.arrayBuffer());
}
async function exportGLB(root, scene, opts = {}) {
scene.updateMatrixWorld?.(true);
const rootInverse = root.matrixWorld?.clone?.().invert?.();
const json = { asset: {version:'2.0',generator:'Tripo local exporter'},scene:0,scenes:[{nodes:[]}],
nodes:[],meshes:[],accessors:[],bufferViews:[],buffers:[{byteLength:0}],
materials:[],images:[],textures:[],samplers:[] };
const pieces = []; let binaryLength = 0, triangles = 0;
const addView = (bytes, target) => {
const offset = align(binaryLength);
binaryLength = offset + bytes.length;
pieces.push({bytes,offset});
const view = {buffer:0,byteOffset:offset,byteLength:bytes.length};
if (target) view.target = target;
return json.bufferViews.push(view)-1;
};
const accessor = (typed, type, target, min, max) => {
const view = addView(new Uint8Array(typed.buffer,typed.byteOffset,typed.byteLength),target);
const componentType = typed instanceof Float32Array ? 5126 : typed instanceof Uint16Array ? 5123 : 5125;
const result = {bufferView:view,componentType,count:typed.length / ({SCALAR:1,VEC2:2,VEC3:3,VEC4:4}[type]),type};
if (min && max) {result.min=min;result.max=max;}
return json.accessors.push(result)-1;
};
const texCache = new Map(), matCache = new Map();
const texIndex = async texture => {
if (!texture) return null;
if (texCache.has(texture)) return texCache.get(texture);
let result = null;
try {
const bytes = await pngBytes(texture);
const imageIdx = json.images.push({mimeType:'image/png',bufferView:addView(bytes)})-1;
const wrap = {1000:10497,1001:33071,1002:33648};
const samplerIdx = json.samplers.push({wrapS:wrap[texture.wrapS] || 10497,wrapT:wrap[texture.wrapT] || 10497})-1;
result = json.textures.push({source:imageIdx,sampler:samplerIdx})-1;
} catch (e) {warn('Could not embed texture:',e.message);}
texCache.set(texture,result);
return result;
};
const matIndex = async (mat, hasUV) => {
if (!mat) return null;
const variant = hasUV ? 'uv' : 'plain';
let variants=matCache.get(mat);
if (variants?.has(variant)) return variants.get(variant);
if (!variants) { variants = new Map(); matCache.set(mat,variants); }
const col=mat.color || {r:1,g:1,b:1},alpha=mat.opacity ?? 1;
const out={name:mat.name || 'Material',doubleSided:mat.side === 2,
pbrMetallicRoughness:{baseColorFactor:[col.r??1,col.g??1,col.b??1,alpha],
metallicFactor:mat.metalness??0,roughnessFactor:mat.roughness??1}};
if (mat.transparent || alpha<1) out.alphaMode='BLEND';
else if (mat.alphaTest>0) {out.alphaMode='MASK';out.alphaCutoff=mat.alphaTest;}
if (mat.emissive) out.emissiveFactor=[mat.emissive.r||0,mat.emissive.g||0,mat.emissive.b||0];
if (hasUV) {
for (const [key,container,field] of [
['map',out.pbrMetallicRoughness,'baseColorTexture'],
['normalMap',out,'normalTexture'],['emissiveMap',out,'emissiveTexture']]) {
const index=await texIndex(mat[key]);
if (index !== null) container[field]={index};
}
}
const index=json.materials.push(out)-1;
variants.set(variant,index);
return index;
};
for (const mesh of meshesOf(root)) {
const g=mesh.geometry,pos=attributeData(g.attributes.position,3);
if (!pos || pos.length<9) continue;
const count=pos.length/3, min=[Infinity,Infinity,Infinity],max=[-Infinity,-Infinity,-Infinity];
for (let i=0;i<pos.length;i+=3) for (let j=0;j<3;j++) {
min[j]=Math.min(min[j],pos[i+j]);max[j]=Math.max(max[j],pos[i+j]);
}
const attrs={POSITION:accessor(pos,'VEC3',34962,min,max)};
let normals=opts.recomputeNormals ? null : attributeData(g.attributes.normal,3);
if (!normals || normals.length!==pos.length) normals=smoothNormals(pos,g);
attrs.NORMAL=accessor(normals,'VEC3',34962);
const uv=attributeData(g.attributes.uv,2);
if (uv && uv.length===count2) attrs.TEXCOORD_0=accessor(uv,'VEC2',34962);
const color=attributeData(g.attributes.color,g.attributes.color?.itemSize === 4 ? 4 : 3);
if (color && (color.length===count3 || color.length===count4))
attrs.COLOR_0=accessor(color,color.length===count4?'VEC4':'VEC3',34962);
const materials=Array.isArray(mesh.material)?mesh.material:[mesh.material];
const limit=g.index?.count ?? count, range=g.drawRange || {start:0,count:Infinity};
const groups=g.groups?.length?g.groups:[{start:0,count:limit,materialIndex:0}];
const primitives=[];
for (const group of groups) {
const start=Math.max(0,group.start,range.start || 0);
const end=Math.min(limit,group.start+group.count,(range.start || 0)+(range.count ?? Infinity));
const n=Math.floor((end-start)/3)*3;
if (n<=0) continue;
const indices=new Array(n);let biggest=0,valid=true;
for (let i=0;i<n;i++) {
const index=g.index?g.index.getX(start+i):start+i;
if (!Number.isInteger(index)||index<0||index>=count) {valid=false;break;}
indices[i]=index;biggest=Math.max(biggest,index);
}
if (!valid) {warn('Invalid indices in',mesh.name);continue;}
const idx=biggest<65536?Uint16Array.from(indices):Uint32Array.from(indices);
const primitive={attributes:attrs,indices:accessor(idx,'SCALAR',34963),mode:4};
const mi=await matIndex(materials[group.materialIndex || 0] || materials[0],!!attrs.TEXCOORD_0);
if (mi!==null) primitive.material=mi;
primitives.push(primitive);triangles+=n/3;
}
if (!primitives.length) continue;
const meshIdx=json.meshes.push({name:mesh.name||'Mesh',primitives})-1;
const node={name:mesh.name||'Mesh',mesh:meshIdx};
if (rootInverse && mesh.matrixWorld) {
const matrix=rootInverse.clone().multiply(mesh.matrixWorld).elements;
if (Array.from(matrix).every(Number.isFinite)) node.matrix=Array.from(matrix);
}
json.scenes[0].nodes.push(json.nodes.push(node)-1);
if (mesh.isSkinnedMesh || Object.keys(g.morphAttributes || {}).length)
warn(Mesh '${mesh.name}' has animation/skin/morphs; only its base shape was exported.);
}
if (!json.meshes.length) throw new Error('No exportable triangle meshes found in the selected object.');
for (const key of ['materials','images','textures','samplers']) if (!json[key].length) delete json[key];
json.buffers[0].byteLength=align(binaryLength);
const jsonBytes=new TextEncoder().encode(JSON.stringify(json));
const jsonLength=align(jsonBytes.length), binLength=align(binaryLength);
const length=12+8+jsonLength+8+binLength;
if (length>0xffffffff) throw new Error('GLB exceeds the 4GB format limit.');
const glb=new ArrayBuffer(length),bytes=new Uint8Array(glb),dv=new DataView(glb);
dv.setUint32(0,0x46546c67,true);dv.setUint32(4,2,true);dv.setUint32(8,length,true);
dv.setUint32(12,jsonLength,true);dv.setUint32(16,0x4e4f534a,true);
bytes.fill(32,20,20+jsonLength);bytes.set(jsonBytes,20);
const binStart=20+jsonLength;
dv.setUint32(binStart,binLength,true);dv.setUint32(binStart+4,0x004e4942,true);
for (const p of pieces) bytes.set(p.bytes,binStart+8+p.offset);
return {glb,stats:{meshes:json.meshes.length,triangles,textures:json.images?.length||0,
sizeMB:(length/1048576).toFixed(2)}};
}
let scene;
try { scene=findScene(); }
catch (e) { console.error(TAG,e); return; }
window.tripoLocalExporter = {
list() {
const rows=meshesOf(scene).map(m=>({name:m.name||'(unnamed)',vertices:m.geometry.attributes.position.count,parent:m.parent?.name||''}));
console.table(rows);return rows;
},
async download(opts={}) {
const root=selectModel(scene,opts);
log('Selected:',root.name||'(unnamed)','meshes:',meshesOf(root).length);
const {glb,stats}=await exportGLB(root,scene,opts);
const id=location.pathname.split('/').filter(Boolean).pop()?.replace(/[^a-zA-Z0-9_-]/g,'_')||'model';
const filename=tripo_local_${id}.glb;
const url=URL.createObjectURL(new Blob([glb],{type:'model/gltf-binary'}));
const a=document.createElement('a');a.href=url;a.download=filename;
document.body.appendChild(a);a.click();a.remove();
setTimeout(()=>URL.revokeObjectURL(url),60000);
log('Download requested:',filename,stats);
return {filename,...stats};
}
};
try { await window.tripoLocalExporter.download(); }
catch (e) { console.error(TAG,'Export failed:',e); log('Available meshes: tripoLocalExporter.list()'); }
})();
Done just copy-paste inside console
idk what i you talk about it worked for me, oh yeah it only work inside the 3d workspace.
sorry can't help
Thanks @gammers422
https://drive.google.com/file/d/1a9m01z2GpJOunh6bblKsqA7_VPlhLbae/view?usp=sharing
Worked perfectly and is so easy to use, is there a github repository dedicated to this extension?
someone report account Sus31415 please thx
Any fixes for now?
Ive got a decent version, takes both textures and glb into one
/**
- tripo3d_model_downloader.js
- ─────────────────────────────────────────────────────────────────────────────
- Extracts the loaded 3D model directly from the TresJS/Three.js renderer on
- studio.tripo3d.ai and downloads it as a .glb.
- HOW IT WORKS
- ─────────────────────────────────────────────────────────────────────────────
-
- The site is a Nuxt 3 / Vue 3 app using TresJS (Vue wrapper for Three.js).
-
- The Vue app is mounted on #__nuxt with vue_app attached to the element.
-
- The whole component tree (including Suspense / Teleport branches) is
- walked from the root instance until a component that provides
useTres - (the TresJS context: { scene, camera, renderer }) is found.
-
- The model meshes (named "tripo_node_" or nested under such a
- node) are collected. If none are named that way, every visible mesh that
- isn't a trivial helper (ground plane, background quad) is exported.
-
- Attributes are read through the BufferAttribute API, so interleaved,
- quantized and normalized attributes are converted to plain floats.
-
- Textures (base color, normal, metal/rough, AO, emissive) are drawn to an
- offscreen canvas and embedded as PNG.
-
- A valid GLB (glTF 2.0 binary) is assembled manually and downloaded.
- USAGE
- ─────────────────────────────────────────────────────────────────────────────
- Paste this entire script into the browser DevTools console while on any
- studio.tripo3d.ai/3d-model/ page and wait for the download prompt.
- Edit OPTIONS below to change behaviour.
- TESTED ON
- ─────────────────────────────────────────────────────────────────────────────
- Three.js r183, TresJS, Nuxt 3, Pinia — May 2026
*/
(async function extractTripoGLB() {
const OPTIONS = {
// Tripo's generated normals are often inconsistent; leaving them out makes
// Blender & co. recompute smooth normals from the face winding.
includeNormals: false,
// false = only export the single mesh with the most vertices.
exportAllMeshes: true,
// Meshes with fewer vertices than this are treated as helpers and skipped
// when no "tripo_node_*" meshes are found.
minHelperVertexCount: 64,
};
const TAG = '[tripo-extract]';
const log = (...a) => console.log(TAG, ...a);
const warn = (...a) => console.warn(TAG, ...a);
const GL = {
FLOAT: 5126, UNSIGNED_SHORT: 5123, UNSIGNED_INT: 5125,
ARRAY_BUFFER: 34962, ELEMENT_ARRAY_BUFFER: 34963,
TRIANGLES: 4,
};
const THREE_CONST = {
DoubleSide: 2,
RepeatWrapping: 1000, ClampToEdgeWrapping: 1001, MirroredRepeatWrapping: 1002,
NearestFilter: 1003, LinearFilter: 1006,
};
const WRAP_TO_GL = {
[THREE_CONST.RepeatWrapping]: 10497,
[THREE_CONST.ClampToEdgeWrapping]: 33071,
[THREE_CONST.MirroredRepeatWrapping]: 33648,
};
const align4 = n => (n + 3) & ~3;
const toRaw = v => (v && v.__v_raw) || v;
const unref = v => toRaw(v && v.__v_isRef ? v.value : v);
const bytesOf = t => new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
try {
// ── 1. Locate the Vue app ───────────────────────────────────────────────
const appEl = [document.querySelector('#__nuxt'), ...document.querySelectorAll('[data-v-app]')]
.find(el => el && el.vue_app);
if (!appEl) throw new Error('Vue app not found. Are you on a Tripo Studio model page?');
const vueApp = appEl.vue_app;
// ── 2. Walk every component instance and find the TresJS context ────────
function* walkInstances(root) {
const seen = new Set();
const stack = [root];
while (stack.length) {
const node = stack.pop();
if (!node || typeof node !== 'object' || seen.has(node)) continue;
seen.add(node);
if (Array.isArray(node)) { stack.push(...node); continue; }
const isInstance = 'subTree' in node && 'vnode' in node && 'uid' in node;
if (isInstance) {
yield node;
stack.push(node.subTree);
if (node.suspense) stack.push(node.suspense.activeBranch);
continue;
}
// vnode
if (node.component) stack.push(node.component);
if (node.suspense) stack.push(node.suspense.activeBranch);
if (Array.isArray(node.children)) stack.push(node.children);
if (Array.isArray(node.dynamicChildren)) stack.push(node.dynamicChildren);
}
}
function sceneFromInstance(inst) {
const candidates = [
inst.provides?.useTres,
inst.exposed?.context,
inst.setupState?.context,
];
for (const c of candidates) {
const ctx = unref(c);
const scene = unref(ctx?.scene);
if (scene?.isScene) return scene;
}
return null;
}
const rootInstance = vueApp._instance
|| vueApp.config?.globalProperties?.$router?.currentRoute?.value?.matched?.[0]?.instances?.default?._;
if (!rootInstance) throw new Error('Root Vue component instance not found.');
// Breadth-first search of an arbitrary object graph for a THREE.Scene (or
// any Object3D whose root is a Scene). Used when the scene lives outside
// the DOM component tree, e.g. in TresJS's separate custom-renderer tree.
function findSceneDeep(roots, budget = 400_000) {
const seen = new Set();
const queue = roots.slice();
for (let qi = 0; qi < queue.length && seen.size < budget && queue.length < 4_000_000; qi++) {
try {
const v = unref(queue[qi]);
if (!v || typeof v !== 'object' || seen.has(v)) continue;
seen.add(v);
if (v.isScene) return v;
if (v.isObject3D) {
let o = v;
while (o.parent) o = o.parent;
if (o.isScene) return o;
continue;
}
if (v === window || v instanceof Window || ArrayBuffer.isView(v) || v instanceof ArrayBuffer) continue;
if (v instanceof Node) {
queue.push(v.__vueParentComponent, v.__vnode, v._vnode);
continue;
}
if (v instanceof Map) { for (const [k, x] of v) queue.push(k, x); continue; }
if (v instanceof Set) { for (const x of v) queue.push(x); continue; }
for (const k of Object.keys(v)) queue.push(v[k]);
} catch { /* cross-origin or throwing getter */ }
}
return null;
}
function userGlobals() {
try {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
const builtins = new Set(Object.getOwnPropertyNames(iframe.contentWindow));
iframe.remove();
return Object.getOwnPropertyNames(window)
.filter(k => !builtins.has(k))
.map(k => { try { return window[k]; } catch { return null; } });
} catch { return []; }
}
const instances = [...walkInstances(rootInstance)];
let scene = null;
// Strategy 1: a component that provides/exposes the TresJS context.
for (const inst of instances) {
scene = sceneFromInstance(inst);
if (scene) break;
}
// Strategy 2: deep search through Vue state, Pinia stores, canvases and globals.
if (!scene) {
const pinia = vueApp.config?.globalProperties?.$pinia;
scene = findSceneDeep([
...(window.__tripoScenes ?? []).slice().reverse(),
...instances.flatMap(i => [i.exposed, i.provides, i.setupState, i.refs, i.props]),
pinia?._s, pinia?.state,
vueApp.config?.globalProperties,
...document.querySelectorAll('canvas'),
rootInstance,
...userGlobals(),
]);
}
if (!scene) {
// Three.js announces every new Scene to window.__THREE_DEVTOOLS__ on
// construction, so a hook installed now catches the next scene built.
if (!window.__tripoScenes) {
window.__tripoScenes = [];
const devtools = window.__THREE_DEVTOOLS__ || (window.__THREE_DEVTOOLS__ = new EventTarget());
devtools.addEventListener('observe', e => { if (e.detail?.isScene) window.__tripoScenes.push(e.detail); });
}
const names = [...new Set(instances.map(i => i.type?.name || i.type?.__name).filter(Boolean))];
console.group(`${TAG} diagnostics`);
log('THREE version (window.__THREE__):', window.__THREE__ ?? 'not set');
log('Canvases:', document.querySelectorAll('canvas').length,
'| iframes:', [...document.querySelectorAll('iframe')].map(f => f.src || '(no src)'));
log('Vue components walked:', instances.length);
log('3D-looking components:', names.filter(n => /tres|canvas|context|scene|viewer|model|three/i.test(n)));
log('Pinia stores:', [...(vueApp.config?.globalProperties?.$pinia?._s?.keys() ?? [])]);
console.groupEnd();
throw new Error(
'THREE.Scene not found. A capture hook is now installed: open a different model in the app ' +
'(click it, do NOT reload the page), come back to this one, then run the script again.');
}
log('Scene found — children:', scene.children.length);
// ── 3. Collect model meshes ─────────────────────────────────────────────
scene.updateMatrixWorld(true);
const visibleMeshes = [];
scene.traverseVisible(o => {
if (o.isMesh && o.geometry?.attributes?.position) visibleMeshes.push(o);
});
if (!visibleMeshes.length) throw new Error('No visible meshes in scene.');
const vertexCountOf = m => m.geometry.attributes.position.count;
const isTripoNode = m => {
for (let o = m; o; o = o.parent) if (/^tripo_node/.test(o.name)) return true;
return false;
};
let meshes = visibleMeshes.filter(isTripoNode);
if (!meshes.length) {
meshes = visibleMeshes.filter(m => vertexCountOf(m) >= OPTIONS.minHelperVertexCount);
if (!meshes.length) meshes = visibleMeshes;
}
if (!OPTIONS.exportAllMeshes || !meshes.length) {
meshes = [meshes.concat(visibleMeshes).reduce((a, b) => (vertexCountOf(b) > vertexCountOf(a) ? b : a))];
}
for (const m of meshes) {
if (m.isInstancedMesh) warn(`"${m.name}" is instanced — only the base geometry is exported.`);
if (m.isSkinnedMesh) warn(`"${m.name}" is skinned — exported in bind pose without skeleton.`);
log(`Mesh "${m.name || '(unnamed)'}" — ${vertexCountOf(m)} vertices, ${m.geometry.index?.count ?? 0} indices`);
}
// ── 4. glTF builder state ───────────────────────────────────────────────
const binParts = [];
let binLength = 0;
const bufferViews = [];
const accessors = [];
const images = [];
const samplers = [];
const textures = [];
const materials = [];
const gltfMeshes = [];
const nodes = [];
const imageCache = new Map();
const textureCache = new Map();
const materialCache = new Map();
function addBufferView(bytes, target) {
const byteOffset = binLength;
binParts.push({ byteOffset, bytes });
binLength = align4(byteOffset + bytes.byteLength);
bufferViews.push({ buffer: 0, byteOffset, byteLength: bytes.byteLength, ...(target ? { target } : {}) });
return bufferViews.length - 1;
}
function addAccessor(typed, componentType, type, count, target, extra = {}) {
const bufferView = addBufferView(bytesOf(typed), target);
accessors.push({ bufferView, byteOffset: 0, componentType, count, type, ...extra });
return accessors.length - 1;
}
// Reads any BufferAttribute / InterleavedBufferAttribute (incl. normalized
// integer attributes) into a tightly packed Float32Array.
function readAttribute(attr, itemSize = attr.itemSize) {
const getters = ['getX', 'getY', 'getZ', 'getW'];
const out = new Float32Array(attr.count * itemSize);
for (let i = 0; i < attr.count; i++) {
for (let k = 0; k < itemSize; k++) out[i * itemSize + k] = attr[getters[k]](i);
}
return out;
}
function computeMinMax(data, itemSize) {
const min = new Array(itemSize).fill(Infinity);
const max = new Array(itemSize).fill(-Infinity);
for (let i = 0; i < data.length; i += itemSize) {
for (let k = 0; k < itemSize; k++) {
const v = data[i + k];
if (v < min[k]) min[k] = v;
if (v > max[k]) max[k] = v;
}
}
return { min, max };
}
// ── 5. Textures ─────────────────────────────────────────────────────────
async function imageToPNG(tex) {
const img = tex.image;
if (!img) return null;
if (tex.isCompressedTexture) {
warn(`Texture "${tex.name}" is GPU-compressed (KTX2/Basis) and can't be read back — skipped.`);
return null;
}
const w = img.width ?? img.naturalWidth ?? img.videoWidth;
const h = img.height ?? img.naturalHeight ?? img.videoHeight;
if (!w || !h) {
warn(`Texture "${tex.name}" has no readable pixels (closed ImageBitmap?) — skipped.`);
return null;
}
const canvas = document.createElement('canvas');
canvas.width = w; canvas.height = h;
const ctx2d = canvas.getContext('2d');
if (tex.isDataTexture) {
const data = img.data;
if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray) || data.length !== w * h * 4) {
warn(`DataTexture "${tex.name}" is not 8-bit RGBA — skipped.`);
return null;
}
ctx2d.putImageData(new ImageData(new Uint8ClampedArray(data), w, h), 0, 0);
} else {
ctx2d.drawImage(img, 0, 0, w, h);
}
try {
const blob = await new Promise((resolve, reject) =>
canvas.toBlob(b => (b ? resolve(b) : reject(new Error('toBlob returned null'))), 'image/png'));
return new Uint8Array(await blob.arrayBuffer());
} catch (e) {
warn(`Could not encode texture "${tex.name}" (cross-origin canvas taint?) — skipped.`, e);
return null;
}
}
async function addTexture(tex) {
if (!tex) return null;
if (textureCache.has(tex)) return textureCache.get(tex);
let imageIndex = imageCache.get(tex.image);
if (imageIndex === undefined) {
const png = await imageToPNG(tex);
if (!png) { textureCache.set(tex, null); return null; }
images.push({ mimeType: 'image/png', bufferView: addBufferView(png) });
imageIndex = images.length - 1;
imageCache.set(tex.image, imageIndex);
log(`Texture ${tex.image.width}×${tex.image.height} → ${(png.byteLength / 1024).toFixed(0)} KB PNG`);
}
if ((tex.offset && (tex.offset.x || tex.offset.y)) ||
(tex.repeat && (tex.repeat.x !== 1 || tex.repeat.y !== 1)) || tex.rotation) {
warn(`Texture "${tex.name}" uses offset/repeat/rotation, which is not exported.`);
}
samplers.push({
magFilter: tex.magFilter === THREE_CONST.NearestFilter ? 9728 : 9729,
wrapS: WRAP_TO_GL[tex.wrapS] ?? 10497,
wrapT: WRAP_TO_GL[tex.wrapT] ?? 10497,
});
textures.push({ source: imageIndex, sampler: samplers.length - 1 });
const index = textures.length - 1;
textureCache.set(tex, index);
return index;
}
// ── 6. Materials ────────────────────────────────────────────────────────
async function addMaterial(mat) {
if (!mat) return undefined;
if (materialCache.has(mat)) return materialCache.get(mat);
const pbr = {
baseColorFactor: mat.color ? [mat.color.r, mat.color.g, mat.color.b, mat.opacity ?? 1] : [1, 1, 1, mat.opacity ?? 1],
metallicFactor: mat.metalness ?? 0,
roughnessFactor: mat.roughness ?? 1,
};
const out = {
name: mat.name || `material_${materials.length}`,
pbrMetallicRoughness: pbr,
doubleSided: mat.side === THREE_CONST.DoubleSide,
};
const baseColor = await addTexture(mat.map);
if (baseColor !== null) pbr.baseColorTexture = { index: baseColor };
// Three reads roughness from G and metalness from B — same as glTF.
const mr = await addTexture(mat.metalnessMap || mat.roughnessMap);
if (mr !== null) pbr.metallicRoughnessTexture = { index: mr };
const normal = await addTexture(mat.normalMap);
if (normal !== null) out.normalTexture = { index: normal, scale: mat.normalScale?.x ?? 1 };
if (mat.aoMap && !mat.aoMap.channel) {
const ao = await addTexture(mat.aoMap);
if (ao !== null) out.occlusionTexture = { index: ao, strength: mat.aoMapIntensity ?? 1 };
}
if (mat.emissive) {
const k = mat.emissiveIntensity ?? 1;
const e = [mat.emissive.r * k, mat.emissive.g * k, mat.emissive.b * k].map(v => Math.min(1, v));
if (e.some(v => v > 0)) out.emissiveFactor = e;
}
const emissive = await addTexture(mat.emissiveMap);
if (emissive !== null) {
out.emissiveTexture = { index: emissive };
out.emissiveFactor ??= [1, 1, 1];
}
if (mat.alphaTest > 0) {
out.alphaMode = 'MASK';
out.alphaCutoff = mat.alphaTest;
} else if (mat.transparent && (mat.opacity < 1 || mat.alphaMap || mat.map)) {
out.alphaMode = 'BLEND';
}
materials.push(out);
const index = materials.length - 1;
materialCache.set(mat, index);
return index;
}
// ── 7. Meshes → primitives ──────────────────────────────────────────────
for (const mesh of meshes) {
const geo = mesh.geometry;
const posAttr = geo.attributes.position;
const vCount = posAttr.count;
const matList = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
const attributes = {};
const positions = readAttribute(posAttr, 3);
attributes.POSITION = addAccessor(positions, GL.FLOAT, 'VEC3', vCount, GL.ARRAY_BUFFER, computeMinMax(positions, 3));
if (OPTIONS.includeNormals && geo.attributes.normal) {
const normals = readAttribute(geo.attributes.normal, 3);
for (let i = 0; i < normals.length; i += 3) {
const len = Math.hypot(normals[i], normals[i + 1], normals[i + 2]) || 1;
normals[i] /= len; normals[i + 1] /= len; normals[i + 2] /= len;
}
attributes.NORMAL = addAccessor(normals, GL.FLOAT, 'VEC3', vCount, GL.ARRAY_BUFFER);
}
if (geo.attributes.uv) {
const uvs = readAttribute(geo.attributes.uv, 2);
// glTF UV origin is the image's top-left. Three only flips non-ImageBitmap
// sources when flipY is set, so only those need their V flipped back.
const map = matList.find(m => m?.map)?.map;
const needsFlip = map && map.flipY && !(typeof ImageBitmap !== 'undefined' && map.image instanceof ImageBitmap);
if (needsFlip) for (let i = 1; i < uvs.length; i += 2) uvs[i] = 1 - uvs[i];
attributes.TEXCOORD_0 = addAccessor(uvs, GL.FLOAT, 'VEC2', vCount, GL.ARRAY_BUFFER);
}
if (geo.attributes.color && matList.some(m => m?.vertexColors)) {
const itemSize = geo.attributes.color.itemSize === 4 ? 4 : 3;
const colors = readAttribute(geo.attributes.color, itemSize);
attributes.COLOR_0 = addAccessor(colors, GL.FLOAT, itemSize === 4 ? 'VEC4' : 'VEC3', vCount, GL.ARRAY_BUFFER);
}
const index = geo.index;
const totalCount = index ? index.count : vCount;
const drawStart = geo.drawRange?.start ?? 0;
const drawCount = Math.min(geo.drawRange?.count ?? Infinity, totalCount - drawStart);
const groups = geo.groups?.length
? geo.groups
: [{ start: drawStart, count: drawCount, materialIndex: 0 }];
const IndexArray = vCount > 65535 ? Uint32Array : Uint16Array;
const indexCompType = vCount > 65535 ? GL.UNSIGNED_INT : GL.UNSIGNED_SHORT;
const primitives = [];
for (const group of groups) {
const start = group.start;
const count = Math.min(group.count, totalCount - start);
if (count <= 0) continue;
const prim = { attributes, mode: GL.TRIANGLES };
const coversAll = start === 0 && count === totalCount;
if (index) {
const idx = new IndexArray(count);
idx.set(index.array.subarray(start, start + count));
prim.indices = addAccessor(idx, indexCompType, 'SCALAR', count, GL.ELEMENT_ARRAY_BUFFER);
} else if (!coversAll) {
const idx = new IndexArray(count);
for (let i = 0; i < count; i++) idx[i] = start + i;
prim.indices = addAccessor(idx, indexCompType, 'SCALAR', count, GL.ELEMENT_ARRAY_BUFFER);
}
const material = await addMaterial(matList[group.materialIndex ?? 0] ?? matList[0]);
if (material !== undefined) prim.material = material;
primitives.push(prim);
}
gltfMeshes.push({ name: mesh.name || `mesh_${gltfMeshes.length}`, primitives });
const node = { name: mesh.name || `node_${nodes.length}`, mesh: gltfMeshes.length - 1 };
const m = mesh.matrixWorld.elements;
const isIdentity = m.every((v, i) => v === (i % 5 === 0 ? 1 : 0));
if (!isIdentity) node.matrix = Array.from(m);
nodes.push(node);
}
// ── 8. Build glTF JSON ──────────────────────────────────────────────────
const gltf = {
asset: { version: '2.0', generator: 'tripo3d-browser-extractor' },
scene: 0,
scenes: [{ name: 'Scene', nodes: nodes.map((_, i) => i) }],
nodes,
meshes: gltfMeshes,
accessors,
bufferViews,
buffers: [{ byteLength: binLength }],
};
if (materials.length) gltf.materials = materials;
if (textures.length) Object.assign(gltf, { textures, samplers, images });
// ── 9. Assemble GLB binary ──────────────────────────────────────────────
const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
const jsonPadded = align4(jsonBytes.length);
const totalSize = 12 + 8 + jsonPadded + 8 + binLength;
const glb = new ArrayBuffer(totalSize);
const dv = new DataView(glb);
const buf = new Uint8Array(glb);
let off = 0;
dv.setUint32(off, 0x46546C67, true); off += 4; // "glTF"
dv.setUint32(off, 2, true); off += 4;
dv.setUint32(off, totalSize, true); off += 4;
dv.setUint32(off, jsonPadded, true); off += 4;
dv.setUint32(off, 0x4E4F534A, true); off += 4; // "JSON"
buf.set(jsonBytes, off);
buf.fill(0x20, off + jsonBytes.length, off + jsonPadded); // JSON must be space-padded
off += jsonPadded;
dv.setUint32(off, binLength, true); off += 4;
dv.setUint32(off, 0x004E4942, true); off += 4; // "BIN\0"
for (const { byteOffset, bytes } of binParts) buf.set(bytes, off + byteOffset);
// ── 10. Download ────────────────────────────────────────────────────────
const fileMB = (totalSize / 1024 / 1024).toFixed(2);
const modelId = (window.location.pathname.split('/').filter(Boolean).pop() || 'model').replace(/[^\w.-]+/g, '_');
const filename = `tripo_${modelId}.glb`;
const blobUrl = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));
const anchor = document.createElement('a');
anchor.href = blobUrl;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 10_000);
const totalVerts = meshes.reduce((s, m) => s + vertexCountOf(m), 0);
log(`✓ Download triggered: ${filename} (${fileMB} MB, ${meshes.length} mesh(es), ${totalVerts} vertices, ${textures.length} texture(s))`);
return { filename, fileMB, meshes: meshes.length, vertices: totalVerts, textures: textures.length };
} catch (err) {
console.error(TAG, err);
throw err;
}
})();
/**
- Tripo Studio local GLB exporter - all in one
- Paste into DevTools Console while your model is visible.
- Finds an accessible Three.js scene and exports meshes/textures already
- loaded by the browser. It cannot unlock assets absent from the viewer.
- No third-party imports or network requests.
*/
(async () => {
it's working for me. thank alot.
could somebody help me plz, I confused, could you guys paste me the full script
You can follow the extension instructions above.
could somebody help me plz, I confused, could you guys paste me the full script
(async function extractTripoGLB() {
const OPTIONS = {
// Tripo's generated normals are often inconsistent; leaving them out makes
// Blender & co. recompute smooth normals from the face winding.
includeNormals: false,
// false = only export the single mesh with the most vertices.
exportAllMeshes: true,
// Meshes with fewer vertices than this are treated as helpers and skipped
// when no "tripo_node_*" meshes are found.
minHelperVertexCount: 64,
};
const TAG = '[tripo-extract]';
const log = (...a) => console.log(TAG, ...a);
const warn = (...a) => console.warn(TAG, ...a);
const GL = {
FLOAT: 5126, UNSIGNED_SHORT: 5123, UNSIGNED_INT: 5125,
ARRAY_BUFFER: 34962, ELEMENT_ARRAY_BUFFER: 34963,
TRIANGLES: 4,
};
const THREE_CONST = {
DoubleSide: 2,
RepeatWrapping: 1000, ClampToEdgeWrapping: 1001, MirroredRepeatWrapping: 1002,
NearestFilter: 1003, LinearFilter: 1006,
};
const WRAP_TO_GL = {
[THREE_CONST.RepeatWrapping]: 10497,
[THREE_CONST.ClampToEdgeWrapping]: 33071,
[THREE_CONST.MirroredRepeatWrapping]: 33648,
};
const align4 = n => (n + 3) & ~3;
const toRaw = v => (v && v.__v_raw) || v;
const unref = v => toRaw(v && v.__v_isRef ? v.value : v);
const bytesOf = t => new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
try {
// ── 1. Locate the Vue app ───────────────────────────────────────────────
const appEl = [document.querySelector('#__nuxt'), ...document.querySelectorAll('[data-v-app]')]
.find(el => el && (el.__vue_app__ || el.vue_app));
if (!appEl) throw new Error('Vue app not found. Are you on a Tripo Studio model page?');
const vueApp = appEl.__vue_app__ || appEl.vue_app;
// ── 2. Walk every component instance and find the TresJS context ────────
function* walkInstances(root) {
const seen = new Set();
const stack = [root];
while (stack.length) {
const node = stack.pop();
if (!node || typeof node !== 'object' || seen.has(node)) continue;
seen.add(node);
if (Array.isArray(node)) { stack.push(...node); continue; }
const isInstance = 'subTree' in node && 'vnode' in node && 'uid' in node;
if (isInstance) {
yield node;
stack.push(node.subTree);
if (node.suspense) stack.push(node.suspense.activeBranch);
continue;
}
// vnode
if (node.component) stack.push(node.component);
if (node.suspense) stack.push(node.suspense.activeBranch);
if (Array.isArray(node.children)) stack.push(node.children);
if (Array.isArray(node.dynamicChildren)) stack.push(node.dynamicChildren);
}
}
function sceneFromInstance(inst) {
const candidates = [
inst.provides?.useTres,
inst.exposed?.context,
inst.setupState?.context,
];
for (const c of candidates) {
const ctx = unref(c);
const scene = unref(ctx?.scene);
if (scene?.isScene) return scene;
}
return null;
}
const rootInstance = vueApp._instance
|| vueApp.config?.globalProperties?.$router?.currentRoute?.value?.matched?.[0]?.instances?.default?._;
if (!rootInstance) throw new Error('Root Vue component instance not found.');
// Breadth-first search of an arbitrary object graph for a THREE.Scene (or
// any Object3D whose root is a Scene). Used when the scene lives outside
// the DOM component tree, e.g. in TresJS's separate custom-renderer tree.
function findSceneDeep(roots, budget = 400_000) {
const seen = new Set();
const queue = roots.slice();
for (let qi = 0; qi < queue.length && seen.size < budget && queue.length < 4_000_000; qi++) {
try {
const v = unref(queue[qi]);
if (!v || typeof v !== 'object' || seen.has(v)) continue;
seen.add(v);
if (v.isScene) return v;
if (v.isObject3D) {
let o = v;
while (o.parent) o = o.parent;
if (o.isScene) return o;
continue;
}
if (v === window || v instanceof Window || ArrayBuffer.isView(v) || v instanceof ArrayBuffer) continue;
if (v instanceof Node) {
queue.push(v.__vueParentComponent, v.__vnode, v._vnode);
continue;
}
if (v instanceof Map) { for (const [k, x] of v) queue.push(k, x); continue; }
if (v instanceof Set) { for (const x of v) queue.push(x); continue; }
for (const k of Object.keys(v)) queue.push(v[k]);
} catch { /* cross-origin or throwing getter */ }
}
return null;
}
function userGlobals() {
try {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
const builtins = new Set(Object.getOwnPropertyNames(iframe.contentWindow));
iframe.remove();
return Object.getOwnPropertyNames(window)
.filter(k => !builtins.has(k))
.map(k => { try { return window[k]; } catch { return null; } });
} catch { return []; }
}
const instances = [...walkInstances(rootInstance)];
let scene = null;
// Strategy 1: a component that provides/exposes the TresJS context.
for (const inst of instances) {
scene = sceneFromInstance(inst);
if (scene) break;
}
// Strategy 2: deep search through Vue state, Pinia stores, canvases and globals.
if (!scene) {
const pinia = vueApp.config?.globalProperties?.$pinia;
scene = findSceneDeep([
...(window.__tripoScenes ?? []).slice().reverse(),
...instances.flatMap(i => [i.exposed, i.provides, i.setupState, i.refs, i.props]),
pinia?._s, pinia?.state,
vueApp.config?.globalProperties,
...document.querySelectorAll('canvas'),
rootInstance,
...userGlobals(),
]);
}
if (!scene) {
// Three.js announces every new Scene to window.__THREE_DEVTOOLS__ on
// construction, so a hook installed now catches the next scene built.
if (!window.__tripoScenes) {
window.__tripoScenes = [];
const devtools = window.__THREE_DEVTOOLS__ || (window.__THREE_DEVTOOLS__ = new EventTarget());
devtools.addEventListener('observe', e => { if (e.detail?.isScene) window.__tripoScenes.push(e.detail); });
}
const names = [...new Set(instances.map(i => i.type?.name || i.type?.__name).filter(Boolean))];
console.group(`${TAG} diagnostics`);
log('THREE version (window.__THREE__):', window.__THREE__ ?? 'not set');
log('Canvases:', document.querySelectorAll('canvas').length,
'| iframes:', [...document.querySelectorAll('iframe')].map(f => f.src || '(no src)'));
log('Vue components walked:', instances.length);
log('3D-looking components:', names.filter(n => /tres|canvas|context|scene|viewer|model|three/i.test(n)));
log('Pinia stores:', [...(vueApp.config?.globalProperties?.$pinia?._s?.keys() ?? [])]);
console.groupEnd();
throw new Error(
'THREE.Scene not found. A capture hook is now installed: open a different model in the app ' +
'(click it, do NOT reload the page), come back to this one, then run the script again.');
}
log('Scene found — children:', scene.children.length);
// ── 3. Collect model meshes ─────────────────────────────────────────────
scene.updateMatrixWorld(true);
const visibleMeshes = [];
scene.traverseVisible(o => {
if (o.isMesh && o.geometry?.attributes?.position) visibleMeshes.push(o);
});
if (!visibleMeshes.length) throw new Error('No visible meshes in scene.');
const vertexCountOf = m => m.geometry.attributes.position.count;
const isTripoNode = m => {
for (let o = m; o; o = o.parent) if (/^tripo_node/.test(o.name)) return true;
return false;
};
let meshes = visibleMeshes.filter(isTripoNode);
if (!meshes.length) {
meshes = visibleMeshes.filter(m => vertexCountOf(m) >= OPTIONS.minHelperVertexCount);
if (!meshes.length) meshes = visibleMeshes;
}
if (!OPTIONS.exportAllMeshes || !meshes.length) {
meshes = [meshes.concat(visibleMeshes).reduce((a, b) => (vertexCountOf(b) > vertexCountOf(a) ? b : a))];
}
for (const m of meshes) {
if (m.isInstancedMesh) warn(`"${m.name}" is instanced — only the base geometry is exported.`);
if (m.isSkinnedMesh) warn(`"${m.name}" is skinned — exported in bind pose without skeleton.`);
log(`Mesh "${m.name || '(unnamed)'}" — ${vertexCountOf(m)} vertices, ${m.geometry.index?.count ?? 0} indices`);
}
// ── 4. glTF builder state ───────────────────────────────────────────────
const binParts = [];
let binLength = 0;
const bufferViews = [];
const accessors = [];
const images = [];
const samplers = [];
const textures = [];
const materials = [];
const gltfMeshes = [];
const nodes = [];
const imageCache = new Map();
const textureCache = new Map();
const materialCache = new Map();
function addBufferView(bytes, target) {
const byteOffset = binLength;
binParts.push({ byteOffset, bytes });
binLength = align4(byteOffset + bytes.byteLength);
bufferViews.push({ buffer: 0, byteOffset, byteLength: bytes.byteLength, ...(target ? { target } : {}) });
return bufferViews.length - 1;
}
function addAccessor(typed, componentType, type, count, target, extra = {}) {
const bufferView = addBufferView(bytesOf(typed), target);
accessors.push({ bufferView, byteOffset: 0, componentType, count, type, ...extra });
return accessors.length - 1;
}
// Reads any BufferAttribute / InterleavedBufferAttribute (incl. normalized
// integer attributes) into a tightly packed Float32Array.
function readAttribute(attr, itemSize = attr.itemSize) {
const getters = ['getX', 'getY', 'getZ', 'getW'];
const out = new Float32Array(attr.count * itemSize);
for (let i = 0; i < attr.count; i++) {
for (let k = 0; k < itemSize; k++) out[i * itemSize + k] = attr[getters[k]](i);
}
return out;
}
function computeMinMax(data, itemSize) {
const min = new Array(itemSize).fill(Infinity);
const max = new Array(itemSize).fill(-Infinity);
for (let i = 0; i < data.length; i += itemSize) {
for (let k = 0; k < itemSize; k++) {
const v = data[i + k];
if (v < min[k]) min[k] = v;
if (v > max[k]) max[k] = v;
}
}
return { min, max };
}
// ── 5. Textures ─────────────────────────────────────────────────────────
async function imageToPNG(tex) {
const img = tex.image;
if (!img) return null;
if (tex.isCompressedTexture) {
warn(`Texture "${tex.name}" is GPU-compressed (KTX2/Basis) and can't be read back — skipped.`);
return null;
}
const w = img.width ?? img.naturalWidth ?? img.videoWidth;
const h = img.height ?? img.naturalHeight ?? img.videoHeight;
if (!w || !h) {
warn(`Texture "${tex.name}" has no readable pixels (closed ImageBitmap?) — skipped.`);
return null;
}
const canvas = document.createElement('canvas');
canvas.width = w; canvas.height = h;
const ctx2d = canvas.getContext('2d');
if (tex.isDataTexture) {
const data = img.data;
if (!(data instanceof Uint8Array || data instanceof Uint8ClampedArray) || data.length !== w * h * 4) {
warn(`DataTexture "${tex.name}" is not 8-bit RGBA — skipped.`);
return null;
}
ctx2d.putImageData(new ImageData(new Uint8ClampedArray(data), w, h), 0, 0);
} else {
ctx2d.drawImage(img, 0, 0, w, h);
}
try {
const blob = await new Promise((resolve, reject) =>
canvas.toBlob(b => (b ? resolve(b) : reject(new Error('toBlob returned null'))), 'image/png'));
return new Uint8Array(await blob.arrayBuffer());
} catch (e) {
warn(`Could not encode texture "${tex.name}" (cross-origin canvas taint?) — skipped.`, e);
return null;
}
}
async function addTexture(tex) {
if (!tex) return null;
if (textureCache.has(tex)) return textureCache.get(tex);
let imageIndex = imageCache.get(tex.image);
if (imageIndex === undefined) {
const png = await imageToPNG(tex);
if (!png) { textureCache.set(tex, null); return null; }
images.push({ mimeType: 'image/png', bufferView: addBufferView(png) });
imageIndex = images.length - 1;
imageCache.set(tex.image, imageIndex);
log(`Texture ${tex.image.width}×${tex.image.height} → ${(png.byteLength / 1024).toFixed(0)} KB PNG`);
}
if ((tex.offset && (tex.offset.x || tex.offset.y)) ||
(tex.repeat && (tex.repeat.x !== 1 || tex.repeat.y !== 1)) || tex.rotation) {
warn(`Texture "${tex.name}" uses offset/repeat/rotation, which is not exported.`);
}
samplers.push({
magFilter: tex.magFilter === THREE_CONST.NearestFilter ? 9728 : 9729,
wrapS: WRAP_TO_GL[tex.wrapS] ?? 10497,
wrapT: WRAP_TO_GL[tex.wrapT] ?? 10497,
});
textures.push({ source: imageIndex, sampler: samplers.length - 1 });
const index = textures.length - 1;
textureCache.set(tex, index);
return index;
}
// ── 6. Materials ────────────────────────────────────────────────────────
async function addMaterial(mat) {
if (!mat) return undefined;
if (materialCache.has(mat)) return materialCache.get(mat);
const pbr = {
baseColorFactor: mat.color ? [mat.color.r, mat.color.g, mat.color.b, mat.opacity ?? 1] : [1, 1, 1, mat.opacity ?? 1],
metallicFactor: mat.metalness ?? 0,
roughnessFactor: mat.roughness ?? 1,
};
const out = {
name: mat.name || `material_${materials.length}`,
pbrMetallicRoughness: pbr,
doubleSided: mat.side === THREE_CONST.DoubleSide,
};
const baseColor = await addTexture(mat.map);
if (baseColor !== null) pbr.baseColorTexture = { index: baseColor };
// Three reads roughness from G and metalness from B — same as glTF.
const mr = await addTexture(mat.metalnessMap || mat.roughnessMap);
if (mr !== null) pbr.metallicRoughnessTexture = { index: mr };
const normal = await addTexture(mat.normalMap);
if (normal !== null) out.normalTexture = { index: normal, scale: mat.normalScale?.x ?? 1 };
if (mat.aoMap && !mat.aoMap.channel) {
const ao = await addTexture(mat.aoMap);
if (ao !== null) out.occlusionTexture = { index: ao, strength: mat.aoMapIntensity ?? 1 };
}
if (mat.emissive) {
const k = mat.emissiveIntensity ?? 1;
const e = [mat.emissive.r * k, mat.emissive.g * k, mat.emissive.b * k].map(v => Math.min(1, v));
if (e.some(v => v > 0)) out.emissiveFactor = e;
}
const emissive = await addTexture(mat.emissiveMap);
if (emissive !== null) {
out.emissiveTexture = { index: emissive };
out.emissiveFactor ??= [1, 1, 1];
}
if (mat.alphaTest > 0) {
out.alphaMode = 'MASK';
out.alphaCutoff = mat.alphaTest;
} else if (mat.transparent && (mat.opacity < 1 || mat.alphaMap || mat.map)) {
out.alphaMode = 'BLEND';
}
materials.push(out);
const index = materials.length - 1;
materialCache.set(mat, index);
return index;
}
// ── 7. Meshes → primitives ──────────────────────────────────────────────
for (const mesh of meshes) {
const geo = mesh.geometry;
const posAttr = geo.attributes.position;
const vCount = posAttr.count;
const matList = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
const attributes = {};
const positions = readAttribute(posAttr, 3);
attributes.POSITION = addAccessor(positions, GL.FLOAT, 'VEC3', vCount, GL.ARRAY_BUFFER, computeMinMax(positions, 3));
if (OPTIONS.includeNormals && geo.attributes.normal) {
const normals = readAttribute(geo.attributes.normal, 3);
for (let i = 0; i < normals.length; i += 3) {
const len = Math.hypot(normals[i], normals[i + 1], normals[i + 2]) || 1;
normals[i] /= len; normals[i + 1] /= len; normals[i + 2] /= len;
}
attributes.NORMAL = addAccessor(normals, GL.FLOAT, 'VEC3', vCount, GL.ARRAY_BUFFER);
}
if (geo.attributes.uv) {
const uvs = readAttribute(geo.attributes.uv, 2);
// glTF UV origin is the image's top-left. Three only flips non-ImageBitmap
// sources when flipY is set, so only those need their V flipped back.
const map = matList.find(m => m?.map)?.map;
const needsFlip = map && map.flipY && !(typeof ImageBitmap !== 'undefined' && map.image instanceof ImageBitmap);
if (needsFlip) for (let i = 1; i < uvs.length; i += 2) uvs[i] = 1 - uvs[i];
attributes.TEXCOORD_0 = addAccessor(uvs, GL.FLOAT, 'VEC2', vCount, GL.ARRAY_BUFFER);
}
if (geo.attributes.color && matList.some(m => m?.vertexColors)) {
const itemSize = geo.attributes.color.itemSize === 4 ? 4 : 3;
const colors = readAttribute(geo.attributes.color, itemSize);
attributes.COLOR_0 = addAccessor(colors, GL.FLOAT, itemSize === 4 ? 'VEC4' : 'VEC3', vCount, GL.ARRAY_BUFFER);
}
const index = geo.index;
const totalCount = index ? index.count : vCount;
const drawStart = geo.drawRange?.start ?? 0;
const drawCount = Math.min(geo.drawRange?.count ?? Infinity, totalCount - drawStart);
const groups = geo.groups?.length
? geo.groups
: [{ start: drawStart, count: drawCount, materialIndex: 0 }];
const IndexArray = vCount > 65535 ? Uint32Array : Uint16Array;
const indexCompType = vCount > 65535 ? GL.UNSIGNED_INT : GL.UNSIGNED_SHORT;
const primitives = [];
for (const group of groups) {
const start = group.start;
const count = Math.min(group.count, totalCount - start);
if (count <= 0) continue;
const prim = { attributes, mode: GL.TRIANGLES };
const coversAll = start === 0 && count === totalCount;
if (index) {
const idx = new IndexArray(count);
idx.set(index.array.subarray(start, start + count));
prim.indices = addAccessor(idx, indexCompType, 'SCALAR', count, GL.ELEMENT_ARRAY_BUFFER);
} else if (!coversAll) {
const idx = new IndexArray(count);
for (let i = 0; i < count; i++) idx[i] = start + i;
prim.indices = addAccessor(idx, indexCompType, 'SCALAR', count, GL.ELEMENT_ARRAY_BUFFER);
}
const material = await addMaterial(matList[group.materialIndex ?? 0] ?? matList[0]);
if (material !== undefined) prim.material = material;
primitives.push(prim);
}
gltfMeshes.push({ name: mesh.name || `mesh_${gltfMeshes.length}`, primitives });
const node = { name: mesh.name || `node_${nodes.length}`, mesh: gltfMeshes.length - 1 };
const m = mesh.matrixWorld.elements;
const isIdentity = m.every((v, i) => v === (i % 5 === 0 ? 1 : 0));
if (!isIdentity) node.matrix = Array.from(m);
nodes.push(node);
}
// ── 8. Build glTF JSON ──────────────────────────────────────────────────
const gltf = {
asset: { version: '2.0', generator: 'tripo3d-browser-extractor' },
scene: 0,
scenes: [{ name: 'Scene', nodes: nodes.map((_, i) => i) }],
nodes,
meshes: gltfMeshes,
accessors,
bufferViews,
buffers: [{ byteLength: binLength }],
};
if (materials.length) gltf.materials = materials;
if (textures.length) Object.assign(gltf, { textures, samplers, images });
// ── 9. Assemble GLB binary ──────────────────────────────────────────────
const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
const jsonPadded = align4(jsonBytes.length);
const totalSize = 12 + 8 + jsonPadded + 8 + binLength;
const glb = new ArrayBuffer(totalSize);
const dv = new DataView(glb);
const buf = new Uint8Array(glb);
let off = 0;
dv.setUint32(off, 0x46546C67, true); off += 4; // "glTF"
dv.setUint32(off, 2, true); off += 4;
dv.setUint32(off, totalSize, true); off += 4;
dv.setUint32(off, jsonPadded, true); off += 4;
dv.setUint32(off, 0x4E4F534A, true); off += 4; // "JSON"
buf.set(jsonBytes, off);
buf.fill(0x20, off + jsonBytes.length, off + jsonPadded); // JSON must be space-padded
off += jsonPadded;
dv.setUint32(off, binLength, true); off += 4;
dv.setUint32(off, 0x004E4942, true); off += 4; // "BIN\0"
for (const { byteOffset, bytes } of binParts) buf.set(bytes, off + byteOffset);
// ── 10. Download ────────────────────────────────────────────────────────
const fileMB = (totalSize / 1024 / 1024).toFixed(2);
const modelId = (window.location.pathname.split('/').filter(Boolean).pop() || 'model').replace(/[^\w.-]+/g, '_');
const filename = `tripo_${modelId}.glb`;
const blobUrl = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));
const anchor = document.createElement('a');
anchor.href = blobUrl;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(blobUrl), 10_000);
const totalVerts = meshes.reduce((s, m) => s + vertexCountOf(m), 0);
log(`✓ Download triggered: ${filename} (${fileMB} MB, ${meshes.length} mesh(es), ${totalVerts} vertices, ${textures.length} texture(s))`);
return { filename, fileMB, meshes: meshes.length, vertices: totalVerts, textures: textures.length };
} catch (err) {
console.error(TAG, err);
throw err;
}
})();
- 1. Copy the script.
- 2. Open developer options in your browser (F12)
- 3. Open the page for the model.
- 4. Try to paste it into the console and it will tell you to enter "allow pasting" as a first response.
- 5. Paste the script and press enter. The download will start automatically.
thanks
is there a way to also extract the rigging?
is there a way to also extract the rigging?
yes
Holy moly this is still active 🤣

thank you so much it worked you are amazing, also, i see in the image you provided you are downloading a fbx file, is there a setting in tampermonkey to change it from downloading a glb to fbx?