Skip to content

Commit 9b996a9

Browse files
committed
add support for generating slots from blender properties
1 parent d6c6f93 commit 9b996a9

File tree

1 file changed

+47
-12
lines changed

1 file changed

+47
-12
lines changed

src/utils/parser.js

+47-12
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,23 @@ function parse(gltf, { fileName = 'model', ...options } = {}) {
1313
const animations = gltf.animations
1414
const hasAnimations = animations.length > 0
1515

16+
/** @type {Record<string, Object3D[]> */
17+
const slots = {}
18+
1619
// Collect all objects
1720
const objects = []
18-
gltf.scene.traverse((child) => objects.push(child))
21+
gltf.scene.traverse((child) => {
22+
objects.push(child);
23+
24+
// Collect slots
25+
const slot = child.userData?.prop;
26+
const hasSlot = (slot && typeof slot === "string" && slot.length > 0);
27+
if (hasSlot)
28+
{
29+
const slotname = sanitizeSlotName(slot);
30+
slots[slotname] ? slots[slotname].push(child) : (slots[slotname] = [child]);
31+
}
32+
})
1933

2034
// Browse for duplicates
2135
const duplicates = {
@@ -75,6 +89,11 @@ function parse(gltf, { fileName = 'model', ...options } = {}) {
7589
return isVarName(name) ? `.${name}` : `['${name}']`
7690
}
7791

92+
/** Ensure that a slot is a valid variable name e.g. must not contain spaces */
93+
function sanitizeSlotName(slotname) {
94+
return slotname.replaceAll(/[^a-zA-Z0-9]/g, '');
95+
}
96+
7897
const rNbr = (number) => {
7998
return parseFloat(number.toFixed(Math.round(options.precision || 2)))
8099
}
@@ -220,17 +239,18 @@ function parse(gltf, { fileName = 'model', ...options } = {}) {
220239
duplicates.geometries[obj.geometry.uuid + obj.material.name] &&
221240
duplicates.geometries[obj.geometry.uuid + obj.material.name].count > (options.instanceall ? 0 : 1)
222241
let animated = gltf.animations && gltf.animations.length > 0
223-
return { type, node, instanced, animated }
242+
const hasSlots = obj.userData?.prop && typeof obj.userData.prop === "string" && obj.userData.prop.length > 0;
243+
return { type, node, instanced, animated, hasSlots }
224244
}
225245

226246
function equalOrNegated(a, b) {
227247
return (a.x === b.x || a.x === -b.x) && (a.y === b.y || a.y === -b.y) && (a.z === b.z || a.z === -b.z)
228248
}
229249

230250
function prune(obj, children, result, oldResult, silent) {
231-
let { type, animated } = getInfo(obj)
251+
let { type, animated, hasSlots } = getInfo(obj)
232252
// Prune ...
233-
if (!obj.__removed && !options.keepgroups && !animated && (type === 'group' || type === 'scene')) {
253+
if (!obj.__removed && !options.keepgroups && !animated && !hasSlots && (type === 'group' || type === 'scene')) {
234254
/** Empty or no-property groups
235255
* <group>
236256
* <mesh geometry={nodes.foo} material={materials.bar} />
@@ -371,13 +391,24 @@ function parse(gltf, { fileName = 'model', ...options } = {}) {
371391
// Bail out if the object was pruned
372392
if (pruned !== undefined) return pruned
373393

374-
// Close tag
375-
result += `${children.length ? '>' : '/>'}\n`
394+
// Add custom slots if defined in the object's userData
395+
// E.g. userData: { "prop" : "mySlot" } becomes `{ mySlot }`
396+
const slot = obj.userData?.prop;
397+
const hasSlot = (slot && typeof slot === "string" && slot.length > 0);
398+
const hasContent = children.length || hasSlot;
376399

377-
// Add children and return
378-
if (children.length) {
379-
if (type === 'bone') result += children + `</primitive>`
380-
else result += children + `</${type}>`
400+
401+
// Close tag if no children
402+
result += `${hasContent ? '>' : '/>'}\n`
403+
404+
// Add children
405+
if (children.length) result += `${children.trimEnd("\n")}\n`
406+
// Add custom slot
407+
if (hasSlot) result += `{${sanitizeSlotName(slot)}}\n`;
408+
// Close tag
409+
if (hasContent) {
410+
if (type === 'bone') result += `</primitive>`
411+
else result += `</${type}>`
381412
}
382413
return result
383414
}
@@ -441,10 +472,14 @@ function parse(gltf, { fileName = 'model', ...options } = {}) {
441472
} catch (e) {
442473
console.log('Error while parsing glTF', e)
443474
}
475+
476+
const slotParams = Object.keys(slots).length > 0 ? (Object.keys(slots).join(", ") + ", ") : "";
477+
444478
const header = `/*
445479
${options.header ? options.header : 'Auto-generated by: https://github.com/pmndrs/gltfjsx'} ${
446480
options.size ? `\nFiles: ${options.size}` : ''
447481
}
482+
448483
${parseExtras(gltf.parser.json.asset && gltf.parser.json.asset.extras)}*/`
449484
const result = `${options.types ? `\nimport * as THREE from 'three'` : ''}
450485
import React, { useRef ${hasInstances ? ', useMemo, useContext, createContext' : ''} } from 'react'
@@ -460,7 +495,7 @@ ${parseExtras(gltf.parser.json.asset && gltf.parser.json.asset.extras)}*/`
460495
hasInstances
461496
? `
462497
const context = createContext(${options.types ? '{} as ContextType' : ''})
463-
export function Instances({ children, ...props }${options.types ? ': JSX.IntrinsicElements["group"]' : ''}) {
498+
export function Instances({ children, ${slotParams}...props }${options.types ? ': JSX.IntrinsicElements["group"]' : ''}) {
464499
const { nodes } = useGLTF('${url}'${options.draco ? `, ${JSON.stringify(options.draco)}` : ''})${
465500
options.types ? ' as GLTFResult' : ''
466501
}
@@ -481,7 +516,7 @@ ${parseExtras(gltf.parser.json.asset && gltf.parser.json.asset.extras)}*/`
481516
: ''
482517
}
483518
484-
export ${options.exportdefault ? 'default' : ''} function Model(props${
519+
export ${options.exportdefault ? 'default' : ''} function Model({ ${slotParams}...props }${
485520
options.types ? ": JSX.IntrinsicElements['group']" : ''
486521
}) {
487522
${hasInstances ? 'const instances = useContext(context);' : ''} ${

0 commit comments

Comments
 (0)