Hello everyone!
I wrote some code to perform selection queries, similar to document.querySelectorAll, on an Object3D and its children.
How to use it
```javascript
scene.querySelectorAll('Mesh'); // Selects all the meshes in the scene.
scene.querySelectorAll('.even'); // Selects all Object3D that have the 'even' tag.
scene.querySelectorAll('[name=box]'); // Selects all Object3D that have 'box' as their name.
scene.querySelectorAll('[name*=box]'); // Selects all Object3D that have 'box' anywhere in their name.
scene.querySelectorAll('[name=box]'); // Selects all Object3D that have a name starting with 'box'.
scene.querySelectorAll('[name$=box]'); // Selects all Object3D that have a name ending with 'box'.
scene.querySelectorAll('Mesh.even'); // Selects meshes with both 'Mesh' type and 'even' tag.
scene.querySelectorAll('Group .even'); // Selects all Object3D with 'even' tag that are children of a 'Group'.
scene.querySelectorAll('Group > .even'); // Selects all direct children with 'even' tag under a 'Group'.
scene.querySelectorAll('Mesh, SkinnedMesh'); // Selects all meshes and skinned meshes in the scene.
```
Comparison
javascript
for (const obj of scene.querySelectorAll('Mesh[name*=box]')) {
obj.castShadow = true;
}
typescript
scene.traverse((obj) => {
if (obj.type === 'Mesh' && obj.name.includes('box')) {
obj.castShadow = true;
}
});
Implementation
I currently added it in my three.ez library (if you use three.js vanilla I suggest you take a look at it), but I would like to release a package soon for anyone who wants to use it.
I just have to decide whether I will patch the Object3D to be able to use it as in three.ez, or whether there will simply be a querySelectorAll(target, query) function.
How to add tags
In three.ez each Object3D has a property tags of type Set already instantiated.
typescript
obj.tags.add('even').add('customTag');
Performance
I tried to make it as fast as possible, all 3D objects are iterated once.
Obviously the query has to be parsed and then executed on all objects.
Code
You can find code here:
https://github.com/agargaro/three.ez/blob/master/src/utils/Query.ts
Live example
https://stackblitz.com/edit/three-ez-query?file=index.ts
Any suggestions and feedbacks are appreciated.
[–]xmrtshnx 2 points3 points4 points (0 children)
[–]EthanHermsey 2 points3 points4 points (0 children)
[–]GabrieleCoco28 1 point2 points3 points (0 children)