-
{{ _("Select Object") }}
-
-
{% with repository_list = object_list, element_type = 'object', htmx="false" %}
{% include "core/components/item-list.jinja2" %}
@@ -357,15 +346,15 @@
function update_selected_items(){
id_marker = "#marker-" + selected_marker;
$('#existent-marker > input').val(selected_marker);
- $(id_marker).css("border-bottom","3px solid #a6a6a6");
+ $(id_marker).css("border-bottom","3px solid #05f7ae");
id_object = "#object-" + selected_object;
$('#existent-object > input').val(selected_object);
- $(id_object).css("border-bottom","3px solid #a6a6a6");
+ $(id_object).css("border-bottom","3px solid #05f7ae");
id_sound = "#sound-" + selected_sound;
$('#existent-sound > input').val(selected_sound);
- $(id_sound).css("border-bottom","3px solid #a6a6a6");
+ $(id_sound).css("border-bottom","3px solid #05f7ae");
}
update_selected_items();
@@ -376,7 +365,7 @@
// reset background
$(this).parent().children().css('border-bottom', 'none')
- $(this).css("border-bottom","3px solid #a6a6a6");
+ $(this).css("border-bottom","3px solid #05f7ae");
id = elementId.split("-")[1];
if(sectionId == 'repo-marker'){
$('#id_selected_marker').val(id);
diff --git a/src/core/jinja2/core/upload-object.jinja2 b/src/core/jinja2/core/upload-object.jinja2
index bc87dfc06..969001cd5 100644
--- a/src/core/jinja2/core/upload-object.jinja2
+++ b/src/core/jinja2/core/upload-object.jinja2
@@ -8,8 +8,6 @@
- {# The last version of threejs that this works, after 0.127.0 we have an error. After 150+ three.min.js is deprecated for usage as a module #}
-
{% if edit %}
{{ _("Edit object") }}
{% else %}
@@ -144,7 +142,7 @@
id_sound = "#sound-" + selected_sound;
$('#existent-sound > input').val(selected_sound);
- $(id_sound).css("border-bottom","3px solid #a6a6a6");
+ $(id_sound).css("border-bottom","3px solid #05f7ae");
}
update_selected_items();
@@ -155,7 +153,7 @@
// reset background
$(this).parent().children().css('border-bottom', 'none')
- $(this).css("border-bottom","3px solid #a6a6a6");
+ $(this).css("border-bottom","3px solid #05f7ae");
id = elementId.split("-")[1];
$('#id_selected_sound').val(id);
selected_sound = id;
@@ -290,119 +288,32 @@
controlsInfo.style.cssText = "margin: 10px 0; padding: 10px; background: #e8f4fd; border-radius: 5px; font-size: 14px;";
controlsInfo.innerHTML = "
3D Controls: Left click + drag to rotate, Right click + drag to pan, Scroll to zoom";
document.getElementById("content-box").appendChild(controlsInfo);
-
- // THREE.js is already loaded globally, just import GLTFLoader and OrbitControls
- Promise.all([
- import('https://unpkg.com/three@0.127.0/examples/jsm/loaders/GLTFLoader.js'),
- import('https://unpkg.com/three@0.127.0/examples/jsm/controls/OrbitControls.js')
- ]).then(([{ GLTFLoader }, { OrbitControls }]) => {
- const scene = new THREE.Scene();
- scene.background = new THREE.Color(0xf0f0f0); // Light gray background
-
- const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
- camera.position.set(0, 0, 5);
-
- const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
- renderer.setSize(600, 600);
- renderer.shadowMap.enabled = false;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
- document.getElementById("content-box").appendChild(renderer.domElement);
- document.getElementById("content-box").appendChild(blockquote);
-
- // Add OrbitControls for camera interaction
- const controls = new OrbitControls(camera, renderer.domElement);
- controls.enableDamping = true; // Smooth camera movement
- controls.dampingFactor = 0.05;
- controls.enableZoom = true;
- controls.enablePan = true;
- controls.enableRotate = true;
- controls.autoRotate = false;
-
- // Add lighting
- const ambientLight = new THREE.AmbientLight(0xFFFDD0, 3.5); // Brighter ambient light
- scene.add(ambientLight);
-
-
- // Animation variables
- let mixer = null;
- const clock = new THREE.Clock();
-
- // Animation loop for smooth controls and animations
- function animate() {
- requestAnimationFrame(animate);
-
- const delta = clock.getDelta();
- if (mixer) mixer.update(delta);
-
- controls.update(); // Update controls for damping
- renderer.render(scene, camera);
+
+ // Create container for 3D viewer
+ var viewerContainer = document.createElement("div");
+ viewerContainer.style.cssText = "width: 600px; height: 600px; max-width: 100%; margin: 0 auto;";
+ document.getElementById("content-box").appendChild(viewerContainer);
+ document.getElementById("content-box").appendChild(blockquote);
+
+ (window.GLBViewer
+ ? Promise.resolve(window.GLBViewer)
+ : import("{{ static('js/glb-viewer.js') }}").then(function(m) { window.GLBViewer = m.GLBViewer; return m.GLBViewer; })
+ ).then(function(GLBViewer) {
+ GLBViewer.init(viewerContainer, URL.createObjectURL(file), {
+ onAnimationsFound: function(count) {
+ const animationInfo = document.createElement("div");
+ animationInfo.style.cssText = "margin: 10px 0; padding: 10px; background: #d4edda; border-radius: 5px; font-size: 14px;";
+ animationInfo.innerHTML = `
Animations: ${count} animation(s) found and playing`;
+ document.getElementById("content-box").appendChild(animationInfo);
+ },
+ onThumbnailReady: function(renderer, scene, camera) {
+ generateThumbnail(renderer, scene, camera);
+ },
+ onError: function(error) {
+ console.error('Error loading GLB file:', error);
}
-
- // Load the GLB file
- const loader = new GLTFLoader();
- loader.load(
- URL.createObjectURL(file),
- function (gltf) {
- scene.add(gltf.scene);
-
- // Handle animations if they exist
- if (gltf.animations && gltf.animations.length > 0) {
- mixer = new THREE.AnimationMixer(gltf.scene);
-
- // Play all animations
- gltf.animations.forEach((clip) => {
- const action = mixer.clipAction(clip);
- action.play();
- });
-
- // Add animation info
- const animationInfo = document.createElement("div");
- animationInfo.style.cssText = "margin: 10px 0; padding: 10px; background: #d4edda; border-radius: 5px; font-size: 14px;";
- animationInfo.innerHTML = `
Animations: ${gltf.animations.length} animation(s) found and playing`;
- document.getElementById("content-box").appendChild(animationInfo);
- }
-
- // Auto-scale and center the model
- const box = new THREE.Box3().setFromObject(gltf.scene);
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3());
-
- // Center the model
- gltf.scene.position.sub(center);
-
- // Scale to fit in view (make it bigger)
- const maxDim = Math.max(size.x, size.y, size.z);
- const scale = 5 / maxDim; // Make it take up more of the view
- gltf.scene.scale.setScalar(scale);
-
- // Position camera at optimal distance
- const distance = Math.max(3, maxDim * 2);
- camera.position.set(distance, distance * 0.5, distance);
- camera.lookAt(0, 0, 0);
-
- // Update controls target to model center
- controls.target.set(0, 0, 0);
- controls.update();
-
- // Start animation loop
- animate();
-
- // Auto-generate thumbnail after model is loaded and positioned
- setTimeout(() => {
- generateThumbnail(renderer, scene, camera);
- }, 1000); // Wait 1 second for the model to be properly positioned
- },
- function (progress) {
- console.log('Loading progress:', progress);
- },
- function (error) {
- console.error('Error loading GLB file:', error);
- }
- );
- })
- .catch(error => {
- console.error('Error loading GLTFLoader or OrbitControls:', error);
});
+ });
} else {
console.log("Invalid file type: " + file.type);
alert("{{ _("Invalid file type! Only image, video or GLB files are accepted.") }}")
diff --git a/src/core/models.py b/src/core/models.py
index 309f2a7f1..cf490c6ef 100644
--- a/src/core/models.py
+++ b/src/core/models.py
@@ -8,7 +8,7 @@
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django_extensions.db.models import TimeStampedModel
-from fast_html import a, audio, b, div, h1, img, p, render, span, video
+from fast_html import a, audio, img, render, video
from core.marker_utils import delete_marker_files
from users.models import Profile
@@ -33,26 +33,6 @@ class ContentMixin:
def content_type(self):
return self.__class__.__name__.lower()
- def _get_edit_button(self):
- content_type = self.content_type()
- return a(
- _("edit"),
- href=reverse(f"edit-{content_type}", query={"id": self.id}),
- class_="edit",
- )
-
- def _get_delete_button(self):
- content_type = self.content_type()
- return a(
- _("delete"),
- href=reverse(
- "delete-content",
- query={"content_type": content_type, "id": self.id},
- ),
- onclick=f"return confirm('{_('Are you sure you want to delete?')}')",
- class_="delete",
- )
-
def used_in_html_string(self):
used_in = "{} {} {} {} {} {}".format(
USED_IN,
@@ -170,19 +150,6 @@ def as_html(self):
)
)
- def as_html_thumbnail(self, editable=False):
- elements = [
- span(self.title, style="display:block;"),
- self.as_html(),
- ]
- if editable and not self.is_used_by_other_user():
- elements.append(self._get_edit_button())
-
- if editable and not self.in_use:
- elements.append(self._get_delete_button())
-
- return render(div(elements, style="margin: 10px auto;"))
-
class ExhibitTypes(models.TextChoices):
AR = "AR", "Augmented Reality"
@@ -249,29 +216,6 @@ def as_html(
)
)
- def as_html_thumbnail(self, editable: bool = False):
- height = DEFAULT_MARKER_THUMBNAIL_HEIGHT
- width = DEFAULT_MARKER_THUMBNAIL_WIDTH
- to_render = [self.as_html(height=height, width=width, thumbnail=True)]
- if editable:
- lower_menu_items = []
- if not self.in_use:
- lower_menu_items.append(self._get_delete_button())
-
- if not self.is_used_by_other_user():
- lower_menu_items.append(self._get_edit_button())
-
- lower_menu_items.append(
- a(
- _("preview"),
- href=reverse("marker-preview", query={"id": self.id}),
- class_="preview",
- )
- )
- lower_menu = div(lower_menu_items, class_="marker-menu")
- to_render.append(lower_menu)
- return render(to_render)
-
class ObjectExtensions(models.TextChoices):
GIF = "gif", "GIF"
@@ -529,18 +473,6 @@ def as_html(self, height: int = None, width: int = None):
else:
return render(img(**attributes))
- def as_html_thumbnail(self, editable=False):
- height = DEFAULT_OBJECT_THUMBNAIL_HEIGHT
- width = DEFAULT_OBJECT_THUMBNAIL_WIDTH
- to_render = [self.as_html(height, width)]
- if editable and not self.is_used_by_other_user():
- to_render.append(self._get_edit_button())
-
- if editable and not self.in_use:
- to_render.append(self._get_delete_button())
-
- return render(to_render)
-
@pghistory.track()
class Artwork(TimeStampedModel, ContentMixin):
@@ -599,31 +531,6 @@ def used_in_html_string(self):
)
return used_in
- def as_html_thumbnail(self, editable=False):
- elements = [
- self.marker.as_html_thumbnail(),
- div(class_="separator"),
- self.augmented.as_html_thumbnail(),
- ]
- if editable:
- elements.extend(
- [
- self._get_edit_button(),
- ]
- )
- if not self.in_use:
- elements.append(self._get_delete_button())
-
- if editable:
- elements.extend(
- a(
- _("preview"),
- href=reverse("artwork-preview", query={"id": self.id}),
- class_="preview",
- )
- )
- return render(div(elements, class_="artwork-elements flex"))
-
@pghistory.track()
class Exhibit(TimeStampedModel, ContentMixin, models.Model):
@@ -672,66 +579,6 @@ def content_type(self):
else:
raise ValueError("Invalid exhibit type")
- def as_html_thumbnail(self, editable=False):
- link_to_exhibit = reverse("exhibit-detail", query={"id": self.id})
- exhibit_title = a(h1(self.name, class_="exhibit-name"), href=link_to_exhibit)
- media_stats = []
- if self.exhibit_type == ExhibitTypes.AR:
- media_stats.append(
- p(
- a(
- "{} {}".format(self.artworks_count, _("Artwork(s)")),
- href=link_to_exhibit,
- ),
- class_="exhibit-about",
- )
- )
- elif self.exhibit_type == ExhibitTypes.MR:
- media_stats.append(
- p(
- a(
- "{} {}".format(self.augmenteds_count, _("Object(s)")),
- href=link_to_exhibit,
- ),
- class_="exhibit-about",
- )
- )
- media_stats.append(
- p(
- a(
- "{} {}".format(self.sounds_count, _("Sound(s)")),
- href=link_to_exhibit,
- ),
- class_="exhibit-about",
- )
- )
- exhibit_info = [
- p([{_("Created by ")}, b(self.owner.user.username)], class_="by"),
- p(self.date, class_="exbDate"),
- div(media_stats),
- ]
-
- button_see_this_exhibit = a(
- _("See this Exhibition"),
- href=f"/{self.slug}/",
- class_="gotoExb",
- )
-
- exhibit_card_elements = [
- exhibit_info,
- button_see_this_exhibit,
- ]
- if editable:
- exhibit_card_elements.extend(
- [div([self._get_delete_button(), self._get_edit_button()])]
- )
- exhibit_card = div(div(exhibit_card_elements, class_="exhibit-elements flex"))
- elements = [
- exhibit_title,
- exhibit_card,
- ]
- return render(elements)
-
@receiver(post_delete, sender=Object)
@receiver(post_delete, sender=Marker)
diff --git a/src/core/static/css/action-menu.css b/src/core/static/css/action-menu.css
new file mode 100644
index 000000000..12764ad92
--- /dev/null
+++ b/src/core/static/css/action-menu.css
@@ -0,0 +1,168 @@
+/* Action Menu - Three-dot dropdown */
+.action-menu-container {
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 10;
+}
+
+.action-menu-trigger {
+ background: rgba(0,0,0,0);
+ border: 1px solid rgba(0,0,0,0);
+ border-radius: 0;
+ width: 28px;
+ height: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ color: #000;
+ padding: 0;
+ margin: 1px 0;
+ transition: background 0.2s ease;
+}
+
+.action-menu-trigger:hover {
+ background: #f5f5f5;
+ border-color: #858585;
+}
+
+.action-menu-dropdown {
+ display: none;
+ position: absolute;
+ top: 100%;
+ right: 0;
+ margin-top: 4px;
+ background: #ffffff;
+ border: 1px solid #000;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ min-width: 130px;
+ overflow: hidden;
+ z-index: 100;
+}
+
+.action-menu-dropdown.open {
+ display: block;
+}
+
+/* When dropdown is open, elevate the entire container above sibling items */
+.action-menu-container:has(.action-menu-dropdown.open),
+.action-menu-container.menu-active {
+ z-index: 1000;
+}
+
+.action-menu-item {
+ display: block;
+ padding: 10px 16px;
+ font-size: 0.8em;
+ color: #333;
+ text-decoration: none;
+ white-space: nowrap;
+ transition: background 0.1s;
+}
+
+.action-menu-item:visited {
+ color: #333;
+}
+
+.action-menu-item:hover {
+ background: #f5f5f5;
+}
+
+.action-menu-item.disabled {
+ color: #aaa;
+ cursor: not-allowed;
+}
+
+.action-menu-item.disabled:hover {
+ background: #fafafa;
+}
+
+.action-menu-item.action-menu-delete:not(.disabled) {
+ color: #d32f2f;
+}
+
+.action-menu-item.action-menu-delete:not(.disabled):hover {
+ background: #fdecea;
+}
+
+/* Confirmation/info modal */
+.action-modal-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.5);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 9999;
+ opacity: 0;
+ visibility: hidden;
+ transition: opacity 0.2s, visibility 0.2s;
+}
+
+.action-modal-overlay.visible {
+ opacity: 1;
+ visibility: visible;
+}
+
+.action-modal-box {
+ background: #fff;
+ border-radius: 8px;
+ padding: 24px 28px;
+ max-width: 400px;
+ width: 90%;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
+ text-align: center;
+}
+
+.action-modal-box p {
+ margin: 0 0 20px;
+ font-size: 0.95em;
+ color: #333;
+ line-height: 1.4;
+}
+
+.action-modal-buttons {
+ display: flex;
+ gap: 10px;
+ justify-content: center;
+}
+
+.action-modal-btn {
+ padding: 8px 20px;
+ border: none;
+ border-radius: 4px;
+ font-size: 0.85em;
+ cursor: pointer;
+ transition: background 0.15s;
+}
+
+.action-modal-btn-cancel {
+ background: #e0e0e0;
+ color: #333;
+}
+
+.action-modal-btn-cancel:hover {
+ background: #d0d0d0;
+}
+
+.action-modal-btn-confirm {
+ background: #d32f2f;
+ color: #fff;
+}
+
+.action-modal-btn-confirm:hover {
+ background: #b71c1c;
+}
+
+.action-modal-btn-ok {
+ background: #5b0058;
+ color: #fff;
+}
+
+.action-modal-btn-ok:hover {
+ background: #3d003b;
+}
diff --git a/src/core/static/css/generator.css b/src/core/static/css/generator.css
index 0bc3dca98..4a1de47b2 100644
--- a/src/core/static/css/generator.css
+++ b/src/core/static/css/generator.css
@@ -61,7 +61,7 @@ label#buttonUpload {
}
div#imageContainer {
- max-width: 320px;
+ max-width: 100%;
height: 320px;
margin: 25px auto;
background: url(../images/icons/icoEptG.png) no-repeat center center;
diff --git a/src/core/static/css/generic-modal.css b/src/core/static/css/generic-modal.css
index 339f079df..d338fa582 100644
--- a/src/core/static/css/generic-modal.css
+++ b/src/core/static/css/generic-modal.css
@@ -26,6 +26,7 @@
margin: 0;
text-align: center;
background: #FFFFFF00;
+ font-size: 1.5em;
}
.modal-content {
@@ -72,22 +73,33 @@
}
#modal-header {
- display:flex;
- flex-direction: row-reverse;
+ display: flex;
+ align-items: center;
+ justify-content: center;
padding: 10px;
- justify-content: space-between;
+ position: relative;
+}
+
+#modal-header #modal-title {
+ margin: 0;
+ text-align: center;
+ flex: 1;
}
#back-modal{
font-size: larger;
margin: 0;
width: 2.5em;
+ position: absolute;
+ left: 10px;
}
#close-modal{
font-size: larger;
width: 2.5em;
margin: 0;
+ position: absolute;
+ right: 10px;
}
#artwork-description{
diff --git a/src/core/static/css/header.css b/src/core/static/css/header.css
index 2a8a6eea5..046f1be62 100644
--- a/src/core/static/css/header.css
+++ b/src/core/static/css/header.css
@@ -1,14 +1,97 @@
+.header .container {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ background-image: linear-gradient(
+ to top,
+ #77777766,
+ #77777766 50%,
+ transparent 50%,
+ transparent
+ );
+ background-position: 100% 10%;
+ background-size: 100% 200%;
+}
+
.aside {
display: flex;
justify-content: flex-end;
align-items: flex-end;
gap: 0px 5px;
font-size: 1em;
- height: 80px;
+ flex-shrink: 0;
}
.logo{
- height: 80px;
display: flex;
- flex-direction: column-reverse;
+ align-items: center;
+}
+
+/* User menu dropdown */
+.user-menu-wrapper {
+ position: relative;
+ display: inline-flex;
+ align-items: flex-end;
+ gap: 5px;
+}
+
+.welcome-text {
+ color: #777;
+ font-size: 1.2em;
+}
+
+button#user-menu-btn.user-menu-button {
+ all: unset;
+ display: inline-flex;
+ align-items: center;
+ padding: 0;
+ background: none;
+ color: #03b595;
+ border: none;
+ cursor: pointer;
+ font-family: inherit;
+ font-size: 2em;
+ font-weight: normal;
+}
+
+button#user-menu-btn.user-menu-button:hover {
+ color: #028a70;
+}
+
+.user-menu-list {
+ position: absolute;
+ top: calc(100% + 4px);
+ right: 0;
+ left: auto;
+ min-width: 160px;
+ background-color: #ffffff;
+ border: 1px solid #000000;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ opacity: 0;
+ visibility: hidden;
+ transform: translateY(-10px);
+ transition: all 0.2s ease;
+ z-index: 1000;
+}
+
+.user-menu-list.show {
+ opacity: 1;
+ visibility: visible;
+ transform: translateY(0);
+}
+
+.user-menu-list .user-menu-option {
+ all: unset;
+ display: block;
+ width: 100%;
+ padding: 10px 16px;
+ font-size: 14px;
+ color: #000;
+ cursor: pointer;
+ box-sizing: border-box;
+ text-align: left;
+}
+
+.user-menu-list .user-menu-option:hover {
+ background-color: #f5f5f5;
}
\ No newline at end of file
diff --git a/src/core/static/css/home.css b/src/core/static/css/home.css
index f78bbb6ef..c6e4eff2e 100644
--- a/src/core/static/css/home.css
+++ b/src/core/static/css/home.css
@@ -19,11 +19,13 @@
}
.use-guide {
- max-width: 300px;
+ width: 100%;
+ max-width: 100%;
margin: 0 auto;
margin-bottom: 20px;
padding: 20px;
background: url(../images/icons/fill.png), #e6e6e6;
+ box-sizing: border-box;
}
.use-guide blockquote:after, .use-guide blockquote:before {
@@ -39,6 +41,65 @@
padding-top: 6%;
}
+.home-section {
+ padding: 20px;
+ max-width: 80%;
+ margin: 0 auto;
+}
+
+.home-highlight {
+ max-width: 80%;
+ min-width: 30%;
+}
+
+.home-highlight blockquote:after, .home-highlight blockquote:before {
+ background: #03b5951a;
+}
+
+.stripped-bg {
+ background-color: #f8f8f8;
+ background-image: linear-gradient(45deg, #f8f8f8 25%, #f5f5f5 25%, #f5f5f5 50%, #f8f8f8 50%, #f8f8f8 75%, #f5f5f5 75%, #f5f5f5 100%);
+ background-size: 30px 30px;
+}
+
+.home-container {
+ border-color: rgb(229 231 235 / var(--tw-border-opacity, 1));
+ border-width: 1px;
+ --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
+ box-shadow: 0 0 #0000, 0 0 #0000, var(--tw-shadow);
+ border-style: solid;
+ width: 80%;
+ margin: 0 auto;
+ margin-bottom: 50px;
+ max-width: 1000px;
+}
+
+.home-container p {
+ font-family: "Istok Web", serif;
+ text-align: justify;
+ font-size: 1.125rem;
+ color: rgb(55 65 81);
+}
+
+.home-container a {
+ color: #03b595;
+}
+
+/* https://stackoverflow.com/questions/35814653/automatic-height-when-embedding-a-youtube-video */
+.video-container {
+ position: relative;
+ padding-bottom: 56.25%; /* 16:9 */
+ height: 0;
+}
+
+.video-container iframe {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ margin: 0 auto;
+}
/* Desktops */
@media(min-width: 800px) {
@@ -46,5 +107,10 @@
max-width: 560px;
margin-bottom: 30px;
}
+ .home-highlight {
+ max-width: 60%;
+ min-width: 30%;
+ }
+}
}
\ No newline at end of file
diff --git a/src/core/static/css/home_v2.css b/src/core/static/css/home_v2.css
deleted file mode 100644
index 732860898..000000000
--- a/src/core/static/css/home_v2.css
+++ /dev/null
@@ -1,97 +0,0 @@
-.header .signup-btn, .header .login-btn {
- background-color: black;
- text-align: center;
- height: 40px;
- line-height: 40px;
- padding: 0px 8px;
- max-width: 70px;
- min-width: 60px;
-}
-
-.header .login-btn {
- background-color: #03b595;
-}
-
-.header .signup-btn a, .header .login-btn a {
- font-weight: bold;
- color: white;
- display: block;
-}
-
-
-.home-section {
- padding: 20px;
- max-width: 80%;
- margin: 0 auto;
-
-}
-.home-highlight {
- max-width: 80%;
- min-width: 30%;
-}
-.home-highlight blockquote:after, .home-highlight blockquote:before {
- background: #03b5951a;
-}
-
-.use-guide .authorize-camera {
- background-color: black;
- text-align: center;
- max-width: 280px;
- height: 35px;
- margin: auto;
- padding-top: 6%;
-}
-
-.stripped-bg {
- background-color: #f8f8f8;
- background-image: linear-gradient(45deg, #f8f8f8 25%, #f5f5f5 25%, #f5f5f5 50%, #f8f8f8 50%, #f8f8f8 75%, #f5f5f5 75%, #f5f5f5 100%);
- background-size: 30px 30px;
-}
-
-.home-container {
- border-color: rgb(229 231 235 / var(--tw-border-opacity, 1));
- border-width: 1px;
- --tw-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
- box-shadow: 0 0 #0000, 0 0 #0000, var(--tw-shadow);
- border-style: solid;
- width: 80%;
- margin: 0 auto;
- margin-bottom: 50px;
- max-width: 1000px;
-}
-
-.home-container p
-{
- font-family: "Istok Web", serif;
- text-align: justify;
- font-size: 1.125rem;
- color: rgb(55 65 81);
-}
-
-.home-container a {
- color: #03b595;
-}
-
-/* https://stackoverflow.com/questions/35814653/automatic-height-when-embedding-a-youtube-video */
-.video-container {
- position: relative;
- padding-bottom: 56.25%; /* 16:9 */
- height: 0;
-}
-
-.video-container iframe {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- margin: 0 auto;
-}
-/* Desktops */
-@media(min-width: 800px) {
- .home-highlight {
- max-width: 60%;
- min-width: 30%;
- }
-
-}
\ No newline at end of file
diff --git a/src/core/static/css/marker-creation.css b/src/core/static/css/marker-creation.css
index ea5387868..d8fbee69a 100644
--- a/src/core/static/css/marker-creation.css
+++ b/src/core/static/css/marker-creation.css
@@ -1,8 +1,18 @@
.modal.modal {
border-radius: 0;
width: 100%;
+ max-width: 800px;
text-align: center;
padding: 3%;
+ padding-top: 0;
+}
+
+.modal.modal .repository-item {
+ flex: 0 1 calc(20% - 16px);
+}
+
+.modal.modal #repo-artwork .repository-item {
+ flex: 0 1 calc(50% - 10px);
}
.form-options{
@@ -23,4 +33,27 @@
.tab {
display: none;
+}
+
+.modal-nav-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 15px;
+ padding: 10px 0;
+}
+
+.modal-nav-header .modal-title {
+ flex: 1;
+ text-align: center;
+ margin: 0;
+ font-size: 1.4em;
+}
+
+.modal-nav-btn {
+ width: 2.5em;
+ height: 2.5em;
+ font-size: larger;
+ margin: 0;
+ flex-shrink: 0;
}
\ No newline at end of file
diff --git a/src/core/static/css/marker-menu.css b/src/core/static/css/marker-menu.css
deleted file mode 100644
index 160fdc303..000000000
--- a/src/core/static/css/marker-menu.css
+++ /dev/null
@@ -1,9 +0,0 @@
-.marker-menu{
- display: flex;
- flex-direction: row-reverse;
- max-width: 130px;
-}
-.marker-menu a{
- margin:0 !important;
- position: relative !important;
-}
\ No newline at end of file
diff --git a/src/core/static/css/repository-list.css b/src/core/static/css/repository-list.css
index cbcf8fd5c..d36ea32e1 100644
--- a/src/core/static/css/repository-list.css
+++ b/src/core/static/css/repository-list.css
@@ -1,11 +1,12 @@
.repository-list {
display: flex;
- align-items: center;
- justify-content: space-between;
+ align-items: flex-start;
+ justify-content: flex-start;
flex-wrap: wrap;
+ gap: 20px;
max-width: 100%;
padding: 0;
- margin-bottom: 40px;
+ margin-bottom: 50px;
}
.repository-list > p {
@@ -25,55 +26,60 @@
}
.repository-item {
- flex: 0 1 calc(25% - 10px);
- padding: 20px 0px;
+ flex: 0 1 calc(25% - 15px);
+ padding: 0;
+ padding-bottom: 10px;
+ min-width: 0;
+ position: relative;
+}
+
+/* Item title label above thumbnails */
+.item-title {
+ display: block;
+ font-size: 0.95em;
+ font-weight: 600;
+ color: #0c0c0c;
+ line-height: 30px;
+ height: 30px;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding: 0 6px;
+ margin: 0;
+ text-align: center;
+ box-sizing: border-box;
}
.repository-item img,
.repository-item video {
object-fit: contain;
+ max-width: 100%;
+ height: auto;
}
-.exhibit-list .repository-item, #repo-artwork .repository-item {
- flex: 0 1 calc(50% - 10px);
-}
-
-.repository-item a.edit, .repository-item a.delete, .repository-item a.preview {
- float: right;
- background-size: contain;
- width: 20px;
- height: 20px;
- text-indent: -99999px;
- border: 8px solid #fff;
- opacity: 1;
- display: block;
- margin: 10px 10px -20px auto;
-}
-
-.repository-item a.edit:hover, .repository-item a.delete:hover, .repository-item a.preview:hover {
- opacity: 0.7;
+#repo-sound .repository-item {
+ flex: 0 1 calc(33.33% - 14px);
}
-.repository-item a.edit {
- background: url(../images/icons/edit.png) no-repeat center center;
- background-size: contain;
+#repo-sound .repository-item audio {
+ width: 100%;
+ max-width: 100%;
+ height: 36px;
}
-.repository-item a.delete{
- background: url(../images/icons/delete.png) no-repeat center center;
- background-size: contain;
+.exhibit-list .repository-item {
+ flex: 0 1 calc(33.33% - 14px);
}
-.repository-item a.preview {
- background: url(../images/icons/preview.png) no-repeat center center;
- background-size: contain;
-}
#repo-artwork .repository-item {
- flex: 0 1 calc(33% - 10px);
+ flex: 0 1 calc(25% - 15px);
background: url(../images/icons/fill.png);
background-position: 100% 20%;
- margin-bottom: 30px;
+ margin-bottom: 0;
+ padding-top: 10px;
+ padding-bottom: 10px;
}
.exhibit-list .repository-item, .exhibit-detail-box {
@@ -89,33 +95,26 @@
#repo-marker.repository-list.flex .repository-item,
#repo-object.repository-list.flex .repository-item {
- flex: 0 1 calc(25%);
-}
-
-#repo-marker .repository-item a.delete, #repo-object .repository-item a.delete {
- margin: -20px 0 0 85px;
- position: absolute;
+ flex: 0 1 calc(25% - 15px);
}
-#repo-marker .repository-item a.edit, #repo-object .repository-item a.edit {
- margin: -20px 0 -30px 40px;
- position: absolute;
-}
-
-.artwork-elements a.edit, .artwork-elements a.delete, .artwork-elements a.preview {
- margin: 10px 10px -40px auto;
+#repo-object .repository-item img,
+#repo-object .repository-item video {
+ display: block;
+ margin: 0 auto;
+ min-height: 128px;
+ max-height: 128px;
+ object-fit: contain;
+ object-position: center;
}
-.artwork-elements a.delete {
- margin: 10px 10px -40px 0;
-}
h1.exhibit-name {
margin: 0 0 10px 0;
padding: 0 15px;
max-width: calc(100% - 30px);
max-height: 50px;
- font-size: 0.85em;
+ font-size: 0.95em;
font-weight: bold;
color: #5b0058;
background: #b019a650;
@@ -129,7 +128,7 @@ h1.exhibit-name:hover {
color: #af00a9;
}
-p.exhibit-slug, a.edit, a.delete{
+p.exhibit-slug {
font-size: 0.65em;
}
@@ -138,6 +137,9 @@ p.by {
display: block;
width: 100%;
margin: 0 10px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
p.by, p.exbDate, p.exhibit-about {
@@ -194,7 +196,16 @@ p.exhibit-about {
}
.artwork-elements.flex {
+ flex-wrap: nowrap;
justify-content: space-evenly;
+ align-items: center;
+ padding-top: 10px;
+}
+
+.artwork-elements img,
+.artwork-elements video {
+ flex-shrink: 1;
+ min-width: 0;
}
a.seeall {
@@ -226,6 +237,41 @@ p.url span {
}
/********* Media Queries ***********/
+@media all and (max-width: 479px) {
+ #repo-artwork .repository-item {
+ flex: 0 1 100%;
+ }
+
+ .exhibit-list .repository-item {
+ flex: 0 1 100%;
+ }
+
+ #repo-sound .repository-item {
+ flex: 0 1 100%;
+ }
+
+ #repo-marker.repository-list.flex .repository-item,
+ #repo-object.repository-list.flex .repository-item,
+ .repository-item {
+ flex: 0 1 calc(50% - 10px);
+ }
+}
+
+@media all and (min-width: 480px) and (max-width: 1024px) {
+ #repo-artwork .repository-item {
+ flex: 0 1 calc(50% - 10px);
+ }
+
+ .exhibit-list .repository-item {
+ flex: 0 1 calc(50% - 10px);
+ }
+
+ #repo-marker.repository-list.flex .repository-item,
+ #repo-object.repository-list.flex .repository-item {
+ flex: 0 1 calc(33.33% - 14px);
+ }
+}
+
@media all and (min-width: 800px) {
p.by {
flex-basis: calc(75% - 55px);
diff --git a/src/core/static/css/reset.css b/src/core/static/css/reset.css
index 1b02d25f2..3efb4c314 100644
--- a/src/core/static/css/reset.css
+++ b/src/core/static/css/reset.css
@@ -33,7 +33,7 @@ ol {
section,
form {
- margin-bottom: 20px;
+ margin-bottom: 35px;
}
a,
@@ -260,10 +260,17 @@ input[type="radio" i] {
/* Structure */
.container {
- max-width: 320px;
+ max-width: 100%;
margin: 0 auto;
text-align: center;
+ width: 80%;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+.header .container {
width: 100%;
+ padding: 0 10px;
}
.colorful .container {
@@ -309,24 +316,12 @@ a.jandigIco {
}
.aside {
- max-width: 120px;
- float: right;
background: #fff;
}
.logo {
text-align: left;
- width: 100%;
- float: left;
- background-image: linear-gradient(
- to top,
- #77777766,
- #77777766 50%,
- transparent 50%,
- transparent
- );
- background-position: 100% 10%;
- background-size: 100% 200%;
+
}
.logo a {
@@ -457,6 +452,14 @@ div.contCam:before {
column-gap: 1.5em;
}
+.useful-links .container > div:not(.contCam) {
+ margin-left: auto;
+}
+
+.useful-links .container > div:not(.contCam) ~ div:not(.contCam) {
+ margin-left: 1.5em;
+}
+
.useful-links a,
.footer a.useful {
padding: 0 5px;
@@ -514,7 +517,7 @@ h1.titObj {
}
.footer .container {
- height: 25px;
+ min-height: 25px;
margin-bottom: 20px;
}
@@ -634,9 +637,18 @@ a.sq-github {
}
/* Media Queries */
-@media all and (min-width: 800px) {
+@media all and (min-width: 480px) {
.container {
+ width: 80%;
max-width: 600px;
+ padding: 0;
+ }
+}
+
+@media all and (min-width: 800px) {
+ .container {
+ width: 80%;
+ max-width: 1200px;
margin: 0 auto;
}
@@ -646,8 +658,7 @@ a.sq-github {
}
.aside {
- max-width: 250px;
- min-width: 250px;
+ flex-shrink: 0;
}
.half {
@@ -668,17 +679,6 @@ a.sq-github {
.logo {
text-align: left;
- width: 350px;
- float: left;
- background-image: linear-gradient(
- to top,
- #77777766,
- #77777766 50%,
- transparent 50%,
- transparent
- );
- background-position: 100% 10%;
- background-size: 100% 200%;
}
.welcome,
@@ -763,7 +763,7 @@ a.sq-github {
}
.footer .container {
- height: 30px;
+ min-height: 30px;
margin-bottom: 40px;
}
diff --git a/src/core/static/css/warning.css b/src/core/static/css/warning.css
index 52927077c..877398e0f 100644
--- a/src/core/static/css/warning.css
+++ b/src/core/static/css/warning.css
@@ -6,7 +6,7 @@
padding: 16px 24px;
margin-top: 10px;
color: #111;
- max-width: 600px;
+ max-width: 100%;
border-radius: 4px;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.05);
}
diff --git a/src/core/static/images/icons/delete.png b/src/core/static/images/icons/delete.png
deleted file mode 100644
index eb49f0bca..000000000
Binary files a/src/core/static/images/icons/delete.png and /dev/null differ
diff --git a/src/core/static/images/icons/edit.png b/src/core/static/images/icons/edit.png
deleted file mode 100644
index 616c7ae14..000000000
Binary files a/src/core/static/images/icons/edit.png and /dev/null differ
diff --git a/src/core/static/images/icons/preview.png b/src/core/static/images/icons/preview.png
deleted file mode 100644
index 1e9a93b92..000000000
Binary files a/src/core/static/images/icons/preview.png and /dev/null differ
diff --git a/src/core/static/js/action-menu.js b/src/core/static/js/action-menu.js
new file mode 100644
index 000000000..b9c149dfe
--- /dev/null
+++ b/src/core/static/js/action-menu.js
@@ -0,0 +1,126 @@
+document.addEventListener("DOMContentLoaded", function () {
+ // Use capturing phase so this fires BEFORE htmx/jQuery handlers on parent elements
+ document.addEventListener("click", function (e) {
+ var menuContainer = e.target.closest(".action-menu-container");
+
+ // Any click inside the menu container: stop propagation to prevent
+ // parent handlers (HTMX modal trigger, jQuery toggleModal) from firing
+ if (menuContainer) {
+ e.stopPropagation();
+
+ var trigger = e.target.closest(".action-menu-trigger");
+ if (trigger) {
+ e.preventDefault();
+ var dropdown = trigger.nextElementSibling;
+ var container = trigger.parentElement;
+ // Close any other open menus first
+ document.querySelectorAll(".action-menu-dropdown.open").forEach(function (d) {
+ if (d !== dropdown) {
+ d.classList.remove("open");
+ d.parentElement.classList.remove("menu-active");
+ }
+ });
+ dropdown.classList.toggle("open");
+ container.classList.toggle("menu-active");
+ return;
+ }
+
+ // Handle disabled menu item click
+ var disabledItem = e.target.closest(".action-menu-item[data-disabled]");
+ if (disabledItem) {
+ e.preventDefault();
+ closeAllMenus();
+ showInfoModal(disabledItem.getAttribute("data-reason"));
+ return;
+ }
+
+ // Handle delete confirmation
+ var deleteItem = e.target.closest(".action-menu-item.action-menu-delete:not(.disabled)");
+ if (deleteItem) {
+ e.preventDefault();
+ closeAllMenus();
+ var message = deleteItem.getAttribute("data-confirm");
+ var href = deleteItem.getAttribute("href");
+ showConfirmModal(message, href);
+ return;
+ }
+
+ // For enabled Edit/Preview links: allow normal navigation (no preventDefault)
+ return;
+ }
+
+ // Click outside any menu: close all menus
+ closeAllMenus();
+ }, true); // true = capturing phase
+
+ function closeAllMenus() {
+ document.querySelectorAll(".action-menu-dropdown.open").forEach(function (d) {
+ d.classList.remove("open");
+ d.parentElement.classList.remove("menu-active");
+ });
+ }
+
+ // --- Modal functions ---
+
+ function createOverlay() {
+ var overlay = document.createElement("div");
+ overlay.className = "action-modal-overlay";
+ overlay.addEventListener("click", function (e) {
+ if (e.target === overlay) {
+ destroyOverlay(overlay);
+ }
+ });
+ document.body.appendChild(overlay);
+ // Force reflow then show
+ overlay.offsetHeight;
+ overlay.classList.add("visible");
+ return overlay;
+ }
+
+ function destroyOverlay(overlay) {
+ overlay.classList.remove("visible");
+ setTimeout(function () {
+ overlay.remove();
+ }, 200);
+ }
+
+ function showInfoModal(reason) {
+ var overlay = createOverlay();
+ var box = document.createElement("div");
+ box.className = "action-modal-box";
+ box.innerHTML =
+ '
' + escapeHtml(reason) + '
' +
+ '
' +
+ 'OK ' +
+ '
';
+ overlay.appendChild(box);
+ box.querySelector(".action-modal-btn-ok").addEventListener("click", function () {
+ destroyOverlay(overlay);
+ });
+ }
+
+ function showConfirmModal(message, href) {
+ var overlay = createOverlay();
+ var box = document.createElement("div");
+ box.className = "action-modal-box";
+ box.innerHTML =
+ '
' + escapeHtml(message) + '
' +
+ '
' +
+ 'Cancel ' +
+ 'Delete ' +
+ '
';
+ overlay.appendChild(box);
+ box.querySelector(".action-modal-btn-cancel").addEventListener("click", function () {
+ destroyOverlay(overlay);
+ });
+ box.querySelector(".action-modal-btn-confirm").addEventListener("click", function () {
+ window.location.href = href;
+ });
+ }
+
+ function escapeHtml(str) {
+ var div = document.createElement("div");
+ div.appendChild(document.createTextNode(str));
+ return div.innerHTML;
+ }
+});
diff --git a/src/core/static/js/glb-viewer.js b/src/core/static/js/glb-viewer.js
new file mode 100644
index 000000000..3819ffc21
--- /dev/null
+++ b/src/core/static/js/glb-viewer.js
@@ -0,0 +1,132 @@
+/**
+ * Shared GLB 3D model viewer using Three.js (ESM, r184).
+ *
+ * Usage:
+ * import { GLBViewer } from './glb-viewer.js';
+ * var viewer = GLBViewer.init(container, sourceUrl, options);
+ * // Later, to clean up:
+ * viewer.dispose();
+ *
+ * Options:
+ * - onThumbnailReady(renderer, scene, camera): called after model loads (for thumbnail generation)
+ * - onAnimationsFound(count): called when animations are detected
+ * - onError(error): called on load failure
+ */
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/GLTFLoader.js';
+import { OrbitControls } from 'three/addons/OrbitControls.js';
+
+function init(container, sourceUrl, options) {
+ options = options || {};
+ var renderer = null;
+ var animationFrameId = null;
+ var disposed = false;
+
+ function dispose() {
+ if (disposed) return;
+ disposed = true;
+ if (animationFrameId) {
+ cancelAnimationFrame(animationFrameId);
+ animationFrameId = null;
+ }
+ if (renderer) {
+ renderer.dispose();
+ renderer.forceContextLoss();
+ renderer = null;
+ }
+ }
+
+ var width = container.clientWidth || 600;
+ var height = container.clientHeight || width;
+
+ var scene = new THREE.Scene();
+ scene.background = new THREE.Color(0xf0f0f0);
+
+ var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
+ camera.position.set(0, 0, 5);
+
+ renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setSize(width, height);
+ container.appendChild(renderer.domElement);
+
+ var controls = new OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.05;
+ controls.enableZoom = true;
+ controls.enablePan = true;
+ controls.enableRotate = true;
+
+ var ambientLight = new THREE.AmbientLight(0xFFFDD0, 3.5);
+ scene.add(ambientLight);
+
+ var mixer = null;
+ var timer = new THREE.Timer();
+
+ function animate() {
+ if (disposed) return;
+ animationFrameId = requestAnimationFrame(animate);
+ timer.update();
+ var delta = timer.getDelta();
+ if (mixer) mixer.update(delta);
+ controls.update();
+ renderer.render(scene, camera);
+ }
+
+ var loader = new GLTFLoader();
+ loader.load(
+ sourceUrl,
+ function (gltf) {
+ if (disposed) return;
+ scene.add(gltf.scene);
+
+ if (gltf.animations && gltf.animations.length > 0) {
+ mixer = new THREE.AnimationMixer(gltf.scene);
+ gltf.animations.forEach(function (clip) {
+ mixer.clipAction(clip).play();
+ });
+ if (options.onAnimationsFound) {
+ options.onAnimationsFound(gltf.animations.length);
+ }
+ }
+
+ // Auto-scale and center the model
+ var box = new THREE.Box3().setFromObject(gltf.scene);
+ var center = box.getCenter(new THREE.Vector3());
+ var size = box.getSize(new THREE.Vector3());
+
+ gltf.scene.position.sub(center);
+
+ var maxDim = Math.max(size.x, size.y, size.z);
+ var scale = 5 / maxDim;
+ gltf.scene.scale.setScalar(scale);
+
+ var distance = Math.max(3, maxDim * 2);
+ camera.position.set(distance, distance * 0.5, distance);
+ camera.lookAt(0, 0, 0);
+
+ controls.target.set(0, 0, 0);
+ controls.update();
+
+ animate();
+
+ if (options.onThumbnailReady) {
+ setTimeout(function () {
+ if (disposed) return;
+ renderer.render(scene, camera);
+ options.onThumbnailReady(renderer, scene, camera);
+ }, 1000);
+ }
+ },
+ undefined,
+ function (error) {
+ console.error('Error loading GLB file:', error);
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ );
+
+ return { dispose: dispose };
+}
+
+export var GLBViewer = { init: init };
diff --git a/src/core/static/libs/BufferGeometryUtils-0.184.0.js b/src/core/static/libs/BufferGeometryUtils-0.184.0.js
new file mode 100644
index 000000000..6e996616e
--- /dev/null
+++ b/src/core/static/libs/BufferGeometryUtils-0.184.0.js
@@ -0,0 +1,1434 @@
+import {
+ BufferAttribute,
+ BufferGeometry,
+ Float32BufferAttribute,
+ InstancedBufferAttribute,
+ InterleavedBuffer,
+ InterleavedBufferAttribute,
+ TriangleFanDrawMode,
+ TriangleStripDrawMode,
+ TrianglesDrawMode,
+ Vector3,
+} from 'three';
+
+/**
+ * @module BufferGeometryUtils
+ * @three_import import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
+ */
+
+/**
+ * Computes vertex tangents using the MikkTSpace algorithm. MikkTSpace generates the same tangents consistently,
+ * and is used in most modelling tools and normal map bakers. Use MikkTSpace for materials with normal maps,
+ * because inconsistent tangents may lead to subtle visual issues in the normal map, particularly around mirrored
+ * UV seams.
+ *
+ * In comparison to this method, {@link BufferGeometry#computeTangents} (a custom algorithm) generates tangents that
+ * probably will not match the tangents in other software. The custom algorithm is sufficient for general use with a
+ * custom material, and may be faster than MikkTSpace.
+ *
+ * Returns the original BufferGeometry. Indexed geometries will be de-indexed. Requires position, normal, and uv attributes.
+ *
+ * @param {BufferGeometry} geometry - The geometry to compute tangents for.
+ * @param {Object} MikkTSpace - Instance of `examples/jsm/libs/mikktspace.module.js`, or `mikktspace` npm package.
+ * Await `MikkTSpace.ready` before use.
+ * @param {boolean} [negateSign=true] - Whether to negate the sign component (.w) of each tangent.
+ * Required for normal map conventions in some formats, including glTF.
+ * @return {BufferGeometry} The updated geometry.
+ */
+function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {
+
+ if ( ! MikkTSpace || ! MikkTSpace.isReady ) {
+
+ throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );
+
+ }
+
+ if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {
+
+ throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' );
+
+ }
+
+ function getAttributeArray( attribute ) {
+
+ if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {
+
+ const dstArray = new Float32Array( attribute.count * attribute.itemSize );
+
+ for ( let i = 0, j = 0; i < attribute.count; i ++ ) {
+
+ dstArray[ j ++ ] = attribute.getX( i );
+ dstArray[ j ++ ] = attribute.getY( i );
+
+ if ( attribute.itemSize > 2 ) {
+
+ dstArray[ j ++ ] = attribute.getZ( i );
+
+ }
+
+ }
+
+ return dstArray;
+
+ }
+
+ if ( attribute.array instanceof Float32Array ) {
+
+ return attribute.array;
+
+ }
+
+ return new Float32Array( attribute.array );
+
+ }
+
+ // MikkTSpace algorithm requires non-indexed input.
+
+ const _geometry = geometry.index ? geometry.toNonIndexed() : geometry;
+
+ // Compute vertex tangents.
+
+ const tangents = MikkTSpace.generateTangents(
+
+ getAttributeArray( _geometry.attributes.position ),
+ getAttributeArray( _geometry.attributes.normal ),
+ getAttributeArray( _geometry.attributes.uv )
+
+ );
+
+ // Texture coordinate convention of glTF differs from the apparent
+ // default of the MikkTSpace library; .w component must be flipped.
+
+ if ( negateSign ) {
+
+ for ( let i = 3; i < tangents.length; i += 4 ) {
+
+ tangents[ i ] *= - 1;
+
+ }
+
+ }
+
+ //
+
+ _geometry.setAttribute( 'tangent', new BufferAttribute( tangents, 4 ) );
+
+ if ( geometry !== _geometry ) {
+
+ geometry.copy( _geometry );
+
+ }
+
+ return geometry;
+
+}
+
+/**
+ * Merges a set of geometries into a single instance. All geometries must have compatible attributes.
+ *
+ * @param {Array
} geometries - The geometries to merge.
+ * @param {boolean} [useGroups=false] - Whether to use groups or not.
+ * @return {?BufferGeometry} The merged geometry. Returns `null` if the merge does not succeed.
+ */
+function mergeGeometries( geometries, useGroups = false ) {
+
+ const isIndexed = geometries[ 0 ].index !== null;
+
+ const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
+ const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
+
+ const attributes = {};
+ const morphAttributes = {};
+
+ const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
+
+ const mergedGeometry = new BufferGeometry();
+
+ let offset = 0;
+
+ for ( let i = 0; i < geometries.length; ++ i ) {
+
+ const geometry = geometries[ i ];
+ let attributesCount = 0;
+
+ // ensure that all geometries are indexed, or none
+
+ if ( isIndexed !== ( geometry.index !== null ) ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
+ return null;
+
+ }
+
+ // gather attributes, exit early if they're different
+
+ for ( const name in geometry.attributes ) {
+
+ if ( ! attributesUsed.has( name ) ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
+ return null;
+
+ }
+
+ if ( attributes[ name ] === undefined ) attributes[ name ] = [];
+
+ attributes[ name ].push( geometry.attributes[ name ] );
+
+ attributesCount ++;
+
+ }
+
+ // ensure geometries have the same number of attributes
+
+ if ( attributesCount !== attributesUsed.size ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
+ return null;
+
+ }
+
+ // gather morph attributes, exit early if they're different
+
+ if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
+ return null;
+
+ }
+
+ for ( const name in geometry.morphAttributes ) {
+
+ if ( ! morphAttributesUsed.has( name ) ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
+ return null;
+
+ }
+
+ if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
+
+ morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
+
+ }
+
+ if ( useGroups ) {
+
+ let count;
+
+ if ( isIndexed ) {
+
+ count = geometry.index.count;
+
+ } else if ( geometry.attributes.position !== undefined ) {
+
+ count = geometry.attributes.position.count;
+
+ } else {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
+ return null;
+
+ }
+
+ mergedGeometry.addGroup( offset, count, i );
+
+ offset += count;
+
+ }
+
+ }
+
+ // merge indices
+
+ if ( isIndexed ) {
+
+ let indexOffset = 0;
+ const mergedIndex = [];
+
+ for ( let i = 0; i < geometries.length; ++ i ) {
+
+ const index = geometries[ i ].index;
+
+ for ( let j = 0; j < index.count; ++ j ) {
+
+ mergedIndex.push( index.getX( j ) + indexOffset );
+
+ }
+
+ indexOffset += geometries[ i ].attributes.position.count;
+
+ }
+
+ mergedGeometry.setIndex( mergedIndex );
+
+ }
+
+ // merge attributes
+
+ for ( const name in attributes ) {
+
+ const mergedAttribute = mergeAttributes( attributes[ name ] );
+
+ if ( ! mergedAttribute ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' attribute.' );
+ return null;
+
+ }
+
+ mergedGeometry.setAttribute( name, mergedAttribute );
+
+ }
+
+ // merge morph attributes
+
+ for ( const name in morphAttributes ) {
+
+ const numMorphTargets = morphAttributes[ name ][ 0 ].length;
+ if ( numMorphTargets === 0 ) continue;
+
+ mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
+ mergedGeometry.morphAttributes[ name ] = [];
+
+ for ( let i = 0; i < numMorphTargets; ++ i ) {
+
+ const morphAttributesToMerge = [];
+
+ for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
+
+ morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
+
+ }
+
+ const mergedMorphAttribute = mergeAttributes( morphAttributesToMerge );
+
+ if ( ! mergedMorphAttribute ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
+ return null;
+
+ }
+
+ mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
+
+ }
+
+ }
+
+ return mergedGeometry;
+
+}
+
+/**
+ * Merges a set of attributes into a single instance. All attributes must have compatible properties and types.
+ * Instances of {@link InterleavedBufferAttribute} are not supported.
+ *
+ * @param {Array} attributes - The attributes to merge.
+ * @return {?BufferAttribute} The merged attribute. Returns `null` if the merge does not succeed.
+ */
+function mergeAttributes( attributes ) {
+
+ let TypedArray;
+ let itemSize;
+ let normalized;
+ let gpuType = - 1;
+ let arrayLength = 0;
+
+ for ( let i = 0; i < attributes.length; ++ i ) {
+
+ const attribute = attributes[ i ];
+
+ if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
+ if ( TypedArray !== attribute.array.constructor ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
+ return null;
+
+ }
+
+ if ( itemSize === undefined ) itemSize = attribute.itemSize;
+ if ( itemSize !== attribute.itemSize ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
+ return null;
+
+ }
+
+ if ( normalized === undefined ) normalized = attribute.normalized;
+ if ( normalized !== attribute.normalized ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
+ return null;
+
+ }
+
+ if ( gpuType === - 1 ) gpuType = attribute.gpuType;
+ if ( gpuType !== attribute.gpuType ) {
+
+ console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.' );
+ return null;
+
+ }
+
+ arrayLength += attribute.count * itemSize;
+
+ }
+
+ const array = new TypedArray( arrayLength );
+ const result = new BufferAttribute( array, itemSize, normalized );
+ let offset = 0;
+
+ for ( let i = 0; i < attributes.length; ++ i ) {
+
+ const attribute = attributes[ i ];
+ if ( attribute.isInterleavedBufferAttribute ) {
+
+ const tupleOffset = offset / itemSize;
+ for ( let j = 0, l = attribute.count; j < l; j ++ ) {
+
+ for ( let c = 0; c < itemSize; c ++ ) {
+
+ const value = attribute.getComponent( j, c );
+ result.setComponent( j + tupleOffset, c, value );
+
+ }
+
+ }
+
+ } else {
+
+ array.set( attribute.array, offset );
+
+ }
+
+ offset += attribute.count * itemSize;
+
+ }
+
+ if ( gpuType !== undefined ) {
+
+ result.gpuType = gpuType;
+
+ }
+
+ return result;
+
+}
+
+/**
+ * Performs a deep clone of the given buffer attribute.
+ *
+ * @param {BufferAttribute} attribute - The attribute to clone.
+ * @return {BufferAttribute} The cloned attribute.
+ */
+function deepCloneAttribute( attribute ) {
+
+ if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) {
+
+ return deinterleaveAttribute( attribute );
+
+ }
+
+ if ( attribute.isInstancedBufferAttribute ) {
+
+ return new InstancedBufferAttribute().copy( attribute );
+
+ }
+
+ return new BufferAttribute().copy( attribute );
+
+}
+
+/**
+ * Interleaves a set of attributes and returns a new array of corresponding attributes that share a
+ * single {@link InterleavedBuffer} instance. All attributes must have compatible types.
+ *
+ * @param {Array} attributes - The attributes to interleave.
+ * @return {?Array} An array of interleaved attributes. If interleave does not succeed, the method returns `null`.
+ */
+function interleaveAttributes( attributes ) {
+
+ // Interleaves the provided attributes into an InterleavedBuffer and returns
+ // a set of InterleavedBufferAttributes for each attribute
+ let TypedArray;
+ let arrayLength = 0;
+ let stride = 0;
+
+ // calculate the length and type of the interleavedBuffer
+ for ( let i = 0, l = attributes.length; i < l; ++ i ) {
+
+ const attribute = attributes[ i ];
+
+ if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
+ if ( TypedArray !== attribute.array.constructor ) {
+
+ console.error( 'AttributeBuffers of different types cannot be interleaved' );
+ return null;
+
+ }
+
+ arrayLength += attribute.array.length;
+ stride += attribute.itemSize;
+
+ }
+
+ // Create the set of buffer attributes
+ const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
+ let offset = 0;
+ const res = [];
+ const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
+ const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
+
+ for ( let j = 0, l = attributes.length; j < l; j ++ ) {
+
+ const attribute = attributes[ j ];
+ const itemSize = attribute.itemSize;
+ const count = attribute.count;
+ const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
+ res.push( iba );
+
+ offset += itemSize;
+
+ // Move the data for each attribute into the new interleavedBuffer
+ // at the appropriate offset
+ for ( let c = 0; c < count; c ++ ) {
+
+ for ( let k = 0; k < itemSize; k ++ ) {
+
+ iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
+
+ }
+
+ }
+
+ }
+
+ return res;
+
+}
+
+/**
+ * Returns a new, non-interleaved version of the given attribute.
+ *
+ * @param {InterleavedBufferAttribute} attribute - The interleaved attribute.
+ * @return {BufferAttribute} The non-interleaved attribute.
+ */
+function deinterleaveAttribute( attribute ) {
+
+ const cons = attribute.data.array.constructor;
+ const count = attribute.count;
+ const itemSize = attribute.itemSize;
+ const normalized = attribute.normalized;
+
+ const array = new cons( count * itemSize );
+ let newAttribute;
+ if ( attribute.isInstancedInterleavedBufferAttribute ) {
+
+ newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
+
+ } else {
+
+ newAttribute = new BufferAttribute( array, itemSize, normalized );
+
+ }
+
+ for ( let i = 0; i < count; i ++ ) {
+
+ newAttribute.setX( i, attribute.getX( i ) );
+
+ if ( itemSize >= 2 ) {
+
+ newAttribute.setY( i, attribute.getY( i ) );
+
+ }
+
+ if ( itemSize >= 3 ) {
+
+ newAttribute.setZ( i, attribute.getZ( i ) );
+
+ }
+
+ if ( itemSize >= 4 ) {
+
+ newAttribute.setW( i, attribute.getW( i ) );
+
+ }
+
+ }
+
+ return newAttribute;
+
+}
+
+/**
+ * Deinterleaves all attributes on the given geometry.
+ *
+ * @param {BufferGeometry} geometry - The geometry to deinterleave.
+ */
+function deinterleaveGeometry( geometry ) {
+
+ const attributes = geometry.attributes;
+ const morphTargets = geometry.morphTargets;
+ const attrMap = new Map();
+
+ for ( const key in attributes ) {
+
+ const attr = attributes[ key ];
+ if ( attr.isInterleavedBufferAttribute ) {
+
+ if ( ! attrMap.has( attr ) ) {
+
+ attrMap.set( attr, deinterleaveAttribute( attr ) );
+
+ }
+
+ attributes[ key ] = attrMap.get( attr );
+
+ }
+
+ }
+
+ for ( const key in morphTargets ) {
+
+ const attr = morphTargets[ key ];
+ if ( attr.isInterleavedBufferAttribute ) {
+
+ if ( ! attrMap.has( attr ) ) {
+
+ attrMap.set( attr, deinterleaveAttribute( attr ) );
+
+ }
+
+ morphTargets[ key ] = attrMap.get( attr );
+
+ }
+
+ }
+
+}
+
+/**
+ * Returns the amount of bytes used by all attributes to represent the geometry.
+ *
+ * @param {BufferGeometry} geometry - The geometry.
+ * @return {number} The estimate bytes used.
+ */
+function estimateBytesUsed( geometry ) {
+
+ // Return the estimated memory used by this geometry in bytes
+ // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
+ // for InterleavedBufferAttributes.
+ let mem = 0;
+ for ( const name in geometry.attributes ) {
+
+ const attr = geometry.getAttribute( name );
+ mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
+
+ }
+
+ const indices = geometry.getIndex();
+ mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
+ return mem;
+
+}
+
+/**
+ * Returns a new geometry with vertices for which all similar vertex attributes (within tolerance) are merged.
+ *
+ * @param {BufferGeometry} geometry - The geometry to merge vertices for.
+ * @param {number} [tolerance=1e-4] - The tolerance value.
+ * @return {BufferGeometry} - The new geometry with merged vertices.
+ */
+function mergeVertices( geometry, tolerance = 1e-4 ) {
+
+ tolerance = Math.max( tolerance, Number.EPSILON );
+
+ // Generate an index buffer if the geometry doesn't have one, or optimize it
+ // if it's already available.
+ const hashToIndex = {};
+ const indices = geometry.getIndex();
+ const positions = geometry.getAttribute( 'position' );
+ const vertexCount = indices ? indices.count : positions.count;
+
+ // next value for triangle indices
+ let nextIndex = 0;
+
+ // attributes and new attribute arrays
+ const attributeNames = Object.keys( geometry.attributes );
+ const tmpAttributes = {};
+ const tmpMorphAttributes = {};
+ const newIndices = [];
+ const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
+ const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
+
+ // Initialize the arrays, allocating space conservatively. Extra
+ // space will be trimmed in the last step.
+ for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
+
+ const name = attributeNames[ i ];
+ const attr = geometry.attributes[ name ];
+
+ tmpAttributes[ name ] = new attr.constructor(
+ new attr.array.constructor( attr.count * attr.itemSize ),
+ attr.itemSize,
+ attr.normalized
+ );
+
+ const morphAttributes = geometry.morphAttributes[ name ];
+ if ( morphAttributes ) {
+
+ if ( ! tmpMorphAttributes[ name ] ) tmpMorphAttributes[ name ] = [];
+ morphAttributes.forEach( ( morphAttr, i ) => {
+
+ const array = new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize );
+ tmpMorphAttributes[ name ][ i ] = new morphAttr.constructor( array, morphAttr.itemSize, morphAttr.normalized );
+
+ } );
+
+ }
+
+ }
+
+ // convert the error tolerance to an amount of decimal places to truncate to
+ const halfTolerance = tolerance * 0.5;
+ const exponent = Math.log10( 1 / tolerance );
+ const hashMultiplier = Math.pow( 10, exponent );
+ const hashAdditive = halfTolerance * hashMultiplier;
+ for ( let i = 0; i < vertexCount; i ++ ) {
+
+ const index = indices ? indices.getX( i ) : i;
+
+ // Generate a hash for the vertex attributes at the current index 'i'
+ let hash = '';
+ for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
+
+ const name = attributeNames[ j ];
+ const attribute = geometry.getAttribute( name );
+ const itemSize = attribute.itemSize;
+
+ for ( let k = 0; k < itemSize; k ++ ) {
+
+ // double tilde truncates the decimal value
+ hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * hashMultiplier + hashAdditive ) },`;
+
+ }
+
+ }
+
+ // Add another reference to the vertex if it's already
+ // used by another index
+ if ( hash in hashToIndex ) {
+
+ newIndices.push( hashToIndex[ hash ] );
+
+ } else {
+
+ // copy data to the new index in the temporary attributes
+ for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
+
+ const name = attributeNames[ j ];
+ const attribute = geometry.getAttribute( name );
+ const morphAttributes = geometry.morphAttributes[ name ];
+ const itemSize = attribute.itemSize;
+ const newArray = tmpAttributes[ name ];
+ const newMorphArrays = tmpMorphAttributes[ name ];
+
+ for ( let k = 0; k < itemSize; k ++ ) {
+
+ const getterFunc = getters[ k ];
+ const setterFunc = setters[ k ];
+ newArray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
+
+ if ( morphAttributes ) {
+
+ for ( let m = 0, ml = morphAttributes.length; m < ml; m ++ ) {
+
+ newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttributes[ m ][ getterFunc ]( index ) );
+
+ }
+
+ }
+
+ }
+
+ }
+
+ hashToIndex[ hash ] = nextIndex;
+ newIndices.push( nextIndex );
+ nextIndex ++;
+
+ }
+
+ }
+
+ // generate result BufferGeometry
+ const result = geometry.clone();
+ for ( const name in geometry.attributes ) {
+
+ const tmpAttribute = tmpAttributes[ name ];
+
+ result.setAttribute( name, new tmpAttribute.constructor(
+ tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ),
+ tmpAttribute.itemSize,
+ tmpAttribute.normalized,
+ ) );
+
+ if ( ! ( name in tmpMorphAttributes ) ) continue;
+
+ for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
+
+ const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
+
+ result.morphAttributes[ name ][ j ] = new tmpMorphAttribute.constructor(
+ tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ),
+ tmpMorphAttribute.itemSize,
+ tmpMorphAttribute.normalized,
+ );
+
+ }
+
+ }
+
+ // indices
+
+ result.setIndex( newIndices );
+
+ return result;
+
+}
+
+/**
+ * Returns a new indexed geometry based on `TrianglesDrawMode` draw mode.
+ * This mode corresponds to the `gl.TRIANGLES` primitive in WebGL.
+ *
+ * @param {BufferGeometry} geometry - The geometry to convert.
+ * @param {number} drawMode - The current draw mode.
+ * @return {BufferGeometry} The new geometry using `TrianglesDrawMode`.
+ */
+function toTrianglesDrawMode( geometry, drawMode ) {
+
+ if ( drawMode === TrianglesDrawMode ) {
+
+ console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
+ return geometry;
+
+ }
+
+ if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
+
+ let index = geometry.getIndex();
+
+ // generate index if not present
+
+ if ( index === null ) {
+
+ const indices = [];
+
+ const position = geometry.getAttribute( 'position' );
+
+ if ( position !== undefined ) {
+
+ for ( let i = 0; i < position.count; i ++ ) {
+
+ indices.push( i );
+
+ }
+
+ geometry.setIndex( indices );
+ index = geometry.getIndex();
+
+ } else {
+
+ console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
+ return geometry;
+
+ }
+
+ }
+
+ //
+
+ const numberOfTriangles = index.count - 2;
+ const newIndices = [];
+
+ if ( drawMode === TriangleFanDrawMode ) {
+
+ // gl.TRIANGLE_FAN
+
+ for ( let i = 1; i <= numberOfTriangles; i ++ ) {
+
+ newIndices.push( index.getX( 0 ) );
+ newIndices.push( index.getX( i ) );
+ newIndices.push( index.getX( i + 1 ) );
+
+ }
+
+ } else {
+
+ // gl.TRIANGLE_STRIP
+
+ for ( let i = 0; i < numberOfTriangles; i ++ ) {
+
+ if ( i % 2 === 0 ) {
+
+ newIndices.push( index.getX( i ) );
+ newIndices.push( index.getX( i + 1 ) );
+ newIndices.push( index.getX( i + 2 ) );
+
+ } else {
+
+ newIndices.push( index.getX( i + 2 ) );
+ newIndices.push( index.getX( i + 1 ) );
+ newIndices.push( index.getX( i ) );
+
+ }
+
+ }
+
+ }
+
+ if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
+
+ console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
+
+ }
+
+ // build final geometry
+
+ const newGeometry = geometry.clone();
+ newGeometry.setIndex( newIndices );
+ newGeometry.clearGroups();
+
+ return newGeometry;
+
+ } else {
+
+ console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
+ return geometry;
+
+ }
+
+}
+
+/**
+ * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
+ *
+ * Helpful for Raytracing or Decals (i.e. a `DecalGeometry` applied to a morphed Object with a `BufferGeometry`
+ * will use the original `BufferGeometry`, not the morphed/skinned one, generating an incorrect result.
+ * Using this function to create a shadow `Object3`D the `DecalGeometry` can be correctly generated).
+ *
+ * @param {Mesh|Line|Points} object - The 3D object to compute morph attributes for.
+ * @return {Object} An object with original position/normal attributes and morphed ones.
+ */
+function computeMorphedAttributes( object ) {
+
+ const _vA = new Vector3();
+ const _vB = new Vector3();
+ const _vC = new Vector3();
+
+ const _tempA = new Vector3();
+ const _tempB = new Vector3();
+ const _tempC = new Vector3();
+
+ const _morphA = new Vector3();
+ const _morphB = new Vector3();
+ const _morphC = new Vector3();
+
+ function _calculateMorphedAttributeData(
+ object,
+ attribute,
+ morphAttribute,
+ morphTargetsRelative,
+ a,
+ b,
+ c,
+ modifiedAttributeArray
+ ) {
+
+ _vA.fromBufferAttribute( attribute, a );
+ _vB.fromBufferAttribute( attribute, b );
+ _vC.fromBufferAttribute( attribute, c );
+
+ const morphInfluences = object.morphTargetInfluences;
+
+ if ( morphAttribute && morphInfluences ) {
+
+ _morphA.set( 0, 0, 0 );
+ _morphB.set( 0, 0, 0 );
+ _morphC.set( 0, 0, 0 );
+
+ for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
+
+ const influence = morphInfluences[ i ];
+ const morph = morphAttribute[ i ];
+
+ if ( influence === 0 ) continue;
+
+ _tempA.fromBufferAttribute( morph, a );
+ _tempB.fromBufferAttribute( morph, b );
+ _tempC.fromBufferAttribute( morph, c );
+
+ if ( morphTargetsRelative ) {
+
+ _morphA.addScaledVector( _tempA, influence );
+ _morphB.addScaledVector( _tempB, influence );
+ _morphC.addScaledVector( _tempC, influence );
+
+ } else {
+
+ _morphA.addScaledVector( _tempA.sub( _vA ), influence );
+ _morphB.addScaledVector( _tempB.sub( _vB ), influence );
+ _morphC.addScaledVector( _tempC.sub( _vC ), influence );
+
+ }
+
+ }
+
+ _vA.add( _morphA );
+ _vB.add( _morphB );
+ _vC.add( _morphC );
+
+ }
+
+ if ( object.isSkinnedMesh ) {
+
+ object.applyBoneTransform( a, _vA );
+ object.applyBoneTransform( b, _vB );
+ object.applyBoneTransform( c, _vC );
+
+ }
+
+ modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
+ modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
+ modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
+ modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
+ modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
+ modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
+ modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
+ modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
+ modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
+
+ }
+
+ const geometry = object.geometry;
+ const material = object.material;
+
+ let a, b, c;
+ const index = geometry.index;
+ const positionAttribute = geometry.attributes.position;
+ const morphPosition = geometry.morphAttributes.position;
+ const morphTargetsRelative = geometry.morphTargetsRelative;
+ const normalAttribute = geometry.attributes.normal;
+ const morphNormal = geometry.morphAttributes.normal;
+
+ const groups = geometry.groups;
+ const drawRange = geometry.drawRange;
+ let i, j, il, jl;
+ let group;
+ let start, end;
+
+ const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
+ const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
+
+ if ( index !== null ) {
+
+ // indexed buffer geometry
+
+ if ( Array.isArray( material ) ) {
+
+ for ( i = 0, il = groups.length; i < il; i ++ ) {
+
+ group = groups[ i ];
+
+ start = Math.max( group.start, drawRange.start );
+ end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
+
+ for ( j = start, jl = end; j < jl; j += 3 ) {
+
+ a = index.getX( j );
+ b = index.getX( j + 1 );
+ c = index.getX( j + 2 );
+
+ _calculateMorphedAttributeData(
+ object,
+ positionAttribute,
+ morphPosition,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedPosition
+ );
+
+ _calculateMorphedAttributeData(
+ object,
+ normalAttribute,
+ morphNormal,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedNormal
+ );
+
+ }
+
+ }
+
+ } else {
+
+ start = Math.max( 0, drawRange.start );
+ end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
+
+ for ( i = start, il = end; i < il; i += 3 ) {
+
+ a = index.getX( i );
+ b = index.getX( i + 1 );
+ c = index.getX( i + 2 );
+
+ _calculateMorphedAttributeData(
+ object,
+ positionAttribute,
+ morphPosition,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedPosition
+ );
+
+ _calculateMorphedAttributeData(
+ object,
+ normalAttribute,
+ morphNormal,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedNormal
+ );
+
+ }
+
+ }
+
+ } else {
+
+ // non-indexed buffer geometry
+
+ if ( Array.isArray( material ) ) {
+
+ for ( i = 0, il = groups.length; i < il; i ++ ) {
+
+ group = groups[ i ];
+
+ start = Math.max( group.start, drawRange.start );
+ end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
+
+ for ( j = start, jl = end; j < jl; j += 3 ) {
+
+ a = j;
+ b = j + 1;
+ c = j + 2;
+
+ _calculateMorphedAttributeData(
+ object,
+ positionAttribute,
+ morphPosition,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedPosition
+ );
+
+ _calculateMorphedAttributeData(
+ object,
+ normalAttribute,
+ morphNormal,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedNormal
+ );
+
+ }
+
+ }
+
+ } else {
+
+ start = Math.max( 0, drawRange.start );
+ end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
+
+ for ( i = start, il = end; i < il; i += 3 ) {
+
+ a = i;
+ b = i + 1;
+ c = i + 2;
+
+ _calculateMorphedAttributeData(
+ object,
+ positionAttribute,
+ morphPosition,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedPosition
+ );
+
+ _calculateMorphedAttributeData(
+ object,
+ normalAttribute,
+ morphNormal,
+ morphTargetsRelative,
+ a, b, c,
+ modifiedNormal
+ );
+
+ }
+
+ }
+
+ }
+
+ const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
+ const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
+
+ return {
+
+ positionAttribute: positionAttribute,
+ normalAttribute: normalAttribute,
+ morphedPositionAttribute: morphedPositionAttribute,
+ morphedNormalAttribute: morphedNormalAttribute
+
+ };
+
+}
+
+/**
+ * Merges the {@link BufferGeometry#groups} for the given geometry.
+ *
+ * @param {BufferGeometry} geometry - The geometry to modify.
+ * @return {BufferGeometry} - The updated geometry
+ */
+function mergeGroups( geometry ) {
+
+ if ( geometry.groups.length === 0 ) {
+
+ console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
+ return geometry;
+
+ }
+
+ let groups = geometry.groups;
+
+ // sort groups by material index
+
+ groups = groups.sort( ( a, b ) => {
+
+ if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
+
+ return a.start - b.start;
+
+ } );
+
+ // create index for non-indexed geometries
+
+ if ( geometry.getIndex() === null ) {
+
+ const positionAttribute = geometry.getAttribute( 'position' );
+ const indices = [];
+
+ for ( let i = 0; i < positionAttribute.count; i += 3 ) {
+
+ indices.push( i, i + 1, i + 2 );
+
+ }
+
+ geometry.setIndex( indices );
+
+ }
+
+ // sort index
+
+ const index = geometry.getIndex();
+
+ const newIndices = [];
+
+ for ( let i = 0; i < groups.length; i ++ ) {
+
+ const group = groups[ i ];
+
+ const groupStart = group.start;
+ const groupLength = groupStart + group.count;
+
+ for ( let j = groupStart; j < groupLength; j ++ ) {
+
+ newIndices.push( index.getX( j ) );
+
+ }
+
+ }
+
+ geometry.dispose(); // Required to force buffer recreation
+ geometry.setIndex( newIndices );
+
+ // update groups indices
+
+ let start = 0;
+
+ for ( let i = 0; i < groups.length; i ++ ) {
+
+ const group = groups[ i ];
+
+ group.start = start;
+ start += group.count;
+
+ }
+
+ // merge groups
+
+ let currentGroup = groups[ 0 ];
+
+ geometry.groups = [ currentGroup ];
+
+ for ( let i = 1; i < groups.length; i ++ ) {
+
+ const group = groups[ i ];
+
+ if ( currentGroup.materialIndex === group.materialIndex ) {
+
+ currentGroup.count += group.count;
+
+ } else {
+
+ currentGroup = group;
+ geometry.groups.push( currentGroup );
+
+ }
+
+ }
+
+ return geometry;
+
+}
+
+/**
+ * Modifies the supplied geometry if it is non-indexed, otherwise creates a new,
+ * non-indexed geometry. Returns the geometry with smooth normals everywhere except
+ * faces that meet at an angle greater than the crease angle.
+ *
+ * @param {BufferGeometry} geometry - The geometry to modify.
+ * @param {number} [creaseAngle=Math.PI/3] - The crease angle in radians.
+ * @return {BufferGeometry} - The updated geometry
+ */
+function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) {
+
+ const creaseDot = Math.cos( creaseAngle );
+ const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
+
+ // reusable vectors
+ const verts = [ new Vector3(), new Vector3(), new Vector3() ];
+ const tempVec1 = new Vector3();
+ const tempVec2 = new Vector3();
+ const tempNorm = new Vector3();
+ const tempNorm2 = new Vector3();
+
+ // hashes a vector
+ function hashVertex( v ) {
+
+ const x = ~ ~ ( v.x * hashMultiplier );
+ const y = ~ ~ ( v.y * hashMultiplier );
+ const z = ~ ~ ( v.z * hashMultiplier );
+ return `${x},${y},${z}`;
+
+ }
+
+ // BufferGeometry.toNonIndexed() warns if the geometry is non-indexed
+ // and returns the original geometry
+ const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry;
+ const posAttr = resultGeometry.attributes.position;
+ const vertexMap = {};
+
+ // find all the normals shared by commonly located vertices
+ for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
+
+ const i3 = 3 * i;
+ const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
+ const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
+ const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
+
+ tempVec1.subVectors( c, b );
+ tempVec2.subVectors( a, b );
+
+ // add the normal to the map for all vertices
+ const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize();
+ for ( let n = 0; n < 3; n ++ ) {
+
+ const vert = verts[ n ];
+ const hash = hashVertex( vert );
+ if ( ! ( hash in vertexMap ) ) {
+
+ vertexMap[ hash ] = [];
+
+ }
+
+ vertexMap[ hash ].push( normal );
+
+ }
+
+ }
+
+ // average normals from all vertices that share a common location if they are within the
+ // provided crease threshold
+ const normalArray = new Float32Array( posAttr.count * 3 );
+ const normAttr = new BufferAttribute( normalArray, 3, false );
+ for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) {
+
+ // get the face normal for this vertex
+ const i3 = 3 * i;
+ const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 );
+ const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 );
+ const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 );
+
+ tempVec1.subVectors( c, b );
+ tempVec2.subVectors( a, b );
+
+ tempNorm.crossVectors( tempVec1, tempVec2 ).normalize();
+
+ // average all normals that meet the threshold and set the normal value
+ for ( let n = 0; n < 3; n ++ ) {
+
+ const vert = verts[ n ];
+ const hash = hashVertex( vert );
+ const otherNormals = vertexMap[ hash ];
+ tempNorm2.set( 0, 0, 0 );
+
+ for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) {
+
+ const otherNorm = otherNormals[ k ];
+ if ( tempNorm.dot( otherNorm ) > creaseDot ) {
+
+ tempNorm2.add( otherNorm );
+
+ }
+
+ }
+
+ tempNorm2.normalize();
+ normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z );
+
+ }
+
+ }
+
+ resultGeometry.setAttribute( 'normal', normAttr );
+ return resultGeometry;
+
+}
+
+export {
+ computeMikkTSpaceTangents,
+ mergeGeometries,
+ mergeAttributes,
+ deepCloneAttribute,
+ deinterleaveAttribute,
+ deinterleaveGeometry,
+ interleaveAttributes,
+ estimateBytesUsed,
+ mergeVertices,
+ toTrianglesDrawMode,
+ computeMorphedAttributes,
+ mergeGroups,
+ toCreasedNormals
+};
diff --git a/src/core/static/libs/GLTFLoader-0.184.0.js b/src/core/static/libs/GLTFLoader-0.184.0.js
new file mode 100644
index 000000000..90b8c6868
--- /dev/null
+++ b/src/core/static/libs/GLTFLoader-0.184.0.js
@@ -0,0 +1,4860 @@
+import {
+ AnimationClip,
+ Bone,
+ Box3,
+ BufferAttribute,
+ BufferGeometry,
+ ClampToEdgeWrapping,
+ Color,
+ ColorManagement,
+ DirectionalLight,
+ DoubleSide,
+ FileLoader,
+ FrontSide,
+ Group,
+ ImageBitmapLoader,
+ InstancedMesh,
+ InterleavedBuffer,
+ InterleavedBufferAttribute,
+ Interpolant,
+ InterpolateDiscrete,
+ InterpolateLinear,
+ Line,
+ LineBasicMaterial,
+ LineLoop,
+ LineSegments,
+ LinearFilter,
+ LinearMipmapLinearFilter,
+ LinearMipmapNearestFilter,
+ LinearSRGBColorSpace,
+ Loader,
+ LoaderUtils,
+ Material,
+ MathUtils,
+ Matrix4,
+ Mesh,
+ MeshBasicMaterial,
+ MeshPhysicalMaterial,
+ MeshStandardMaterial,
+ MirroredRepeatWrapping,
+ NearestFilter,
+ NearestMipmapLinearFilter,
+ NearestMipmapNearestFilter,
+ NumberKeyframeTrack,
+ Object3D,
+ OrthographicCamera,
+ PerspectiveCamera,
+ PointLight,
+ Points,
+ PointsMaterial,
+ PropertyBinding,
+ Quaternion,
+ QuaternionKeyframeTrack,
+ RepeatWrapping,
+ Skeleton,
+ SkinnedMesh,
+ Sphere,
+ SpotLight,
+ Texture,
+ TextureLoader,
+ TriangleFanDrawMode,
+ TriangleStripDrawMode,
+ Vector2,
+ Vector3,
+ VectorKeyframeTrack,
+ SRGBColorSpace,
+ InstancedBufferAttribute
+} from 'three';
+import { toTrianglesDrawMode } from './BufferGeometryUtils-0.184.0.js';
+import { clone } from './SkeletonUtils-0.184.0.js';
+
+/**
+ * A loader for the glTF 2.0 format.
+ *
+ * [glTF](https://www.khronos.org/gltf/) (GL Transmission Format) is an [open format specification]{@link https://github.com/KhronosGroup/glTF/tree/main/specification/2.0)
+ * for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb)
+ * format. External files store textures (.jpg, .png) and additional binary data (.bin). A glTF asset may deliver
+ * one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights,
+ * and/or cameras.
+ *
+ * `GLTFLoader` uses {@link ImageBitmapLoader} whenever possible. Be advised that image bitmaps are not
+ * automatically GC-collected when they are no longer referenced, and they require special handling during
+ * the disposal process.
+ *
+ * `GLTFLoader` supports the following glTF 2.0 extensions:
+ * - KHR_draco_mesh_compression
+ * - KHR_lights_punctual
+ * - KHR_materials_anisotropy
+ * - KHR_materials_clearcoat
+ * - KHR_materials_dispersion
+ * - KHR_materials_emissive_strength
+ * - KHR_materials_ior
+ * - KHR_materials_specular
+ * - KHR_materials_transmission
+ * - KHR_materials_iridescence
+ * - KHR_materials_unlit
+ * - KHR_materials_volume
+ * - KHR_mesh_quantization
+ * - KHR_meshopt_compression
+ * - KHR_texture_basisu
+ * - KHR_texture_transform
+ * - EXT_materials_bump
+ * - EXT_meshopt_compression
+ * - EXT_mesh_gpu_instancing
+ * - EXT_texture_avif
+ * - EXT_texture_webp
+ *
+ * The following glTF 2.0 extension is supported by an external user plugin:
+ * - [KHR_materials_variants](https://github.com/takahirox/three-gltf-extensions)
+ * - [MSFT_texture_dds](https://github.com/takahirox/three-gltf-extensions)
+ * - [KHR_animation_pointer](https://github.com/needle-tools/three-animation-pointer)
+ * - [NEEDLE_progressive](https://github.com/needle-tools/gltf-progressive)
+ *
+ * ```js
+ * const loader = new GLTFLoader();
+ *
+ * // Optional: Provide a DRACOLoader instance to decode compressed mesh data
+ * const dracoLoader = new DRACOLoader();
+ * dracoLoader.setDecoderPath( '/examples/jsm/libs/draco/' );
+ * loader.setDRACOLoader( dracoLoader );
+ *
+ * const gltf = await loader.loadAsync( 'models/gltf/duck/duck.gltf' );
+ * scene.add( gltf.scene );
+ * ```
+ *
+ * @augments Loader
+ * @three_import import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+ */
+class GLTFLoader extends Loader {
+
+ /**
+ * Constructs a new glTF loader.
+ *
+ * @param {LoadingManager} [manager] - The loading manager.
+ */
+ constructor( manager ) {
+
+ super( manager );
+
+ this.dracoLoader = null;
+ this.ktx2Loader = null;
+ this.meshoptDecoder = null;
+
+ this.pluginCallbacks = [];
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsClearcoatExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsDispersionExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFTextureBasisUExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFTextureWebPExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFTextureAVIFExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsSheenExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsTransmissionExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsVolumeExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsIorExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsEmissiveStrengthExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsSpecularExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsIridescenceExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsAnisotropyExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMaterialsBumpExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFLightsExtension( parser );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMeshoptCompression( parser, EXTENSIONS.EXT_MESHOPT_COMPRESSION );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMeshoptCompression( parser, EXTENSIONS.KHR_MESHOPT_COMPRESSION );
+
+ } );
+
+ this.register( function ( parser ) {
+
+ return new GLTFMeshGpuInstancing( parser );
+
+ } );
+
+ }
+
+ /**
+ * Starts loading from the given URL and passes the loaded glTF asset
+ * to the `onLoad()` callback.
+ *
+ * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
+ * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
+ * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
+ * @param {onErrorCallback} onError - Executed when errors occur.
+ */
+ load( url, onLoad, onProgress, onError ) {
+
+ const scope = this;
+
+ let resourcePath;
+
+ if ( this.resourcePath !== '' ) {
+
+ resourcePath = this.resourcePath;
+
+ } else if ( this.path !== '' ) {
+
+ // If a base path is set, resources will be relative paths from that plus the relative path of the gltf file
+ // Example path = 'https://my-cnd-server.com/', url = 'assets/models/model.gltf'
+ // resourcePath = 'https://my-cnd-server.com/assets/models/'
+ // referenced resource 'model.bin' will be loaded from 'https://my-cnd-server.com/assets/models/model.bin'
+ // referenced resource '../textures/texture.png' will be loaded from 'https://my-cnd-server.com/assets/textures/texture.png'
+ const relativeUrl = LoaderUtils.extractUrlBase( url );
+ resourcePath = LoaderUtils.resolveURL( relativeUrl, this.path );
+
+ } else {
+
+ resourcePath = LoaderUtils.extractUrlBase( url );
+
+ }
+
+ // Tells the LoadingManager to track an extra item, which resolves after
+ // the model is fully loaded. This means the count of items loaded will
+ // be incorrect, but ensures manager.onLoad() does not fire early.
+ this.manager.itemStart( url );
+
+ const _onError = function ( e ) {
+
+ if ( onError ) {
+
+ onError( e );
+
+ } else {
+
+ console.error( e );
+
+ }
+
+ scope.manager.itemError( url );
+ scope.manager.itemEnd( url );
+
+ };
+
+ const loader = new FileLoader( this.manager );
+
+ loader.setPath( this.path );
+ loader.setResponseType( 'arraybuffer' );
+ loader.setRequestHeader( this.requestHeader );
+ loader.setWithCredentials( this.withCredentials );
+
+ loader.load( url, function ( data ) {
+
+ try {
+
+ scope.parse( data, resourcePath, function ( gltf ) {
+
+ onLoad( gltf );
+
+ scope.manager.itemEnd( url );
+
+ }, _onError );
+
+ } catch ( e ) {
+
+ _onError( e );
+
+ }
+
+ }, onProgress, _onError );
+
+ }
+
+ /**
+ * Sets the given Draco loader to this loader. Required for decoding assets
+ * compressed with the `KHR_draco_mesh_compression` extension.
+ *
+ * @param {DRACOLoader} dracoLoader - The Draco loader to set.
+ * @return {GLTFLoader} A reference to this loader.
+ */
+ setDRACOLoader( dracoLoader ) {
+
+ this.dracoLoader = dracoLoader;
+ return this;
+
+ }
+
+ /**
+ * Sets the given KTX2 loader to this loader. Required for loading KTX2
+ * compressed textures.
+ *
+ * @param {KTX2Loader} ktx2Loader - The KTX2 loader to set.
+ * @return {GLTFLoader} A reference to this loader.
+ */
+ setKTX2Loader( ktx2Loader ) {
+
+ this.ktx2Loader = ktx2Loader;
+ return this;
+
+ }
+
+ /**
+ * Sets the given meshopt decoder. Required for decoding assets
+ * compressed with the `EXT_meshopt_compression` extension.
+ *
+ * @param {Object} meshoptDecoder - The meshopt decoder to set.
+ * @return {GLTFLoader} A reference to this loader.
+ */
+ setMeshoptDecoder( meshoptDecoder ) {
+
+ this.meshoptDecoder = meshoptDecoder;
+ return this;
+
+ }
+
+ /**
+ * Registers a plugin callback. This API is internally used to implement the various
+ * glTF extensions but can also used by third-party code to add additional logic
+ * to the loader.
+ *
+ * @param {function(parser:GLTFParser)} callback - The callback function to register.
+ * @return {GLTFLoader} A reference to this loader.
+ */
+ register( callback ) {
+
+ if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
+
+ this.pluginCallbacks.push( callback );
+
+ }
+
+ return this;
+
+ }
+
+ /**
+ * Unregisters a plugin callback.
+ *
+ * @param {Function} callback - The callback function to unregister.
+ * @return {GLTFLoader} A reference to this loader.
+ */
+ unregister( callback ) {
+
+ if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
+
+ this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
+
+ }
+
+ return this;
+
+ }
+
+ /**
+ * Parses the given glTF data and returns the resulting group.
+ *
+ * @param {string|ArrayBuffer} data - The raw glTF data.
+ * @param {string} path - The URL base path.
+ * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
+ * @param {onErrorCallback} onError - Executed when errors occur.
+ */
+ parse( data, path, onLoad, onError ) {
+
+ let json;
+ const extensions = {};
+ const plugins = {};
+ const textDecoder = new TextDecoder();
+
+ if ( typeof data === 'string' ) {
+
+ json = JSON.parse( data );
+
+ } else if ( data instanceof ArrayBuffer ) {
+
+ const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );
+
+ if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
+
+ try {
+
+ extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
+
+ } catch ( error ) {
+
+ if ( onError ) onError( error );
+ return;
+
+ }
+
+ json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );
+
+ } else {
+
+ json = JSON.parse( textDecoder.decode( data ) );
+
+ }
+
+ } else {
+
+ json = data;
+
+ }
+
+ if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
+
+ if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
+ return;
+
+ }
+
+ const parser = new GLTFParser( json, {
+
+ path: path || this.resourcePath || '',
+ crossOrigin: this.crossOrigin,
+ requestHeader: this.requestHeader,
+ manager: this.manager,
+ ktx2Loader: this.ktx2Loader,
+ meshoptDecoder: this.meshoptDecoder
+
+ } );
+
+ parser.fileLoader.setRequestHeader( this.requestHeader );
+
+ for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
+
+ const plugin = this.pluginCallbacks[ i ]( parser );
+
+ if ( ! plugin.name ) console.error( 'THREE.GLTFLoader: Invalid plugin found: missing name' );
+
+ plugins[ plugin.name ] = plugin;
+
+ // Workaround to avoid determining as unknown extension
+ // in addUnknownExtensionsToUserData().
+ // Remove this workaround if we move all the existing
+ // extension handlers to plugin system
+ extensions[ plugin.name ] = true;
+
+ }
+
+ if ( json.extensionsUsed ) {
+
+ for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
+
+ const extensionName = json.extensionsUsed[ i ];
+ const extensionsRequired = json.extensionsRequired || [];
+
+ switch ( extensionName ) {
+
+ case EXTENSIONS.KHR_MATERIALS_UNLIT:
+ extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
+ break;
+
+ case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
+ extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
+ break;
+
+ case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
+ extensions[ extensionName ] = new GLTFTextureTransformExtension();
+ break;
+
+ case EXTENSIONS.KHR_MESH_QUANTIZATION:
+ extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
+ break;
+
+ default:
+
+ if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
+
+ console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
+
+ }
+
+ }
+
+ }
+
+ }
+
+ parser.setExtensions( extensions );
+ parser.setPlugins( plugins );
+ parser.parse( onLoad, onError );
+
+ }
+
+ /**
+ * Async version of {@link GLTFLoader#parse}.
+ *
+ * @async
+ * @param {string|ArrayBuffer} data - The raw glTF data.
+ * @param {string} path - The URL base path.
+ * @return {Promise} A Promise that resolves with the loaded glTF when the parsing has been finished.
+ */
+ parseAsync( data, path ) {
+
+ const scope = this;
+
+ return new Promise( function ( resolve, reject ) {
+
+ scope.parse( data, path, resolve, reject );
+
+ } );
+
+ }
+
+}
+
+/* GLTFREGISTRY */
+
+function GLTFRegistry() {
+
+ let objects = {};
+
+ return {
+
+ get: function ( key ) {
+
+ return objects[ key ];
+
+ },
+
+ add: function ( key, object ) {
+
+ objects[ key ] = object;
+
+ },
+
+ remove: function ( key ) {
+
+ delete objects[ key ];
+
+ },
+
+ removeAll: function () {
+
+ objects = {};
+
+ }
+
+ };
+
+}
+
+/*********************************/
+/********** EXTENSIONS ***********/
+/*********************************/
+
+function getMaterialExtension( parser, materialIndex, extensionName ) {
+
+ const materialDef = parser.json.materials[ materialIndex ];
+
+ if ( materialDef.extensions && materialDef.extensions[ extensionName ] ) {
+
+ return materialDef.extensions[ extensionName ];
+
+ }
+
+ return null;
+
+}
+
+const EXTENSIONS = {
+ KHR_BINARY_GLTF: 'KHR_binary_glTF',
+ KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
+ KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
+ KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
+ KHR_MATERIALS_DISPERSION: 'KHR_materials_dispersion',
+ KHR_MATERIALS_IOR: 'KHR_materials_ior',
+ KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
+ KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
+ KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
+ KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
+ KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy',
+ KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
+ KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
+ KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
+ KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
+ KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
+ KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
+ EXT_MATERIALS_BUMP: 'EXT_materials_bump',
+ EXT_TEXTURE_WEBP: 'EXT_texture_webp',
+ EXT_TEXTURE_AVIF: 'EXT_texture_avif',
+ EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
+ KHR_MESHOPT_COMPRESSION: 'KHR_meshopt_compression',
+ EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
+};
+
+/**
+ * Punctual Lights Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
+ *
+ * @private
+ */
+class GLTFLightsExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
+
+ // Object3D instance caches
+ this.cache = { refs: {}, uses: {} };
+
+ }
+
+ _markDefs() {
+
+ const parser = this.parser;
+ const nodeDefs = this.parser.json.nodes || [];
+
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
+
+ const nodeDef = nodeDefs[ nodeIndex ];
+
+ if ( nodeDef.extensions
+ && nodeDef.extensions[ this.name ]
+ && nodeDef.extensions[ this.name ].light !== undefined ) {
+
+ parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
+
+ }
+
+ }
+
+ }
+
+ _loadLight( lightIndex ) {
+
+ const parser = this.parser;
+ const cacheKey = 'light:' + lightIndex;
+ let dependency = parser.cache.get( cacheKey );
+
+ if ( dependency ) return dependency;
+
+ const json = parser.json;
+ const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
+ const lightDefs = extensions.lights || [];
+ const lightDef = lightDefs[ lightIndex ];
+ let lightNode;
+
+ const color = new Color( 0xffffff );
+
+ if ( lightDef.color !== undefined ) color.setRGB( lightDef.color[ 0 ], lightDef.color[ 1 ], lightDef.color[ 2 ], LinearSRGBColorSpace );
+
+ const range = lightDef.range !== undefined ? lightDef.range : 0;
+
+ switch ( lightDef.type ) {
+
+ case 'directional':
+ lightNode = new DirectionalLight( color );
+ lightNode.target.position.set( 0, 0, - 1 );
+ lightNode.add( lightNode.target );
+ break;
+
+ case 'point':
+ lightNode = new PointLight( color );
+ lightNode.distance = range;
+ break;
+
+ case 'spot':
+ lightNode = new SpotLight( color );
+ lightNode.distance = range;
+ // Handle spotlight properties.
+ lightDef.spot = lightDef.spot || {};
+ lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
+ lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
+ lightNode.angle = lightDef.spot.outerConeAngle;
+ lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
+ lightNode.target.position.set( 0, 0, - 1 );
+ lightNode.add( lightNode.target );
+ break;
+
+ default:
+ throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
+
+ }
+
+ // Some lights (e.g. spot) default to a position other than the origin. Reset the position
+ // here, because node-level parsing will only override position if explicitly specified.
+ lightNode.position.set( 0, 0, 0 );
+
+ assignExtrasToUserData( lightNode, lightDef );
+
+ if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
+
+ lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
+
+ dependency = Promise.resolve( lightNode );
+
+ parser.cache.add( cacheKey, dependency );
+
+ return dependency;
+
+ }
+
+ getDependency( type, index ) {
+
+ if ( type !== 'light' ) return;
+
+ return this._loadLight( index );
+
+ }
+
+ createNodeAttachment( nodeIndex ) {
+
+ const self = this;
+ const parser = this.parser;
+ const json = parser.json;
+ const nodeDef = json.nodes[ nodeIndex ];
+ const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
+ const lightIndex = lightDef.light;
+
+ if ( lightIndex === undefined ) return null;
+
+ return this._loadLight( lightIndex ).then( function ( light ) {
+
+ return parser._getNodeRef( self.cache, lightIndex, light );
+
+ } );
+
+ }
+
+}
+
+/**
+ * Unlit Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
+ *
+ * @private
+ */
+class GLTFMaterialsUnlitExtension {
+
+ constructor() {
+
+ this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
+
+ }
+
+ getMaterialType() {
+
+ return MeshBasicMaterial;
+
+ }
+
+ extendParams( materialParams, materialDef, parser ) {
+
+ const pending = [];
+
+ materialParams.color = new Color( 1.0, 1.0, 1.0 );
+ materialParams.opacity = 1.0;
+
+ const metallicRoughness = materialDef.pbrMetallicRoughness;
+
+ if ( metallicRoughness ) {
+
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
+
+ const array = metallicRoughness.baseColorFactor;
+
+ materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace );
+ materialParams.opacity = array[ 3 ];
+
+ }
+
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
+
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) );
+
+ }
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Materials Emissive Strength Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
+ *
+ * @private
+ */
+class GLTFMaterialsEmissiveStrengthExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ if ( extension.emissiveStrength !== undefined ) {
+
+ materialParams.emissiveIntensity = extension.emissiveStrength;
+
+ }
+
+ return Promise.resolve();
+
+ }
+
+}
+
+/**
+ * Clearcoat Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
+ *
+ * @private
+ */
+class GLTFMaterialsClearcoatExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ if ( extension.clearcoatFactor !== undefined ) {
+
+ materialParams.clearcoat = extension.clearcoatFactor;
+
+ }
+
+ if ( extension.clearcoatTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
+
+ }
+
+ if ( extension.clearcoatRoughnessFactor !== undefined ) {
+
+ materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
+
+ }
+
+ if ( extension.clearcoatRoughnessTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
+
+ }
+
+ if ( extension.clearcoatNormalTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
+
+ if ( extension.clearcoatNormalTexture.scale !== undefined ) {
+
+ const scale = extension.clearcoatNormalTexture.scale;
+
+ materialParams.clearcoatNormalScale = new Vector2( scale, scale );
+
+ }
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Materials dispersion Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_dispersion
+ *
+ * @private
+ */
+class GLTFMaterialsDispersionExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0;
+
+ return Promise.resolve();
+
+ }
+
+}
+
+/**
+ * Iridescence Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
+ *
+ * @private
+ */
+class GLTFMaterialsIridescenceExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ if ( extension.iridescenceFactor !== undefined ) {
+
+ materialParams.iridescence = extension.iridescenceFactor;
+
+ }
+
+ if ( extension.iridescenceTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );
+
+ }
+
+ if ( extension.iridescenceIor !== undefined ) {
+
+ materialParams.iridescenceIOR = extension.iridescenceIor;
+
+ }
+
+ if ( materialParams.iridescenceThicknessRange === undefined ) {
+
+ materialParams.iridescenceThicknessRange = [ 100, 400 ];
+
+ }
+
+ if ( extension.iridescenceThicknessMinimum !== undefined ) {
+
+ materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;
+
+ }
+
+ if ( extension.iridescenceThicknessMaximum !== undefined ) {
+
+ materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;
+
+ }
+
+ if ( extension.iridescenceThicknessTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Sheen Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
+ *
+ * @private
+ */
+class GLTFMaterialsSheenExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ materialParams.sheenColor = new Color( 0, 0, 0 );
+ materialParams.sheenRoughness = 0;
+ materialParams.sheen = 1;
+
+ if ( extension.sheenColorFactor !== undefined ) {
+
+ const colorFactor = extension.sheenColorFactor;
+ materialParams.sheenColor.setRGB( colorFactor[ 0 ], colorFactor[ 1 ], colorFactor[ 2 ], LinearSRGBColorSpace );
+
+ }
+
+ if ( extension.sheenRoughnessFactor !== undefined ) {
+
+ materialParams.sheenRoughness = extension.sheenRoughnessFactor;
+
+ }
+
+ if ( extension.sheenColorTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, SRGBColorSpace ) );
+
+ }
+
+ if ( extension.sheenRoughnessTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Transmission Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
+ * Draft: https://github.com/KhronosGroup/glTF/pull/1698
+ *
+ * @private
+ */
+class GLTFMaterialsTransmissionExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ if ( extension.transmissionFactor !== undefined ) {
+
+ materialParams.transmission = extension.transmissionFactor;
+
+ }
+
+ if ( extension.transmissionTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Materials Volume Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
+ *
+ * @private
+ */
+class GLTFMaterialsVolumeExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
+
+ if ( extension.thicknessTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
+
+ }
+
+ materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
+
+ const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
+ materialParams.attenuationColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace );
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Materials ior Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
+ *
+ * @private
+ */
+class GLTFMaterialsIorExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_IOR;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
+
+ if ( materialParams.ior === 0 ) materialParams.ior = 1000; // see #26167
+
+ return Promise.resolve();
+
+ }
+
+}
+
+/**
+ * Materials specular Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
+ *
+ * @private
+ */
+class GLTFMaterialsSpecularExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
+
+ if ( extension.specularTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
+
+ }
+
+ const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
+ materialParams.specularColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace );
+
+ if ( extension.specularColorTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, SRGBColorSpace ) );
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+
+/**
+ * Materials bump Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
+ *
+ * @private
+ */
+class GLTFMaterialsBumpExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.EXT_MATERIALS_BUMP;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1.0;
+
+ if ( extension.bumpTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'bumpMap', extension.bumpTexture ) );
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * Materials anisotropy Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_anisotropy
+ *
+ * @private
+ */
+class GLTFMaterialsAnisotropyExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;
+
+ }
+
+ getMaterialType( materialIndex ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ return extension !== null ? MeshPhysicalMaterial : null;
+
+ }
+
+ extendMaterialParams( materialIndex, materialParams ) {
+
+ const extension = getMaterialExtension( this.parser, materialIndex, this.name );
+
+ if ( extension === null ) return Promise.resolve();
+
+ const pending = [];
+
+ if ( extension.anisotropyStrength !== undefined ) {
+
+ materialParams.anisotropy = extension.anisotropyStrength;
+
+ }
+
+ if ( extension.anisotropyRotation !== undefined ) {
+
+ materialParams.anisotropyRotation = extension.anisotropyRotation;
+
+ }
+
+ if ( extension.anisotropyTexture !== undefined ) {
+
+ pending.push( this.parser.assignTexture( materialParams, 'anisotropyMap', extension.anisotropyTexture ) );
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+}
+
+/**
+ * BasisU Texture Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
+ *
+ * @private
+ */
+class GLTFTextureBasisUExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
+
+ }
+
+ loadTexture( textureIndex ) {
+
+ const parser = this.parser;
+ const json = parser.json;
+
+ const textureDef = json.textures[ textureIndex ];
+
+ if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
+
+ return null;
+
+ }
+
+ const extension = textureDef.extensions[ this.name ];
+ const loader = parser.options.ktx2Loader;
+
+ if ( ! loader ) {
+
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
+
+ throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
+
+ } else {
+
+ // Assumes that the extension is optional and that a fallback texture is present
+ return null;
+
+ }
+
+ }
+
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
+
+ }
+
+}
+
+/**
+ * WebP Texture Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
+ *
+ * @private
+ */
+class GLTFTextureWebPExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
+
+ }
+
+ loadTexture( textureIndex ) {
+
+ const name = this.name;
+ const parser = this.parser;
+ const json = parser.json;
+
+ const textureDef = json.textures[ textureIndex ];
+
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
+
+ return null;
+
+ }
+
+ const extension = textureDef.extensions[ name ];
+ const source = json.images[ extension.source ];
+
+ let loader = parser.textureLoader;
+ if ( source.uri ) {
+
+ const handler = parser.options.manager.getHandler( source.uri );
+ if ( handler !== null ) loader = handler;
+
+ }
+
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
+
+ }
+
+}
+
+/**
+ * AVIF Texture Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif
+ *
+ * @private
+ */
+class GLTFTextureAVIFExtension {
+
+ constructor( parser ) {
+
+ this.parser = parser;
+ this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
+
+ }
+
+ loadTexture( textureIndex ) {
+
+ const name = this.name;
+ const parser = this.parser;
+ const json = parser.json;
+
+ const textureDef = json.textures[ textureIndex ];
+
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
+
+ return null;
+
+ }
+
+ const extension = textureDef.extensions[ name ];
+ const source = json.images[ extension.source ];
+
+ let loader = parser.textureLoader;
+ if ( source.uri ) {
+
+ const handler = parser.options.manager.getHandler( source.uri );
+ if ( handler !== null ) loader = handler;
+
+ }
+
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
+
+ }
+
+}
+
+/**
+ * meshopt BufferView Compression Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
+ *
+ * @private
+ */
+class GLTFMeshoptCompression {
+
+ constructor( parser, name ) {
+
+ this.name = name;
+ this.parser = parser;
+
+ }
+
+ loadBufferView( index ) {
+
+ const json = this.parser.json;
+ const bufferView = json.bufferViews[ index ];
+
+ if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
+
+ const extensionDef = bufferView.extensions[ this.name ];
+
+ const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
+ const decoder = this.parser.options.meshoptDecoder;
+
+ if ( ! decoder || ! decoder.supported ) {
+
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
+
+ throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
+
+ } else {
+
+ // Assumes that the extension is optional and that fallback buffer data is present
+ return null;
+
+ }
+
+ }
+
+ return buffer.then( function ( res ) {
+
+ const byteOffset = extensionDef.byteOffset || 0;
+ const byteLength = extensionDef.byteLength || 0;
+
+ const count = extensionDef.count;
+ const stride = extensionDef.byteStride;
+
+ const source = new Uint8Array( res, byteOffset, byteLength );
+
+ if ( decoder.decodeGltfBufferAsync ) {
+
+ return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {
+
+ return res.buffer;
+
+ } );
+
+ } else {
+
+ // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
+ return decoder.ready.then( function () {
+
+ const result = new ArrayBuffer( count * stride );
+ decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
+ return result;
+
+ } );
+
+ }
+
+ } );
+
+ } else {
+
+ return null;
+
+ }
+
+ }
+
+}
+
+/**
+ * GPU Instancing Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
+ *
+ * @private
+ */
+class GLTFMeshGpuInstancing {
+
+ constructor( parser ) {
+
+ this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
+ this.parser = parser;
+
+ }
+
+ createNodeMesh( nodeIndex ) {
+
+ const json = this.parser.json;
+ const nodeDef = json.nodes[ nodeIndex ];
+
+ if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||
+ nodeDef.mesh === undefined ) {
+
+ return null;
+
+ }
+
+ const meshDef = json.meshes[ nodeDef.mesh ];
+
+ // No Points or Lines + Instancing support yet
+
+ for ( const primitive of meshDef.primitives ) {
+
+ if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
+ primitive.mode !== undefined ) {
+
+ return null;
+
+ }
+
+ }
+
+ const extensionDef = nodeDef.extensions[ this.name ];
+ const attributesDef = extensionDef.attributes;
+
+ // @TODO: Can we support InstancedMesh + SkinnedMesh?
+
+ const pending = [];
+ const attributes = {};
+
+ for ( const key in attributesDef ) {
+
+ pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {
+
+ attributes[ key ] = accessor;
+ return attributes[ key ];
+
+ } ) );
+
+ }
+
+ if ( pending.length < 1 ) {
+
+ return null;
+
+ }
+
+ pending.push( this.parser.createNodeMesh( nodeIndex ) );
+
+ return Promise.all( pending ).then( results => {
+
+ const nodeObject = results.pop();
+ const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];
+ const count = results[ 0 ].count; // All attribute counts should be same
+ const instancedMeshes = [];
+
+ for ( const mesh of meshes ) {
+
+ // Temporal variables
+ const m = new Matrix4();
+ const p = new Vector3();
+ const q = new Quaternion();
+ const s = new Vector3( 1, 1, 1 );
+
+ const instancedMesh = new InstancedMesh( mesh.geometry, mesh.material, count );
+
+ for ( let i = 0; i < count; i ++ ) {
+
+ if ( attributes.TRANSLATION ) {
+
+ p.fromBufferAttribute( attributes.TRANSLATION, i );
+
+ }
+
+ if ( attributes.ROTATION ) {
+
+ q.fromBufferAttribute( attributes.ROTATION, i );
+
+ }
+
+ if ( attributes.SCALE ) {
+
+ s.fromBufferAttribute( attributes.SCALE, i );
+
+ }
+
+ instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );
+
+ }
+
+ // Add instance attributes to the geometry, excluding TRS.
+ for ( const attributeName in attributes ) {
+
+ if ( attributeName === '_COLOR_0' ) {
+
+ const attr = attributes[ attributeName ];
+ instancedMesh.instanceColor = new InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized );
+
+ } else if ( attributeName !== 'TRANSLATION' &&
+ attributeName !== 'ROTATION' &&
+ attributeName !== 'SCALE' ) {
+
+ mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );
+
+ }
+
+ }
+
+ // Just in case
+ Object3D.prototype.copy.call( instancedMesh, mesh );
+
+ this.parser.assignFinalMaterial( instancedMesh );
+
+ instancedMeshes.push( instancedMesh );
+
+ }
+
+ if ( nodeObject.isGroup ) {
+
+ nodeObject.clear();
+
+ nodeObject.add( ... instancedMeshes );
+
+ return nodeObject;
+
+ }
+
+ return instancedMeshes[ 0 ];
+
+ } );
+
+ }
+
+}
+
+/* BINARY EXTENSION */
+const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
+const BINARY_EXTENSION_HEADER_LENGTH = 12;
+const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
+
+class GLTFBinaryExtension {
+
+ constructor( data ) {
+
+ this.name = EXTENSIONS.KHR_BINARY_GLTF;
+ this.content = null;
+ this.body = null;
+
+ const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
+ const textDecoder = new TextDecoder();
+
+ this.header = {
+ magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),
+ version: headerView.getUint32( 4, true ),
+ length: headerView.getUint32( 8, true )
+ };
+
+ if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
+
+ throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
+
+ } else if ( this.header.version < 2.0 ) {
+
+ throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
+
+ }
+
+ const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
+ const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
+ let chunkIndex = 0;
+
+ while ( chunkIndex < chunkContentsLength ) {
+
+ const chunkLength = chunkView.getUint32( chunkIndex, true );
+ chunkIndex += 4;
+
+ const chunkType = chunkView.getUint32( chunkIndex, true );
+ chunkIndex += 4;
+
+ if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
+
+ const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
+ this.content = textDecoder.decode( contentArray );
+
+ } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
+
+ const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
+ this.body = data.slice( byteOffset, byteOffset + chunkLength );
+
+ }
+
+ // Clients must ignore chunks with unknown types.
+
+ chunkIndex += chunkLength;
+
+ }
+
+ if ( this.content === null ) {
+
+ throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
+
+ }
+
+ }
+
+}
+
+/**
+ * DRACO Mesh Compression Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
+ *
+ * @private
+ */
+class GLTFDracoMeshCompressionExtension {
+
+ constructor( json, dracoLoader ) {
+
+ if ( ! dracoLoader ) {
+
+ throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
+
+ }
+
+ this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
+ this.json = json;
+ this.dracoLoader = dracoLoader;
+ this.dracoLoader.preload();
+
+ }
+
+ decodePrimitive( primitive, parser ) {
+
+ const json = this.json;
+ const dracoLoader = this.dracoLoader;
+ const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
+ const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
+ const threeAttributeMap = {};
+ const attributeNormalizedMap = {};
+ const attributeTypeMap = {};
+
+ for ( const attributeName in gltfAttributeMap ) {
+
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
+
+ threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
+
+ }
+
+ for ( const attributeName in primitive.attributes ) {
+
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
+
+ if ( gltfAttributeMap[ attributeName ] !== undefined ) {
+
+ const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
+ const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
+
+ attributeTypeMap[ threeAttributeName ] = componentType.name;
+ attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
+
+ }
+
+ }
+
+ return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
+
+ return new Promise( function ( resolve, reject ) {
+
+ dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
+
+ for ( const attributeName in geometry.attributes ) {
+
+ const attribute = geometry.attributes[ attributeName ];
+ const normalized = attributeNormalizedMap[ attributeName ];
+
+ if ( normalized !== undefined ) attribute.normalized = normalized;
+
+ }
+
+ resolve( geometry );
+
+ }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject );
+
+ } );
+
+ } );
+
+ }
+
+}
+
+/**
+ * Texture Transform Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
+ *
+ * @private
+ */
+class GLTFTextureTransformExtension {
+
+ constructor() {
+
+ this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
+
+ }
+
+ extendTexture( texture, transform ) {
+
+ if ( ( transform.texCoord === undefined || transform.texCoord === texture.channel )
+ && transform.offset === undefined
+ && transform.rotation === undefined
+ && transform.scale === undefined ) {
+
+ // See https://github.com/mrdoob/three.js/issues/21819.
+ return texture;
+
+ }
+
+ texture = texture.clone();
+
+ if ( transform.texCoord !== undefined ) {
+
+ texture.channel = transform.texCoord;
+
+ }
+
+ if ( transform.offset !== undefined ) {
+
+ texture.offset.fromArray( transform.offset );
+
+ }
+
+ if ( transform.rotation !== undefined ) {
+
+ texture.rotation = transform.rotation;
+
+ }
+
+ if ( transform.scale !== undefined ) {
+
+ texture.repeat.fromArray( transform.scale );
+
+ }
+
+ texture.needsUpdate = true;
+
+ return texture;
+
+ }
+
+}
+
+/**
+ * Mesh Quantization Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
+ *
+ * @private
+ */
+class GLTFMeshQuantizationExtension {
+
+ constructor() {
+
+ this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
+
+ }
+
+}
+
+/*********************************/
+/********** INTERPOLATION ********/
+/*********************************/
+
+// Spline Interpolation
+// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
+class GLTFCubicSplineInterpolant extends Interpolant {
+
+ constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
+
+ super( parameterPositions, sampleValues, sampleSize, resultBuffer );
+
+ }
+
+ copySampleValue_( index ) {
+
+ // Copies a sample value to the result buffer. See description of glTF
+ // CUBICSPLINE values layout in interpolate_() function below.
+
+ const result = this.resultBuffer,
+ values = this.sampleValues,
+ valueSize = this.valueSize,
+ offset = index * valueSize * 3 + valueSize;
+
+ for ( let i = 0; i !== valueSize; i ++ ) {
+
+ result[ i ] = values[ offset + i ];
+
+ }
+
+ return result;
+
+ }
+
+ interpolate_( i1, t0, t, t1 ) {
+
+ const result = this.resultBuffer;
+ const values = this.sampleValues;
+ const stride = this.valueSize;
+
+ const stride2 = stride * 2;
+ const stride3 = stride * 3;
+
+ const td = t1 - t0;
+
+ const p = ( t - t0 ) / td;
+ const pp = p * p;
+ const ppp = pp * p;
+
+ const offset1 = i1 * stride3;
+ const offset0 = offset1 - stride3;
+
+ const s2 = - 2 * ppp + 3 * pp;
+ const s3 = ppp - pp;
+ const s0 = 1 - s2;
+ const s1 = s3 - pp + p;
+
+ // Layout of keyframe output values for CUBICSPLINE animations:
+ // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
+ for ( let i = 0; i !== stride; i ++ ) {
+
+ const p0 = values[ offset0 + i + stride ]; // splineVertex_k
+ const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
+ const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
+ const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
+
+ result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
+
+ }
+
+ return result;
+
+ }
+
+}
+
+const _quaternion = new Quaternion();
+
+class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
+
+ interpolate_( i1, t0, t, t1 ) {
+
+ const result = super.interpolate_( i1, t0, t, t1 );
+
+ _quaternion.fromArray( result ).normalize().toArray( result );
+
+ return result;
+
+ }
+
+}
+
+
+/*********************************/
+/********** INTERNALS ************/
+/*********************************/
+
+/* CONSTANTS */
+
+const WEBGL_CONSTANTS = {
+ FLOAT: 5126,
+ //FLOAT_MAT2: 35674,
+ FLOAT_MAT3: 35675,
+ FLOAT_MAT4: 35676,
+ FLOAT_VEC2: 35664,
+ FLOAT_VEC3: 35665,
+ FLOAT_VEC4: 35666,
+ LINEAR: 9729,
+ REPEAT: 10497,
+ SAMPLER_2D: 35678,
+ POINTS: 0,
+ LINES: 1,
+ LINE_LOOP: 2,
+ LINE_STRIP: 3,
+ TRIANGLES: 4,
+ TRIANGLE_STRIP: 5,
+ TRIANGLE_FAN: 6,
+ UNSIGNED_BYTE: 5121,
+ UNSIGNED_SHORT: 5123
+};
+
+const WEBGL_COMPONENT_TYPES = {
+ 5120: Int8Array,
+ 5121: Uint8Array,
+ 5122: Int16Array,
+ 5123: Uint16Array,
+ 5125: Uint32Array,
+ 5126: Float32Array
+};
+
+const WEBGL_FILTERS = {
+ 9728: NearestFilter,
+ 9729: LinearFilter,
+ 9984: NearestMipmapNearestFilter,
+ 9985: LinearMipmapNearestFilter,
+ 9986: NearestMipmapLinearFilter,
+ 9987: LinearMipmapLinearFilter
+};
+
+const WEBGL_WRAPPINGS = {
+ 33071: ClampToEdgeWrapping,
+ 33648: MirroredRepeatWrapping,
+ 10497: RepeatWrapping
+};
+
+const WEBGL_TYPE_SIZES = {
+ 'SCALAR': 1,
+ 'VEC2': 2,
+ 'VEC3': 3,
+ 'VEC4': 4,
+ 'MAT2': 4,
+ 'MAT3': 9,
+ 'MAT4': 16
+};
+
+const ATTRIBUTES = {
+ POSITION: 'position',
+ NORMAL: 'normal',
+ TANGENT: 'tangent',
+ TEXCOORD_0: 'uv',
+ TEXCOORD_1: 'uv1',
+ TEXCOORD_2: 'uv2',
+ TEXCOORD_3: 'uv3',
+ COLOR_0: 'color',
+ WEIGHTS_0: 'skinWeight',
+ JOINTS_0: 'skinIndex',
+};
+
+const PATH_PROPERTIES = {
+ scale: 'scale',
+ translation: 'position',
+ rotation: 'quaternion',
+ weights: 'morphTargetInfluences'
+};
+
+const INTERPOLATION = {
+ CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
+ // keyframe track will be initialized with a default interpolation type, then modified.
+ LINEAR: InterpolateLinear,
+ STEP: InterpolateDiscrete
+};
+
+const ALPHA_MODES = {
+ OPAQUE: 'OPAQUE',
+ MASK: 'MASK',
+ BLEND: 'BLEND'
+};
+
+/**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
+ *
+ * @private
+ * @param {Object} cache
+ * @return {Material}
+ */
+function createDefaultMaterial( cache ) {
+
+ if ( cache[ 'DefaultMaterial' ] === undefined ) {
+
+ cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {
+ color: 0xFFFFFF,
+ emissive: 0x000000,
+ metalness: 1,
+ roughness: 1,
+ transparent: false,
+ depthTest: true,
+ side: FrontSide
+ } );
+
+ }
+
+ return cache[ 'DefaultMaterial' ];
+
+}
+
+function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
+
+ // Add unknown glTF extensions to an object's userData.
+
+ for ( const name in objectDef.extensions ) {
+
+ if ( knownExtensions[ name ] === undefined ) {
+
+ object.userData.gltfExtensions = object.userData.gltfExtensions || {};
+ object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
+
+ }
+
+ }
+
+}
+
+/**
+ *
+ * @private
+ * @param {Object3D|Material|BufferGeometry|Object|AnimationClip} object
+ * @param {GLTF.definition} gltfDef
+ */
+function assignExtrasToUserData( object, gltfDef ) {
+
+ if ( gltfDef.extras !== undefined ) {
+
+ if ( typeof gltfDef.extras === 'object' ) {
+
+ Object.assign( object.userData, gltfDef.extras );
+
+ } else {
+
+ console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
+
+ }
+
+ }
+
+}
+
+/**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
+ *
+ * @private
+ * @param {BufferGeometry} geometry
+ * @param {Array} targets
+ * @param {GLTFParser} parser
+ * @return {Promise}
+ */
+function addMorphTargets( geometry, targets, parser ) {
+
+ let hasMorphPosition = false;
+ let hasMorphNormal = false;
+ let hasMorphColor = false;
+
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
+
+ const target = targets[ i ];
+
+ if ( target.POSITION !== undefined ) hasMorphPosition = true;
+ if ( target.NORMAL !== undefined ) hasMorphNormal = true;
+ if ( target.COLOR_0 !== undefined ) hasMorphColor = true;
+
+ if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
+
+ }
+
+ if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
+
+ const pendingPositionAccessors = [];
+ const pendingNormalAccessors = [];
+ const pendingColorAccessors = [];
+
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
+
+ const target = targets[ i ];
+
+ if ( hasMorphPosition ) {
+
+ const pendingAccessor = target.POSITION !== undefined
+ ? parser.getDependency( 'accessor', target.POSITION )
+ : geometry.attributes.position;
+
+ pendingPositionAccessors.push( pendingAccessor );
+
+ }
+
+ if ( hasMorphNormal ) {
+
+ const pendingAccessor = target.NORMAL !== undefined
+ ? parser.getDependency( 'accessor', target.NORMAL )
+ : geometry.attributes.normal;
+
+ pendingNormalAccessors.push( pendingAccessor );
+
+ }
+
+ if ( hasMorphColor ) {
+
+ const pendingAccessor = target.COLOR_0 !== undefined
+ ? parser.getDependency( 'accessor', target.COLOR_0 )
+ : geometry.attributes.color;
+
+ pendingColorAccessors.push( pendingAccessor );
+
+ }
+
+ }
+
+ return Promise.all( [
+ Promise.all( pendingPositionAccessors ),
+ Promise.all( pendingNormalAccessors ),
+ Promise.all( pendingColorAccessors )
+ ] ).then( function ( accessors ) {
+
+ const morphPositions = accessors[ 0 ];
+ const morphNormals = accessors[ 1 ];
+ const morphColors = accessors[ 2 ];
+
+ if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
+ if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
+ if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
+ geometry.morphTargetsRelative = true;
+
+ return geometry;
+
+ } );
+
+}
+
+/**
+ *
+ * @private
+ * @param {Mesh} mesh
+ * @param {GLTF.Mesh} meshDef
+ */
+function updateMorphTargets( mesh, meshDef ) {
+
+ mesh.updateMorphTargets();
+
+ if ( meshDef.weights !== undefined ) {
+
+ for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
+
+ mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
+
+ }
+
+ }
+
+ // .extras has user-defined data, so check that .extras.targetNames is an array.
+ if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
+
+ const targetNames = meshDef.extras.targetNames;
+
+ if ( mesh.morphTargetInfluences.length === targetNames.length ) {
+
+ mesh.morphTargetDictionary = {};
+
+ for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
+
+ mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
+
+ }
+
+ } else {
+
+ console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
+
+ }
+
+ }
+
+}
+
+function createPrimitiveKey( primitiveDef ) {
+
+ let geometryKey;
+
+ const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
+
+ if ( dracoExtension ) {
+
+ geometryKey = 'draco:' + dracoExtension.bufferView
+ + ':' + dracoExtension.indices
+ + ':' + createAttributesKey( dracoExtension.attributes );
+
+ } else {
+
+ geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
+
+ }
+
+ if ( primitiveDef.targets !== undefined ) {
+
+ for ( let i = 0, il = primitiveDef.targets.length; i < il; i ++ ) {
+
+ geometryKey += ':' + createAttributesKey( primitiveDef.targets[ i ] );
+
+ }
+
+ }
+
+ return geometryKey;
+
+}
+
+function createAttributesKey( attributes ) {
+
+ let attributesKey = '';
+
+ const keys = Object.keys( attributes ).sort();
+
+ for ( let i = 0, il = keys.length; i < il; i ++ ) {
+
+ attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
+
+ }
+
+ return attributesKey;
+
+}
+
+function getNormalizedComponentScale( constructor ) {
+
+ // Reference:
+ // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
+
+ switch ( constructor ) {
+
+ case Int8Array:
+ return 1 / 127;
+
+ case Uint8Array:
+ return 1 / 255;
+
+ case Int16Array:
+ return 1 / 32767;
+
+ case Uint16Array:
+ return 1 / 65535;
+
+ default:
+ throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
+
+ }
+
+}
+
+function getImageURIMimeType( uri ) {
+
+ if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';
+ if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';
+ if ( uri.search( /\.ktx2($|\?)/i ) > 0 || uri.search( /^data\:image\/ktx2/ ) === 0 ) return 'image/ktx2';
+
+ return 'image/png';
+
+}
+
+const _identityMatrix = new Matrix4();
+
+/* GLTF PARSER */
+
+class GLTFParser {
+
+ constructor( json = {}, options = {} ) {
+
+ this.json = json;
+ this.extensions = {};
+ this.plugins = {};
+ this.options = options;
+
+ // loader object cache
+ this.cache = new GLTFRegistry();
+
+ // associations between Three.js objects and glTF elements
+ this.associations = new Map();
+
+ // BufferGeometry caching
+ this.primitiveCache = {};
+
+ // Node cache
+ this.nodeCache = {};
+
+ // Object3D instance caches
+ this.meshCache = { refs: {}, uses: {} };
+ this.cameraCache = { refs: {}, uses: {} };
+ this.lightCache = { refs: {}, uses: {} };
+
+ this.sourceCache = {};
+ this.textureCache = {};
+
+ // Track node names, to ensure no duplicates
+ this.nodeNamesUsed = {};
+
+ // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
+ // expensive work of uploading a texture to the GPU off the main thread.
+
+ let isSafari = false;
+ let safariVersion = - 1;
+ let isFirefox = false;
+ let firefoxVersion = - 1;
+
+ if ( typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined' ) {
+
+ const userAgent = navigator.userAgent;
+
+ isSafari = /^((?!chrome|android).)*safari/i.test( userAgent ) === true;
+ const safariMatch = userAgent.match( /Version\/(\d+)/ );
+ safariVersion = isSafari && safariMatch ? parseInt( safariMatch[ 1 ], 10 ) : - 1;
+
+ isFirefox = userAgent.indexOf( 'Firefox' ) > - 1;
+ firefoxVersion = isFirefox ? userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1;
+
+ }
+
+ if ( typeof createImageBitmap === 'undefined' || ( isSafari && safariVersion < 17 ) || ( isFirefox && firefoxVersion < 98 ) ) {
+
+ this.textureLoader = new TextureLoader( this.options.manager );
+
+ } else {
+
+ this.textureLoader = new ImageBitmapLoader( this.options.manager );
+
+ }
+
+ this.textureLoader.setCrossOrigin( this.options.crossOrigin );
+ this.textureLoader.setRequestHeader( this.options.requestHeader );
+
+ this.fileLoader = new FileLoader( this.options.manager );
+ this.fileLoader.setResponseType( 'arraybuffer' );
+
+ if ( this.options.crossOrigin === 'use-credentials' ) {
+
+ this.fileLoader.setWithCredentials( true );
+
+ }
+
+ }
+
+ setExtensions( extensions ) {
+
+ this.extensions = extensions;
+
+ }
+
+ setPlugins( plugins ) {
+
+ this.plugins = plugins;
+
+ }
+
+ parse( onLoad, onError ) {
+
+ const parser = this;
+ const json = this.json;
+ const extensions = this.extensions;
+
+ // Clear the loader cache
+ this.cache.removeAll();
+ this.nodeCache = {};
+
+ // Mark the special nodes/meshes in json for efficient parse
+ this._invokeAll( function ( ext ) {
+
+ return ext._markDefs && ext._markDefs();
+
+ } );
+
+ Promise.all( this._invokeAll( function ( ext ) {
+
+ return ext.beforeRoot && ext.beforeRoot();
+
+ } ) ).then( function () {
+
+ return Promise.all( [
+
+ parser.getDependencies( 'scene' ),
+ parser.getDependencies( 'animation' ),
+ parser.getDependencies( 'camera' ),
+
+ ] );
+
+ } ).then( function ( dependencies ) {
+
+ const result = {
+ scene: dependencies[ 0 ][ json.scene || 0 ],
+ scenes: dependencies[ 0 ],
+ animations: dependencies[ 1 ],
+ cameras: dependencies[ 2 ],
+ asset: json.asset,
+ parser: parser,
+ userData: {}
+ };
+
+ addUnknownExtensionsToUserData( extensions, result, json );
+
+ assignExtrasToUserData( result, json );
+
+ return Promise.all( parser._invokeAll( function ( ext ) {
+
+ return ext.afterRoot && ext.afterRoot( result );
+
+ } ) ).then( function () {
+
+ for ( const scene of result.scenes ) {
+
+ scene.updateMatrixWorld();
+
+ }
+
+ onLoad( result );
+
+ } );
+
+ } ).catch( onError );
+
+ }
+
+ /**
+ * Marks the special nodes/meshes in json for efficient parse.
+ *
+ * @private
+ */
+ _markDefs() {
+
+ const nodeDefs = this.json.nodes || [];
+ const skinDefs = this.json.skins || [];
+ const meshDefs = this.json.meshes || [];
+
+ // Nothing in the node definition indicates whether it is a Bone or an
+ // Object3D. Use the skins' joint references to mark bones.
+ for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
+
+ const joints = skinDefs[ skinIndex ].joints;
+
+ for ( let i = 0, il = joints.length; i < il; i ++ ) {
+
+ nodeDefs[ joints[ i ] ].isBone = true;
+
+ }
+
+ }
+
+ // Iterate over all nodes, marking references to shared resources,
+ // as well as skeleton joints.
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
+
+ const nodeDef = nodeDefs[ nodeIndex ];
+
+ if ( nodeDef.mesh !== undefined ) {
+
+ this._addNodeRef( this.meshCache, nodeDef.mesh );
+
+ // Nothing in the mesh definition indicates whether it is
+ // a SkinnedMesh or Mesh. Use the node's mesh reference
+ // to mark SkinnedMesh if node has skin.
+ if ( nodeDef.skin !== undefined ) {
+
+ meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
+
+ }
+
+ }
+
+ if ( nodeDef.camera !== undefined ) {
+
+ this._addNodeRef( this.cameraCache, nodeDef.camera );
+
+ }
+
+ }
+
+ }
+
+ /**
+ * Counts references to shared node / Object3D resources. These resources
+ * can be reused, or "instantiated", at multiple nodes in the scene
+ * hierarchy. Mesh, Camera, and Light instances are instantiated and must
+ * be marked. Non-scenegraph resources (like Materials, Geometries, and
+ * Textures) can be reused directly and are not marked here.
+ *
+ * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
+ *
+ * @private
+ * @param {Object} cache
+ * @param {Object3D} index
+ */
+ _addNodeRef( cache, index ) {
+
+ if ( index === undefined ) return;
+
+ if ( cache.refs[ index ] === undefined ) {
+
+ cache.refs[ index ] = cache.uses[ index ] = 0;
+
+ }
+
+ cache.refs[ index ] ++;
+
+ }
+
+ /**
+ * Returns a reference to a shared resource, cloning it if necessary.
+ *
+ * @private
+ * @param {Object} cache
+ * @param {number} index
+ * @param {Object} object
+ * @return {Object}
+ */
+ _getNodeRef( cache, index, object ) {
+
+ if ( cache.refs[ index ] <= 1 ) return object;
+
+ const ref = object.clone();
+
+ // Propagates mappings to the cloned object, prevents mappings on the
+ // original object from being lost.
+ const updateMappings = ( original, clone ) => {
+
+ const mappings = this.associations.get( original );
+ if ( mappings != null ) {
+
+ this.associations.set( clone, mappings );
+
+ }
+
+ for ( const [ i, child ] of original.children.entries() ) {
+
+ updateMappings( child, clone.children[ i ] );
+
+ }
+
+ };
+
+ updateMappings( object, ref );
+
+ ref.name += '_instance_' + ( cache.uses[ index ] ++ );
+
+ return ref;
+
+ }
+
+ _invokeOne( func ) {
+
+ const extensions = Object.values( this.plugins );
+ extensions.push( this );
+
+ for ( let i = 0; i < extensions.length; i ++ ) {
+
+ const result = func( extensions[ i ] );
+
+ if ( result ) return result;
+
+ }
+
+ return null;
+
+ }
+
+ _invokeAll( func ) {
+
+ const extensions = Object.values( this.plugins );
+ extensions.unshift( this );
+
+ const pending = [];
+
+ for ( let i = 0; i < extensions.length; i ++ ) {
+
+ const result = func( extensions[ i ] );
+
+ if ( result ) pending.push( result );
+
+ }
+
+ return pending;
+
+ }
+
+ /**
+ * Requests the specified dependency asynchronously, with caching.
+ *
+ * @private
+ * @param {string} type
+ * @param {number} index
+ * @return {Promise}
+ */
+ getDependency( type, index ) {
+
+ const cacheKey = type + ':' + index;
+ let dependency = this.cache.get( cacheKey );
+
+ if ( ! dependency ) {
+
+ switch ( type ) {
+
+ case 'scene':
+ dependency = this.loadScene( index );
+ break;
+
+ case 'node':
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext.loadNode && ext.loadNode( index );
+
+ } );
+ break;
+
+ case 'mesh':
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext.loadMesh && ext.loadMesh( index );
+
+ } );
+ break;
+
+ case 'accessor':
+ dependency = this.loadAccessor( index );
+ break;
+
+ case 'bufferView':
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext.loadBufferView && ext.loadBufferView( index );
+
+ } );
+ break;
+
+ case 'buffer':
+ dependency = this.loadBuffer( index );
+ break;
+
+ case 'material':
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext.loadMaterial && ext.loadMaterial( index );
+
+ } );
+ break;
+
+ case 'texture':
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext.loadTexture && ext.loadTexture( index );
+
+ } );
+ break;
+
+ case 'skin':
+ dependency = this.loadSkin( index );
+ break;
+
+ case 'animation':
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext.loadAnimation && ext.loadAnimation( index );
+
+ } );
+ break;
+
+ case 'camera':
+ dependency = this.loadCamera( index );
+ break;
+
+ default:
+ dependency = this._invokeOne( function ( ext ) {
+
+ return ext != this && ext.getDependency && ext.getDependency( type, index );
+
+ } );
+
+ if ( ! dependency ) {
+
+ throw new Error( 'Unknown type: ' + type );
+
+ }
+
+ break;
+
+ }
+
+ this.cache.add( cacheKey, dependency );
+
+ }
+
+ return dependency;
+
+ }
+
+ /**
+ * Requests all dependencies of the specified type asynchronously, with caching.
+ *
+ * @private
+ * @param {string} type
+ * @return {Promise>}
+ */
+ getDependencies( type ) {
+
+ let dependencies = this.cache.get( type );
+
+ if ( ! dependencies ) {
+
+ const parser = this;
+ const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
+
+ dependencies = Promise.all( defs.map( function ( def, index ) {
+
+ return parser.getDependency( type, index );
+
+ } ) );
+
+ this.cache.add( type, dependencies );
+
+ }
+
+ return dependencies;
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
+ *
+ * @private
+ * @param {number} bufferIndex
+ * @return {Promise}
+ */
+ loadBuffer( bufferIndex ) {
+
+ const bufferDef = this.json.buffers[ bufferIndex ];
+ const loader = this.fileLoader;
+
+ if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
+
+ throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
+
+ }
+
+ // If present, GLB container is required to be the first buffer.
+ if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
+
+ return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
+
+ }
+
+ const options = this.options;
+
+ return new Promise( function ( resolve, reject ) {
+
+ loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
+
+ reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
+
+ } );
+
+ } );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
+ *
+ * @private
+ * @param {number} bufferViewIndex
+ * @return {Promise}
+ */
+ loadBufferView( bufferViewIndex ) {
+
+ const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
+
+ return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
+
+ const byteLength = bufferViewDef.byteLength || 0;
+ const byteOffset = bufferViewDef.byteOffset || 0;
+ return buffer.slice( byteOffset, byteOffset + byteLength );
+
+ } );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
+ *
+ * @private
+ * @param {number} accessorIndex
+ * @return {Promise}
+ */
+ loadAccessor( accessorIndex ) {
+
+ const parser = this;
+ const json = this.json;
+
+ const accessorDef = this.json.accessors[ accessorIndex ];
+
+ if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
+
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
+ const normalized = accessorDef.normalized === true;
+
+ const array = new TypedArray( accessorDef.count * itemSize );
+ return Promise.resolve( new BufferAttribute( array, itemSize, normalized ) );
+
+ }
+
+ const pendingBufferViews = [];
+
+ if ( accessorDef.bufferView !== undefined ) {
+
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
+
+ } else {
+
+ pendingBufferViews.push( null );
+
+ }
+
+ if ( accessorDef.sparse !== undefined ) {
+
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
+
+ }
+
+ return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
+
+ const bufferView = bufferViews[ 0 ];
+
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
+
+ // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
+ const elementBytes = TypedArray.BYTES_PER_ELEMENT;
+ const itemBytes = elementBytes * itemSize;
+ const byteOffset = accessorDef.byteOffset || 0;
+ const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
+ const normalized = accessorDef.normalized === true;
+ let array, bufferAttribute;
+
+ // The buffer is not interleaved if the stride is the item size in bytes.
+ if ( byteStride && byteStride !== itemBytes ) {
+
+ // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
+ // This makes sure that IBA.count reflects accessor.count properly
+ const ibSlice = Math.floor( byteOffset / byteStride );
+ const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
+ let ib = parser.cache.get( ibCacheKey );
+
+ if ( ! ib ) {
+
+ array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
+
+ // Integer parameters to IB/IBA are in array elements, not bytes.
+ ib = new InterleavedBuffer( array, byteStride / elementBytes );
+
+ parser.cache.add( ibCacheKey, ib );
+
+ }
+
+ bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
+
+ } else {
+
+ if ( bufferView === null ) {
+
+ array = new TypedArray( accessorDef.count * itemSize );
+
+ } else {
+
+ array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
+
+ }
+
+ bufferAttribute = new BufferAttribute( array, itemSize, normalized );
+
+ }
+
+ // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
+ if ( accessorDef.sparse !== undefined ) {
+
+ const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
+ const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
+
+ const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
+ const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
+
+ const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
+ const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
+
+ if ( bufferView !== null ) {
+
+ // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
+ bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
+
+ }
+
+ // Ignore normalized since we copy from sparse
+ bufferAttribute.normalized = false;
+
+ for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
+
+ const index = sparseIndices[ i ];
+
+ bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
+ if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
+ if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
+ if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
+ if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
+
+ }
+
+ bufferAttribute.normalized = normalized;
+
+ }
+
+ return bufferAttribute;
+
+ } );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
+ *
+ * @private
+ * @param {number} textureIndex
+ * @return {Promise}
+ */
+ loadTexture( textureIndex ) {
+
+ const json = this.json;
+ const options = this.options;
+ const textureDef = json.textures[ textureIndex ];
+ const sourceIndex = textureDef.source;
+ const sourceDef = json.images[ sourceIndex ];
+
+ let loader = this.textureLoader;
+
+ if ( sourceDef.uri ) {
+
+ const handler = options.manager.getHandler( sourceDef.uri );
+ if ( handler !== null ) loader = handler;
+
+ }
+
+ return this.loadTextureImage( textureIndex, sourceIndex, loader );
+
+ }
+
+ loadTextureImage( textureIndex, sourceIndex, loader ) {
+
+ const parser = this;
+ const json = this.json;
+
+ const textureDef = json.textures[ textureIndex ];
+ const sourceDef = json.images[ sourceIndex ];
+
+ const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;
+
+ if ( this.textureCache[ cacheKey ] ) {
+
+ // See https://github.com/mrdoob/three.js/issues/21559.
+ return this.textureCache[ cacheKey ];
+
+ }
+
+ const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {
+
+ texture.flipY = false;
+
+ texture.name = textureDef.name || sourceDef.name || '';
+
+ if ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) {
+
+ texture.name = sourceDef.uri;
+
+ }
+
+ const samplers = json.samplers || {};
+ const sampler = samplers[ textureDef.sampler ] || {};
+
+ texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
+ texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
+ texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
+ texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
+ texture.generateMipmaps = ! texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
+
+ parser.associations.set( texture, { textures: textureIndex } );
+
+ return texture;
+
+ } ).catch( function () {
+
+ return null;
+
+ } );
+
+ this.textureCache[ cacheKey ] = promise;
+
+ return promise;
+
+ }
+
+ loadImageSource( sourceIndex, loader ) {
+
+ const parser = this;
+ const json = this.json;
+ const options = this.options;
+
+ if ( this.sourceCache[ sourceIndex ] !== undefined ) {
+
+ return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );
+
+ }
+
+ const sourceDef = json.images[ sourceIndex ];
+
+ const URL = self.URL || self.webkitURL;
+
+ let sourceURI = sourceDef.uri || '';
+ let isObjectURL = false;
+
+ if ( sourceDef.bufferView !== undefined ) {
+
+ // Load binary image data from bufferView, if provided.
+
+ sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {
+
+ isObjectURL = true;
+ const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );
+ sourceURI = URL.createObjectURL( blob );
+ return sourceURI;
+
+ } );
+
+ } else if ( sourceDef.uri === undefined ) {
+
+ throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );
+
+ }
+
+ const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
+
+ return new Promise( function ( resolve, reject ) {
+
+ let onLoad = resolve;
+
+ if ( loader.isImageBitmapLoader === true ) {
+
+ onLoad = function ( imageBitmap ) {
+
+ const texture = new Texture( imageBitmap );
+ texture.needsUpdate = true;
+
+ resolve( texture );
+
+ };
+
+ }
+
+ loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
+
+ } );
+
+ } ).then( function ( texture ) {
+
+ // Clean up resources and configure Texture.
+
+ if ( isObjectURL === true ) {
+
+ URL.revokeObjectURL( sourceURI );
+
+ }
+
+ assignExtrasToUserData( texture, sourceDef );
+
+ texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );
+
+ return texture;
+
+ } ).catch( function ( error ) {
+
+ console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
+ throw error;
+
+ } );
+
+ this.sourceCache[ sourceIndex ] = promise;
+ return promise;
+
+ }
+
+ /**
+ * Asynchronously assigns a texture to the given material parameters.
+ *
+ * @private
+ * @param {Object} materialParams
+ * @param {string} mapName
+ * @param {Object} mapDef
+ * @param {string} [colorSpace]
+ * @return {Promise}
+ */
+ assignTexture( materialParams, mapName, mapDef, colorSpace ) {
+
+ const parser = this;
+
+ return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
+
+ if ( ! texture ) return null;
+
+ if ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) {
+
+ texture = texture.clone();
+ texture.channel = mapDef.texCoord;
+
+ }
+
+ if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
+
+ const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
+
+ if ( transform ) {
+
+ const gltfReference = parser.associations.get( texture );
+ texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
+ parser.associations.set( texture, gltfReference );
+
+ }
+
+ }
+
+ if ( colorSpace !== undefined ) {
+
+ texture.colorSpace = colorSpace;
+
+ }
+
+ materialParams[ mapName ] = texture;
+
+ return texture;
+
+ } );
+
+ }
+
+ /**
+ * Assigns final material to a Mesh, Line, or Points instance. The instance
+ * already has a material (generated from the glTF material options alone)
+ * but reuse of the same glTF material may require multiple threejs materials
+ * to accommodate different primitive types, defines, etc. New materials will
+ * be created if necessary, and reused from a cache.
+ *
+ * @private
+ * @param {Object3D} mesh Mesh, Line, or Points instance.
+ */
+ assignFinalMaterial( mesh ) {
+
+ const geometry = mesh.geometry;
+ let material = mesh.material;
+
+ const useDerivativeTangents = geometry.attributes.tangent === undefined;
+ const useVertexColors = geometry.attributes.color !== undefined;
+ const useFlatShading = geometry.attributes.normal === undefined;
+
+ if ( mesh.isPoints ) {
+
+ const cacheKey = 'PointsMaterial:' + material.uuid;
+
+ let pointsMaterial = this.cache.get( cacheKey );
+
+ if ( ! pointsMaterial ) {
+
+ pointsMaterial = new PointsMaterial();
+ Material.prototype.copy.call( pointsMaterial, material );
+ pointsMaterial.color.copy( material.color );
+ pointsMaterial.map = material.map;
+ pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
+
+ this.cache.add( cacheKey, pointsMaterial );
+
+ }
+
+ material = pointsMaterial;
+
+ } else if ( mesh.isLine ) {
+
+ const cacheKey = 'LineBasicMaterial:' + material.uuid;
+
+ let lineMaterial = this.cache.get( cacheKey );
+
+ if ( ! lineMaterial ) {
+
+ lineMaterial = new LineBasicMaterial();
+ Material.prototype.copy.call( lineMaterial, material );
+ lineMaterial.color.copy( material.color );
+ lineMaterial.map = material.map;
+
+ this.cache.add( cacheKey, lineMaterial );
+
+ }
+
+ material = lineMaterial;
+
+ }
+
+ // Clone the material if it will be modified
+ if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
+
+ let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
+
+ if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
+ if ( useVertexColors ) cacheKey += 'vertex-colors:';
+ if ( useFlatShading ) cacheKey += 'flat-shading:';
+
+ let cachedMaterial = this.cache.get( cacheKey );
+
+ if ( ! cachedMaterial ) {
+
+ cachedMaterial = material.clone();
+
+ if ( useVertexColors ) cachedMaterial.vertexColors = true;
+ if ( useFlatShading ) cachedMaterial.flatShading = true;
+
+ if ( useDerivativeTangents ) {
+
+ // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
+ if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
+ if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
+
+ }
+
+ this.cache.add( cacheKey, cachedMaterial );
+
+ this.associations.set( cachedMaterial, this.associations.get( material ) );
+
+ }
+
+ material = cachedMaterial;
+
+ }
+
+ mesh.material = material;
+
+ }
+
+ getMaterialType( /* materialIndex */ ) {
+
+ return MeshStandardMaterial;
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
+ *
+ * @private
+ * @param {number} materialIndex
+ * @return {Promise}
+ */
+ loadMaterial( materialIndex ) {
+
+ const parser = this;
+ const json = this.json;
+ const extensions = this.extensions;
+ const materialDef = json.materials[ materialIndex ];
+
+ let materialType;
+ const materialParams = {};
+ const materialExtensions = materialDef.extensions || {};
+
+ const pending = [];
+
+ if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
+
+ const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
+ materialType = kmuExtension.getMaterialType();
+ pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
+
+ } else {
+
+ // Specification:
+ // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
+
+ const metallicRoughness = materialDef.pbrMetallicRoughness || {};
+
+ materialParams.color = new Color( 1.0, 1.0, 1.0 );
+ materialParams.opacity = 1.0;
+
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
+
+ const array = metallicRoughness.baseColorFactor;
+
+ materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace );
+ materialParams.opacity = array[ 3 ];
+
+ }
+
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
+
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) );
+
+ }
+
+ materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
+ materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
+
+ if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
+
+ pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
+ pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
+
+ }
+
+ materialType = this._invokeOne( function ( ext ) {
+
+ return ext.getMaterialType && ext.getMaterialType( materialIndex );
+
+ } );
+
+ pending.push( Promise.all( this._invokeAll( function ( ext ) {
+
+ return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
+
+ } ) ) );
+
+ }
+
+ if ( materialDef.doubleSided === true ) {
+
+ materialParams.side = DoubleSide;
+
+ }
+
+ const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
+
+ if ( alphaMode === ALPHA_MODES.BLEND ) {
+
+ materialParams.transparent = true;
+
+ // See: https://github.com/mrdoob/three.js/issues/17706
+ materialParams.depthWrite = false;
+
+ } else {
+
+ materialParams.transparent = false;
+
+ if ( alphaMode === ALPHA_MODES.MASK ) {
+
+ materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
+
+ }
+
+ }
+
+ if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
+
+ pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
+
+ materialParams.normalScale = new Vector2( 1, 1 );
+
+ if ( materialDef.normalTexture.scale !== undefined ) {
+
+ const scale = materialDef.normalTexture.scale;
+
+ materialParams.normalScale.set( scale, scale );
+
+ }
+
+ }
+
+ if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
+
+ pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
+
+ if ( materialDef.occlusionTexture.strength !== undefined ) {
+
+ materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
+
+ }
+
+ }
+
+ if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
+
+ const emissiveFactor = materialDef.emissiveFactor;
+ materialParams.emissive = new Color().setRGB( emissiveFactor[ 0 ], emissiveFactor[ 1 ], emissiveFactor[ 2 ], LinearSRGBColorSpace );
+
+ }
+
+ if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
+
+ pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, SRGBColorSpace ) );
+
+ }
+
+ return Promise.all( pending ).then( function () {
+
+ const material = new materialType( materialParams );
+
+ if ( materialDef.name ) material.name = materialDef.name;
+
+ assignExtrasToUserData( material, materialDef );
+
+ parser.associations.set( material, { materials: materialIndex } );
+
+ if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
+
+ return material;
+
+ } );
+
+ }
+
+ /**
+ * When Object3D instances are targeted by animation, they need unique names.
+ *
+ * @private
+ * @param {string} originalName
+ * @return {string}
+ */
+ createUniqueName( originalName ) {
+
+ const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );
+
+ if ( sanitizedName in this.nodeNamesUsed ) {
+
+ return sanitizedName + '_' + ( ++ this.nodeNamesUsed[ sanitizedName ] );
+
+ } else {
+
+ this.nodeNamesUsed[ sanitizedName ] = 0;
+
+ return sanitizedName;
+
+ }
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
+ *
+ * Creates BufferGeometries from primitives.
+ *
+ * @private
+ * @param {Array} primitives
+ * @return {Promise>}
+ */
+ loadGeometries( primitives ) {
+
+ const parser = this;
+ const extensions = this.extensions;
+ const cache = this.primitiveCache;
+
+ function createDracoPrimitive( primitive ) {
+
+ return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
+ .decodePrimitive( primitive, parser )
+ .then( function ( geometry ) {
+
+ return addPrimitiveAttributes( geometry, primitive, parser );
+
+ } );
+
+ }
+
+ const pending = [];
+
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
+
+ const primitive = primitives[ i ];
+ const cacheKey = createPrimitiveKey( primitive );
+
+ // See if we've already created this geometry
+ const cached = cache[ cacheKey ];
+
+ if ( cached ) {
+
+ // Use the cached geometry if it exists
+ pending.push( cached.promise );
+
+ } else {
+
+ let geometryPromise;
+
+ if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
+
+ // Use DRACO geometry if available
+ geometryPromise = createDracoPrimitive( primitive );
+
+ } else {
+
+ // Otherwise create a new geometry
+ geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
+
+ }
+
+ // Cache this geometry
+ cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
+
+ pending.push( geometryPromise );
+
+ }
+
+ }
+
+ return Promise.all( pending );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
+ *
+ * @private
+ * @param {number} meshIndex
+ * @return {Promise}
+ */
+ loadMesh( meshIndex ) {
+
+ const parser = this;
+ const json = this.json;
+ const extensions = this.extensions;
+
+ const meshDef = json.meshes[ meshIndex ];
+ const primitives = meshDef.primitives;
+
+ const pending = [];
+
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
+
+ const material = primitives[ i ].material === undefined
+ ? createDefaultMaterial( this.cache )
+ : this.getDependency( 'material', primitives[ i ].material );
+
+ pending.push( material );
+
+ }
+
+ pending.push( parser.loadGeometries( primitives ) );
+
+ return Promise.all( pending ).then( function ( results ) {
+
+ const materials = results.slice( 0, results.length - 1 );
+ const geometries = results[ results.length - 1 ];
+
+ const meshes = [];
+
+ for ( let i = 0, il = geometries.length; i < il; i ++ ) {
+
+ const geometry = geometries[ i ];
+ const primitive = primitives[ i ];
+
+ // 1. create Mesh
+
+ let mesh;
+
+ const material = materials[ i ];
+
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
+ primitive.mode === undefined ) {
+
+ // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
+ mesh = meshDef.isSkinnedMesh === true
+ ? new SkinnedMesh( geometry, material )
+ : new Mesh( geometry, material );
+
+ if ( mesh.isSkinnedMesh === true ) {
+
+ // normalize skin weights to fix malformed assets (see #15319)
+ mesh.normalizeSkinWeights();
+
+ }
+
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
+
+ mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode );
+
+ } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
+
+ mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode );
+
+ }
+
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
+
+ mesh = new LineSegments( geometry, material );
+
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
+
+ mesh = new Line( geometry, material );
+
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
+
+ mesh = new LineLoop( geometry, material );
+
+ } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
+
+ mesh = new Points( geometry, material );
+
+ } else {
+
+ throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
+
+ }
+
+ if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
+
+ updateMorphTargets( mesh, meshDef );
+
+ }
+
+ mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
+
+ assignExtrasToUserData( mesh, meshDef );
+
+ if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
+
+ parser.assignFinalMaterial( mesh );
+
+ meshes.push( mesh );
+
+ }
+
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
+
+ parser.associations.set( meshes[ i ], {
+ meshes: meshIndex,
+ primitives: i
+ } );
+
+ }
+
+ if ( meshes.length === 1 ) {
+
+ if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, meshes[ 0 ], meshDef );
+
+ return meshes[ 0 ];
+
+ }
+
+ const group = new Group();
+
+ if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, group, meshDef );
+
+ parser.associations.set( group, { meshes: meshIndex } );
+
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
+
+ group.add( meshes[ i ] );
+
+ }
+
+ return group;
+
+ } );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
+ *
+ * @private
+ * @param {number} cameraIndex
+ * @return {Promise|undefined}
+ */
+ loadCamera( cameraIndex ) {
+
+ let camera;
+ const cameraDef = this.json.cameras[ cameraIndex ];
+ const params = cameraDef[ cameraDef.type ];
+
+ if ( ! params ) {
+
+ console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
+ return;
+
+ }
+
+ if ( cameraDef.type === 'perspective' ) {
+
+ camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
+
+ } else if ( cameraDef.type === 'orthographic' ) {
+
+ camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
+
+ }
+
+ if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
+
+ assignExtrasToUserData( camera, cameraDef );
+
+ return Promise.resolve( camera );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
+ *
+ * @private
+ * @param {number} skinIndex
+ * @return {Promise}
+ */
+ loadSkin( skinIndex ) {
+
+ const skinDef = this.json.skins[ skinIndex ];
+
+ const pending = [];
+
+ for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {
+
+ pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );
+
+ }
+
+ if ( skinDef.inverseBindMatrices !== undefined ) {
+
+ pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );
+
+ } else {
+
+ pending.push( null );
+
+ }
+
+ return Promise.all( pending ).then( function ( results ) {
+
+ const inverseBindMatrices = results.pop();
+ const jointNodes = results;
+
+ // Note that bones (joint nodes) may or may not be in the
+ // scene graph at this time.
+
+ const bones = [];
+ const boneInverses = [];
+
+ for ( let i = 0, il = jointNodes.length; i < il; i ++ ) {
+
+ const jointNode = jointNodes[ i ];
+
+ if ( jointNode ) {
+
+ bones.push( jointNode );
+
+ const mat = new Matrix4();
+
+ if ( inverseBindMatrices !== null ) {
+
+ mat.fromArray( inverseBindMatrices.array, i * 16 );
+
+ }
+
+ boneInverses.push( mat );
+
+ } else {
+
+ console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] );
+
+ }
+
+ }
+
+ return new Skeleton( bones, boneInverses );
+
+ } );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
+ *
+ * @private
+ * @param {number} animationIndex
+ * @return {Promise}
+ */
+ loadAnimation( animationIndex ) {
+
+ const json = this.json;
+ const parser = this;
+
+ const animationDef = json.animations[ animationIndex ];
+ const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
+
+ const pendingNodes = [];
+ const pendingInputAccessors = [];
+ const pendingOutputAccessors = [];
+ const pendingSamplers = [];
+ const pendingTargets = [];
+
+ for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
+
+ const channel = animationDef.channels[ i ];
+ const sampler = animationDef.samplers[ channel.sampler ];
+ const target = channel.target;
+ const name = target.node;
+ const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
+ const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
+
+ if ( target.node === undefined ) continue;
+
+ pendingNodes.push( this.getDependency( 'node', name ) );
+ pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
+ pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
+ pendingSamplers.push( sampler );
+ pendingTargets.push( target );
+
+ }
+
+ return Promise.all( [
+
+ Promise.all( pendingNodes ),
+ Promise.all( pendingInputAccessors ),
+ Promise.all( pendingOutputAccessors ),
+ Promise.all( pendingSamplers ),
+ Promise.all( pendingTargets )
+
+ ] ).then( function ( dependencies ) {
+
+ const nodes = dependencies[ 0 ];
+ const inputAccessors = dependencies[ 1 ];
+ const outputAccessors = dependencies[ 2 ];
+ const samplers = dependencies[ 3 ];
+ const targets = dependencies[ 4 ];
+
+ const tracks = [];
+
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
+
+ const node = nodes[ i ];
+ const inputAccessor = inputAccessors[ i ];
+ const outputAccessor = outputAccessors[ i ];
+ const sampler = samplers[ i ];
+ const target = targets[ i ];
+
+ if ( node === undefined ) continue;
+
+ if ( node.updateMatrix ) {
+
+ node.updateMatrix();
+
+ }
+
+ const createdTracks = parser._createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target );
+
+ if ( createdTracks ) {
+
+ for ( let k = 0; k < createdTracks.length; k ++ ) {
+
+ tracks.push( createdTracks[ k ] );
+
+ }
+
+ }
+
+ }
+
+ const animation = new AnimationClip( animationName, undefined, tracks );
+
+ assignExtrasToUserData( animation, animationDef );
+
+ return animation;
+
+ } );
+
+ }
+
+ createNodeMesh( nodeIndex ) {
+
+ const json = this.json;
+ const parser = this;
+ const nodeDef = json.nodes[ nodeIndex ];
+
+ if ( nodeDef.mesh === undefined ) return null;
+
+ return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
+
+ const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
+
+ // if weights are provided on the node, override weights on the mesh.
+ if ( nodeDef.weights !== undefined ) {
+
+ node.traverse( function ( o ) {
+
+ if ( ! o.isMesh ) return;
+
+ for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
+
+ o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
+
+ }
+
+ } );
+
+ }
+
+ return node;
+
+ } );
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
+ *
+ * @private
+ * @param {number} nodeIndex
+ * @return {Promise}
+ */
+ loadNode( nodeIndex ) {
+
+ const json = this.json;
+ const parser = this;
+
+ const nodeDef = json.nodes[ nodeIndex ];
+
+ const nodePending = parser._loadNodeShallow( nodeIndex );
+
+ const childPending = [];
+ const childrenDef = nodeDef.children || [];
+
+ for ( let i = 0, il = childrenDef.length; i < il; i ++ ) {
+
+ childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );
+
+ }
+
+ const skeletonPending = nodeDef.skin === undefined
+ ? Promise.resolve( null )
+ : parser.getDependency( 'skin', nodeDef.skin );
+
+ return Promise.all( [
+ nodePending,
+ Promise.all( childPending ),
+ skeletonPending
+ ] ).then( function ( results ) {
+
+ const node = results[ 0 ];
+ const children = results[ 1 ];
+ const skeleton = results[ 2 ];
+
+ if ( skeleton !== null ) {
+
+ // This full traverse should be fine because
+ // child glTF nodes have not been added to this node yet.
+ node.traverse( function ( mesh ) {
+
+ if ( ! mesh.isSkinnedMesh ) return;
+
+ mesh.bind( skeleton, _identityMatrix );
+
+ } );
+
+ }
+
+ for ( let i = 0, il = children.length; i < il; i ++ ) {
+
+ node.add( children[ i ] );
+
+ }
+
+ // Reconstruct pivot from container pattern created by GLTFExporter
+ // The container has position+pivot, rotation, scale; child has -pivot offset and mesh
+ if ( node.userData.pivot !== undefined && children.length > 0 ) {
+
+ const pivot = node.userData.pivot;
+ const pivotChild = children[ 0 ];
+
+ // Set pivot on container and adjust transforms
+ node.pivot = new Vector3().fromArray( pivot );
+
+ // Adjust container position: stored as position + pivot, so subtract pivot
+ node.position.x -= pivot[ 0 ];
+ node.position.y -= pivot[ 1 ];
+ node.position.z -= pivot[ 2 ];
+
+ // Remove the child's -pivot offset since pivot now handles it
+ pivotChild.position.set( 0, 0, 0 );
+
+ delete node.userData.pivot;
+
+ }
+
+ return node;
+
+ } );
+
+ }
+
+ // ._loadNodeShallow() parses a single node.
+ // skin and child nodes are created and added in .loadNode() (no '_' prefix).
+ _loadNodeShallow( nodeIndex ) {
+
+ const json = this.json;
+ const extensions = this.extensions;
+ const parser = this;
+
+ // This method is called from .loadNode() and .loadSkin().
+ // Cache a node to avoid duplication.
+
+ if ( this.nodeCache[ nodeIndex ] !== undefined ) {
+
+ return this.nodeCache[ nodeIndex ];
+
+ }
+
+ const nodeDef = json.nodes[ nodeIndex ];
+
+ // reserve node's name before its dependencies, so the root has the intended name.
+ const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
+
+ const pending = [];
+
+ const meshPromise = parser._invokeOne( function ( ext ) {
+
+ return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
+
+ } );
+
+ if ( meshPromise ) {
+
+ pending.push( meshPromise );
+
+ }
+
+ if ( nodeDef.camera !== undefined ) {
+
+ pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
+
+ return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
+
+ } ) );
+
+ }
+
+ parser._invokeAll( function ( ext ) {
+
+ return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
+
+ } ).forEach( function ( promise ) {
+
+ pending.push( promise );
+
+ } );
+
+ this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {
+
+ let node;
+
+ // .isBone isn't in glTF spec. See ._markDefs
+ if ( nodeDef.isBone === true ) {
+
+ node = new Bone();
+
+ } else if ( objects.length > 1 ) {
+
+ node = new Group();
+
+ } else if ( objects.length === 1 ) {
+
+ node = objects[ 0 ];
+
+ } else {
+
+ node = new Object3D();
+
+ }
+
+ if ( node !== objects[ 0 ] ) {
+
+ for ( let i = 0, il = objects.length; i < il; i ++ ) {
+
+ node.add( objects[ i ] );
+
+ }
+
+ }
+
+ if ( nodeDef.name ) {
+
+ node.userData.name = nodeDef.name;
+ node.name = nodeName;
+
+ }
+
+ assignExtrasToUserData( node, nodeDef );
+
+ if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
+
+ if ( nodeDef.matrix !== undefined ) {
+
+ const matrix = new Matrix4();
+ matrix.fromArray( nodeDef.matrix );
+ node.applyMatrix4( matrix );
+
+ } else {
+
+ if ( nodeDef.translation !== undefined ) {
+
+ node.position.fromArray( nodeDef.translation );
+
+ }
+
+ if ( nodeDef.rotation !== undefined ) {
+
+ node.quaternion.fromArray( nodeDef.rotation );
+
+ }
+
+ if ( nodeDef.scale !== undefined ) {
+
+ node.scale.fromArray( nodeDef.scale );
+
+ }
+
+ }
+
+ if ( ! parser.associations.has( node ) ) {
+
+ parser.associations.set( node, {} );
+
+ } else if ( nodeDef.mesh !== undefined && parser.meshCache.refs[ nodeDef.mesh ] > 1 ) {
+
+ const mapping = parser.associations.get( node );
+ parser.associations.set( node, { ...mapping } );
+
+ }
+
+ parser.associations.get( node ).nodes = nodeIndex;
+
+ return node;
+
+ } );
+
+ return this.nodeCache[ nodeIndex ];
+
+ }
+
+ /**
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
+ *
+ * @private
+ * @param {number} sceneIndex
+ * @return {Promise}
+ */
+ loadScene( sceneIndex ) {
+
+ const extensions = this.extensions;
+ const sceneDef = this.json.scenes[ sceneIndex ];
+ const parser = this;
+
+ // Loader returns Group, not Scene.
+ // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
+ const scene = new Group();
+ if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
+
+ assignExtrasToUserData( scene, sceneDef );
+
+ if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
+
+ const nodeIds = sceneDef.nodes || [];
+
+ const pending = [];
+
+ for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
+
+ pending.push( parser.getDependency( 'node', nodeIds[ i ] ) );
+
+ }
+
+ return Promise.all( pending ).then( function ( nodes ) {
+
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
+
+ const node = nodes[ i ];
+
+ // If the node already has a parent, it means it's being reused across multiple scenes.
+ // Clone it to avoid the second scene's add() removing it from the first scene.
+ // See: https://github.com/mrdoob/three.js/issues/27993
+ if ( node.parent !== null ) {
+
+ scene.add( clone( node ) );
+
+ } else {
+
+ scene.add( node );
+
+ }
+
+ }
+
+ // Removes dangling associations, associations that reference a node that
+ // didn't make it into the scene.
+ const reduceAssociations = ( node ) => {
+
+ const reducedAssociations = new Map();
+
+ for ( const [ key, value ] of parser.associations ) {
+
+ if ( key instanceof Material || key instanceof Texture ) {
+
+ reducedAssociations.set( key, value );
+
+ }
+
+ }
+
+ node.traverse( ( node ) => {
+
+ const mappings = parser.associations.get( node );
+
+ if ( mappings != null ) {
+
+ reducedAssociations.set( node, mappings );
+
+ }
+
+ } );
+
+ return reducedAssociations;
+
+ };
+
+ parser.associations = reduceAssociations( scene );
+
+ return scene;
+
+ } );
+
+ }
+
+ _createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ) {
+
+ const tracks = [];
+
+ const targetName = node.name ? node.name : node.uuid;
+ const targetNames = [];
+
+ function collectMorphTargets( object ) {
+
+ if ( object.morphTargetInfluences ) {
+
+ targetNames.push( object.name ? object.name : object.uuid );
+
+ }
+
+ }
+
+
+ if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
+
+ collectMorphTargets( node );
+
+ // for multi-primitive meshes, the node is a Group containing the sub-meshes
+
+ if ( node.isGroup ) {
+
+ node.children.forEach( collectMorphTargets );
+
+ }
+
+ } else {
+
+ targetNames.push( targetName );
+
+ }
+
+ let TypedKeyframeTrack;
+
+ switch ( PATH_PROPERTIES[ target.path ] ) {
+
+ case PATH_PROPERTIES.weights:
+
+ TypedKeyframeTrack = NumberKeyframeTrack;
+ break;
+
+ case PATH_PROPERTIES.rotation:
+
+ TypedKeyframeTrack = QuaternionKeyframeTrack;
+ break;
+
+ case PATH_PROPERTIES.translation:
+ case PATH_PROPERTIES.scale:
+
+ TypedKeyframeTrack = VectorKeyframeTrack;
+ break;
+
+ default:
+
+ switch ( outputAccessor.itemSize ) {
+
+ case 1:
+ TypedKeyframeTrack = NumberKeyframeTrack;
+ break;
+ case 2:
+ case 3:
+ default:
+ TypedKeyframeTrack = VectorKeyframeTrack;
+ break;
+
+ }
+
+ break;
+
+ }
+
+ const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
+
+
+ const outputArray = this._getArrayFromAccessor( outputAccessor );
+
+ for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
+
+ const track = new TypedKeyframeTrack(
+ targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
+ inputAccessor.array,
+ outputArray,
+ interpolation
+ );
+
+ // Override interpolation with custom factory method.
+ if ( sampler.interpolation === 'CUBICSPLINE' ) {
+
+ this._createCubicSplineTrackInterpolant( track );
+
+ }
+
+ tracks.push( track );
+
+ }
+
+ return tracks;
+
+ }
+
+ _getArrayFromAccessor( accessor ) {
+
+ let outputArray = accessor.array;
+
+ if ( accessor.normalized ) {
+
+ const scale = getNormalizedComponentScale( outputArray.constructor );
+ const scaled = new Float32Array( outputArray.length );
+
+ for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
+
+ scaled[ j ] = outputArray[ j ] * scale;
+
+ }
+
+ outputArray = scaled;
+
+ }
+
+ return outputArray;
+
+ }
+
+ _createCubicSplineTrackInterpolant( track ) {
+
+ track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
+
+ // A CUBICSPLINE keyframe in glTF has three output values for each input value,
+ // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
+ // must be divided by three to get the interpolant's sampleSize argument.
+
+ const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
+
+ return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
+
+ };
+
+ // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
+ track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
+
+ }
+
+}
+
+/**
+ *
+ * @private
+ * @param {BufferGeometry} geometry
+ * @param {GLTF.Primitive} primitiveDef
+ * @param {GLTFParser} parser
+ */
+function computeBounds( geometry, primitiveDef, parser ) {
+
+ const attributes = primitiveDef.attributes;
+
+ const box = new Box3();
+
+ if ( attributes.POSITION !== undefined ) {
+
+ const accessor = parser.json.accessors[ attributes.POSITION ];
+
+ const min = accessor.min;
+ const max = accessor.max;
+
+ // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
+
+ if ( min !== undefined && max !== undefined ) {
+
+ box.set(
+ new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
+ new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
+ );
+
+ if ( accessor.normalized ) {
+
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
+ box.min.multiplyScalar( boxScale );
+ box.max.multiplyScalar( boxScale );
+
+ }
+
+ } else {
+
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
+
+ return;
+
+ }
+
+ } else {
+
+ return;
+
+ }
+
+ const targets = primitiveDef.targets;
+
+ if ( targets !== undefined ) {
+
+ const maxDisplacement = new Vector3();
+ const vector = new Vector3();
+
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
+
+ const target = targets[ i ];
+
+ if ( target.POSITION !== undefined ) {
+
+ const accessor = parser.json.accessors[ target.POSITION ];
+ const min = accessor.min;
+ const max = accessor.max;
+
+ // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
+
+ if ( min !== undefined && max !== undefined ) {
+
+ // we need to get max of absolute components because target weight is [-1,1]
+ vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
+ vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
+ vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
+
+
+ if ( accessor.normalized ) {
+
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
+ vector.multiplyScalar( boxScale );
+
+ }
+
+ // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
+ // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
+ // are used to implement key-frame animations and as such only two are active at a time - this results in very large
+ // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
+ maxDisplacement.max( vector );
+
+ } else {
+
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
+
+ }
+
+ }
+
+ }
+
+ // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
+ box.expandByVector( maxDisplacement );
+
+ }
+
+ geometry.boundingBox = box;
+
+ const sphere = new Sphere();
+
+ box.getCenter( sphere.center );
+ sphere.radius = box.min.distanceTo( box.max ) / 2;
+
+ geometry.boundingSphere = sphere;
+
+}
+
+/**
+ *
+ * @private
+ * @param {BufferGeometry} geometry
+ * @param {GLTF.Primitive} primitiveDef
+ * @param {GLTFParser} parser
+ * @return {Promise}
+ */
+function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
+
+ const attributes = primitiveDef.attributes;
+
+ const pending = [];
+
+ function assignAttributeAccessor( accessorIndex, attributeName ) {
+
+ return parser.getDependency( 'accessor', accessorIndex )
+ .then( function ( accessor ) {
+
+ geometry.setAttribute( attributeName, accessor );
+
+ } );
+
+ }
+
+ for ( const gltfAttributeName in attributes ) {
+
+ const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
+
+ // Skip attributes already provided by e.g. Draco extension.
+ if ( threeAttributeName in geometry.attributes ) continue;
+
+ pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
+
+ }
+
+ if ( primitiveDef.indices !== undefined && ! geometry.index ) {
+
+ const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
+
+ geometry.setIndex( accessor );
+
+ } );
+
+ pending.push( accessor );
+
+ }
+
+ if ( ColorManagement.workingColorSpace !== LinearSRGBColorSpace && 'COLOR_0' in attributes ) {
+
+ console.warn( `THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.` );
+
+ }
+
+ assignExtrasToUserData( geometry, primitiveDef );
+
+ computeBounds( geometry, primitiveDef, parser );
+
+ return Promise.all( pending ).then( function () {
+
+ return primitiveDef.targets !== undefined
+ ? addMorphTargets( geometry, primitiveDef.targets, parser )
+ : geometry;
+
+ } );
+
+}
+
+/**
+ * Loader result of `GLTFLoader`.
+ *
+ * @typedef {Object} GLTFLoader~LoadObject
+ * @property {Array} animations - An array of animation clips.
+ * @property {Object} asset - Meta data about the loaded asset.
+ * @property {Array} cameras - An array of cameras.
+ * @property {GLTFParser} parser - A reference to the internal parser.
+ * @property {Group} scene - The default scene.
+ * @property {Array} scenes - glTF assets might define multiple scenes.
+ * @property {Object} userData - Additional data.
+ **/
+
+export { GLTFLoader };
diff --git a/src/core/static/libs/OrbitControls-0.184.0.js b/src/core/static/libs/OrbitControls-0.184.0.js
new file mode 100644
index 000000000..6060cd4f9
--- /dev/null
+++ b/src/core/static/libs/OrbitControls-0.184.0.js
@@ -0,0 +1,1963 @@
+import {
+ Controls,
+ MOUSE,
+ Quaternion,
+ Spherical,
+ TOUCH,
+ Vector2,
+ Vector3,
+ Plane,
+ Ray,
+ MathUtils
+} from 'three';
+
+/**
+ * Fires when the camera has been transformed by the controls.
+ *
+ * @event OrbitControls#change
+ * @type {Object}
+ */
+const _changeEvent = { type: 'change' };
+
+/**
+ * Fires when an interaction was initiated.
+ *
+ * @event OrbitControls#start
+ * @type {Object}
+ */
+const _startEvent = { type: 'start' };
+
+/**
+ * Fires when an interaction has finished.
+ *
+ * @event OrbitControls#end
+ * @type {Object}
+ */
+const _endEvent = { type: 'end' };
+
+const _ray = new Ray();
+const _plane = new Plane();
+const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
+
+const _v = new Vector3();
+const _twoPI = 2 * Math.PI;
+
+const _STATE = {
+ NONE: - 1,
+ ROTATE: 0,
+ DOLLY: 1,
+ PAN: 2,
+ TOUCH_ROTATE: 3,
+ TOUCH_PAN: 4,
+ TOUCH_DOLLY_PAN: 5,
+ TOUCH_DOLLY_ROTATE: 6
+};
+const _EPS = 0.000001;
+
+
+/**
+ * Orbit controls allow the camera to orbit around a target.
+ *
+ * OrbitControls performs orbiting, dollying (zooming), and panning. Unlike {@link TrackballControls},
+ * it maintains the "up" direction `object.up` (+Y by default).
+ *
+ * - Orbit: Left mouse / touch: one-finger move.
+ * - Zoom: Middle mouse, or mousewheel / touch: two-finger spread or squish.
+ * - Pan: Right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move.
+ *
+ * ```js
+ * const controls = new OrbitControls( camera, renderer.domElement );
+ *
+ * // controls.update() must be called after any manual changes to the camera's transform
+ * camera.position.set( 0, 20, 100 );
+ * controls.update();
+ *
+ * function animate() {
+ *
+ * // required if controls.enableDamping or controls.autoRotate are set to true
+ * controls.update();
+ *
+ * renderer.render( scene, camera );
+ *
+ * }
+ * ```
+ *
+ * @augments Controls
+ * @three_import import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+ */
+class OrbitControls extends Controls {
+
+ /**
+ * Constructs a new controls instance.
+ *
+ * @param {Object3D} object - The object that is managed by the controls.
+ * @param {?HTMLElement} domElement - The HTML element used for event listeners.
+ */
+ constructor( object, domElement = null ) {
+
+ super( object, domElement );
+
+ this.state = _STATE.NONE;
+
+ /**
+ * The focus point of the controls, the `object` orbits around this.
+ * It can be updated manually at any point to change the focus of the controls.
+ *
+ * @type {Vector3}
+ */
+ this.target = new Vector3();
+
+ /**
+ * The focus point of the `minTargetRadius` and `maxTargetRadius` limits.
+ * It can be updated manually at any point to change the center of interest
+ * for the `target`.
+ *
+ * @type {Vector3}
+ */
+ this.cursor = new Vector3();
+
+ /**
+ * How far you can dolly in (perspective camera only).
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minDistance = 0;
+
+ /**
+ * How far you can dolly out (perspective camera only).
+ *
+ * @type {number}
+ * @default Infinity
+ */
+ this.maxDistance = Infinity;
+
+ /**
+ * How far you can zoom in (orthographic camera only).
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minZoom = 0;
+
+ /**
+ * How far you can zoom out (orthographic camera only).
+ *
+ * @type {number}
+ * @default Infinity
+ */
+ this.maxZoom = Infinity;
+
+ /**
+ * How close you can get the target to the 3D `cursor`.
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minTargetRadius = 0;
+
+ /**
+ * How far you can move the target from the 3D `cursor`.
+ *
+ * @type {number}
+ * @default Infinity
+ */
+ this.maxTargetRadius = Infinity;
+
+ /**
+ * How far you can orbit vertically, lower limit. Range is `[0, Math.PI]` radians.
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minPolarAngle = 0;
+
+ /**
+ * How far you can orbit vertically, upper limit. Range is `[0, Math.PI]` radians.
+ *
+ * @type {number}
+ * @default Math.PI
+ */
+ this.maxPolarAngle = Math.PI;
+
+ /**
+ * How far you can orbit horizontally, lower limit. If set, the interval `[ min, max ]`
+ * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`.
+ *
+ * @type {number}
+ * @default -Infinity
+ */
+ this.minAzimuthAngle = - Infinity;
+
+ /**
+ * How far you can orbit horizontally, upper limit. If set, the interval `[ min, max ]`
+ * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`.
+ *
+ * @type {number}
+ * @default -Infinity
+ */
+ this.maxAzimuthAngle = Infinity;
+
+ /**
+ * Set to `true` to enable damping (inertia), which can be used to give a sense of weight
+ * to the controls. Note that if this is enabled, you must call `update()` in your animation
+ * loop.
+ *
+ * @type {boolean}
+ * @default false
+ */
+ this.enableDamping = false;
+
+ /**
+ * The damping inertia used if `enableDamping` is set to `true`.
+ *
+ * Note that for this to work, you must call `update()` in your animation loop.
+ *
+ * @type {number}
+ * @default 0.05
+ */
+ this.dampingFactor = 0.05;
+
+ /**
+ * Enable or disable zooming (dollying) of the camera.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.enableZoom = true;
+
+ /**
+ * Speed of zooming / dollying.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.zoomSpeed = 1.0;
+
+ /**
+ * Enable or disable horizontal and vertical rotation of the camera.
+ *
+ * Note that it is possible to disable a single axis by setting the min and max of the
+ * `minPolarAngle` or `minAzimuthAngle` to the same value, which will cause the vertical
+ * or horizontal rotation to be fixed at that value.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.enableRotate = true;
+
+ /**
+ * Speed of rotation.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.rotateSpeed = 1.0;
+
+ /**
+ * How fast to rotate the camera when the keyboard is used.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.keyRotateSpeed = 1.0;
+
+ /**
+ * Enable or disable camera panning.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.enablePan = true;
+
+ /**
+ * Speed of panning.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.panSpeed = 1.0;
+
+ /**
+ * Defines how the camera's position is translated when panning. If `true`, the camera pans
+ * in screen space. Otherwise, the camera pans in the plane orthogonal to the camera's up
+ * direction.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.screenSpacePanning = true;
+
+ /**
+ * How fast to pan the camera when the keyboard is used in
+ * pixels per keypress.
+ *
+ * @type {number}
+ * @default 7
+ */
+ this.keyPanSpeed = 7.0;
+
+ /**
+ * Setting this property to `true` allows to zoom to the cursor's position.
+ *
+ * @type {boolean}
+ * @default false
+ */
+ this.zoomToCursor = false;
+
+ /**
+ * Set to true to automatically rotate around the target
+ *
+ * Note that if this is enabled, you must call `update()` in your animation loop.
+ * If you want the auto-rotate speed to be independent of the frame rate (the refresh
+ * rate of the display), you must pass the time `deltaTime`, in seconds, to `update()`.
+ *
+ * @type {boolean}
+ * @default false
+ */
+ this.autoRotate = false;
+
+ /**
+ * How fast to rotate around the target if `autoRotate` is `true`. The default equates to 30 seconds
+ * per orbit at 60fps.
+ *
+ * Note that if `autoRotate` is enabled, you must call `update()` in your animation loop.
+ *
+ * @type {number}
+ * @default 2
+ */
+ this.autoRotateSpeed = 2.0;
+
+ /**
+ * This object contains references to the keycodes for controlling camera panning.
+ *
+ * ```js
+ * controls.keys = {
+ * LEFT: 'ArrowLeft', //left arrow
+ * UP: 'ArrowUp', // up arrow
+ * RIGHT: 'ArrowRight', // right arrow
+ * BOTTOM: 'ArrowDown' // down arrow
+ * }
+ * ```
+ * @type {Object}
+ */
+ this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
+
+ /**
+ * This object contains references to the mouse actions used by the controls.
+ *
+ * ```js
+ * controls.mouseButtons = {
+ * LEFT: THREE.MOUSE.ROTATE,
+ * MIDDLE: THREE.MOUSE.DOLLY,
+ * RIGHT: THREE.MOUSE.PAN
+ * }
+ * ```
+ * @type {Object}
+ */
+ this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
+
+ /**
+ * This object contains references to the touch actions used by the controls.
+ *
+ * ```js
+ * controls.mouseButtons = {
+ * ONE: THREE.TOUCH.ROTATE,
+ * TWO: THREE.TOUCH.DOLLY_PAN
+ * }
+ * ```
+ * @type {Object}
+ */
+ this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
+
+ /**
+ * Used internally by `saveState()` and `reset()`.
+ *
+ * @type {Vector3}
+ */
+ this.target0 = this.target.clone();
+
+ /**
+ * Used internally by `saveState()` and `reset()`.
+ *
+ * @type {Vector3}
+ */
+ this.position0 = this.object.position.clone();
+
+ /**
+ * Used internally by `saveState()` and `reset()`.
+ *
+ * @type {number}
+ */
+ this.zoom0 = this.object.zoom;
+
+ this._cursorStyle = 'auto';
+
+ // the target DOM element for key events
+ this._domElementKeyEvents = null;
+
+ // internals
+
+ this._lastPosition = new Vector3();
+ this._lastQuaternion = new Quaternion();
+ this._lastTargetPosition = new Vector3();
+
+ // so camera.up is the orbit axis
+ this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
+ this._quatInverse = this._quat.clone().invert();
+
+ // current position in spherical coordinates
+ this._spherical = new Spherical();
+ this._sphericalDelta = new Spherical();
+
+ this._scale = 1;
+ this._panOffset = new Vector3();
+
+ this._rotateStart = new Vector2();
+ this._rotateEnd = new Vector2();
+ this._rotateDelta = new Vector2();
+
+ this._panStart = new Vector2();
+ this._panEnd = new Vector2();
+ this._panDelta = new Vector2();
+
+ this._dollyStart = new Vector2();
+ this._dollyEnd = new Vector2();
+ this._dollyDelta = new Vector2();
+
+ this._dollyDirection = new Vector3();
+ this._mouse = new Vector2();
+ this._performCursorZoom = false;
+
+ this._pointers = [];
+ this._pointerPositions = {};
+
+ this._controlActive = false;
+
+ // event listeners
+
+ this._onPointerMove = onPointerMove.bind( this );
+ this._onPointerDown = onPointerDown.bind( this );
+ this._onPointerUp = onPointerUp.bind( this );
+ this._onContextMenu = onContextMenu.bind( this );
+ this._onMouseWheel = onMouseWheel.bind( this );
+ this._onKeyDown = onKeyDown.bind( this );
+
+ this._onTouchStart = onTouchStart.bind( this );
+ this._onTouchMove = onTouchMove.bind( this );
+
+ this._onMouseDown = onMouseDown.bind( this );
+ this._onMouseMove = onMouseMove.bind( this );
+
+ this._interceptControlDown = interceptControlDown.bind( this );
+ this._interceptControlUp = interceptControlUp.bind( this );
+
+ //
+
+ if ( this.domElement !== null ) {
+
+ this.connect( this.domElement );
+
+ }
+
+ this.update();
+
+ }
+
+ /**
+ * Defines the visual representation of the cursor.
+ *
+ * @type {('auto'|'grab')}
+ * @default 'auto'
+ */
+ set cursorStyle( type ) {
+
+ this._cursorStyle = type;
+
+ if ( type === 'grab' ) {
+
+ this.domElement.style.cursor = 'grab';
+
+ } else {
+
+ this.domElement.style.cursor = 'auto';
+
+ }
+
+ }
+
+ get cursorStyle() {
+
+ return this._cursorStyle;
+
+ }
+
+ connect( element ) {
+
+ super.connect( element );
+
+ this.domElement.addEventListener( 'pointerdown', this._onPointerDown );
+ this.domElement.addEventListener( 'pointercancel', this._onPointerUp );
+
+ this.domElement.addEventListener( 'contextmenu', this._onContextMenu );
+ this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } );
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+ document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } );
+
+ this.domElement.style.touchAction = 'none'; // Disable touch scroll
+
+ }
+
+ disconnect() {
+
+ this.domElement.removeEventListener( 'pointerdown', this._onPointerDown );
+ this.domElement.ownerDocument.removeEventListener( 'pointermove', this._onPointerMove );
+ this.domElement.ownerDocument.removeEventListener( 'pointerup', this._onPointerUp );
+ this.domElement.removeEventListener( 'pointercancel', this._onPointerUp );
+
+ this.domElement.removeEventListener( 'wheel', this._onMouseWheel );
+ this.domElement.removeEventListener( 'contextmenu', this._onContextMenu );
+
+ this.stopListenToKeyEvents();
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+ document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } );
+
+ this.domElement.style.touchAction = ''; // Restore touch scroll
+
+ }
+
+ dispose() {
+
+ this.disconnect();
+
+ }
+
+ /**
+ * Get the current vertical rotation, in radians.
+ *
+ * @return {number} The current vertical rotation, in radians.
+ */
+ getPolarAngle() {
+
+ return this._spherical.phi;
+
+ }
+
+ /**
+ * Get the current horizontal rotation, in radians.
+ *
+ * @return {number} The current horizontal rotation, in radians.
+ */
+ getAzimuthalAngle() {
+
+ return this._spherical.theta;
+
+ }
+
+ /**
+ * Returns the distance from the camera to the target.
+ *
+ * @return {number} The distance from the camera to the target.
+ */
+ getDistance() {
+
+ return this.object.position.distanceTo( this.target );
+
+ }
+
+ /**
+ * Adds key event listeners to the given DOM element.
+ * `window` is a recommended argument for using this method.
+ *
+ * @param {HTMLElement} domElement - The DOM element
+ */
+ listenToKeyEvents( domElement ) {
+
+ domElement.addEventListener( 'keydown', this._onKeyDown );
+ this._domElementKeyEvents = domElement;
+
+ }
+
+ /**
+ * Removes the key event listener previously defined with `listenToKeyEvents()`.
+ */
+ stopListenToKeyEvents() {
+
+ if ( this._domElementKeyEvents !== null ) {
+
+ this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown );
+ this._domElementKeyEvents = null;
+
+ }
+
+ }
+
+ /**
+ * Save the current state of the controls. This can later be recovered with `reset()`.
+ */
+ saveState() {
+
+ this.target0.copy( this.target );
+ this.position0.copy( this.object.position );
+ this.zoom0 = this.object.zoom;
+
+ }
+
+ /**
+ * Reset the controls to their state from either the last time the `saveState()`
+ * was called, or the initial state.
+ */
+ reset() {
+
+ this.target.copy( this.target0 );
+ this.object.position.copy( this.position0 );
+ this.object.zoom = this.zoom0;
+
+ this.object.updateProjectionMatrix();
+ this.dispatchEvent( _changeEvent );
+
+ this.update();
+
+ this.state = _STATE.NONE;
+
+ }
+
+ /**
+ * Programmatically pan the camera.
+ *
+ * @param {number} deltaX - The horizontal pan amount in pixels.
+ * @param {number} deltaY - The vertical pan amount in pixels.
+ */
+ pan( deltaX, deltaY ) {
+
+ this._pan( deltaX, deltaY );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically dolly in (zoom in for perspective camera).
+ *
+ * @param {number} dollyScale - The dolly scale factor.
+ */
+ dollyIn( dollyScale ) {
+
+ this._dollyIn( dollyScale );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically dolly out (zoom out for perspective camera).
+ *
+ * @param {number} dollyScale - The dolly scale factor.
+ */
+ dollyOut( dollyScale ) {
+
+ this._dollyOut( dollyScale );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically rotate the camera left (around the vertical axis).
+ *
+ * @param {number} angle - The rotation angle in radians.
+ */
+ rotateLeft( angle ) {
+
+ this._rotateLeft( angle );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically rotate the camera up (around the horizontal axis).
+ *
+ * @param {number} angle - The rotation angle in radians.
+ */
+ rotateUp( angle ) {
+
+ this._rotateUp( angle );
+ this.update();
+
+ }
+
+ update( deltaTime = null ) {
+
+ const position = this.object.position;
+
+ _v.copy( position ).sub( this.target );
+
+ // rotate offset to "y-axis-is-up" space
+ _v.applyQuaternion( this._quat );
+
+ // angle from z-axis around y-axis
+ this._spherical.setFromVector3( _v );
+
+ if ( this.autoRotate && this.state === _STATE.NONE ) {
+
+ this._rotateLeft( this._getAutoRotationAngle( deltaTime ) );
+
+ }
+
+ if ( this.enableDamping ) {
+
+ this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor;
+ this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor;
+
+ } else {
+
+ this._spherical.theta += this._sphericalDelta.theta;
+ this._spherical.phi += this._sphericalDelta.phi;
+
+ }
+
+ // restrict theta to be between desired limits
+
+ let min = this.minAzimuthAngle;
+ let max = this.maxAzimuthAngle;
+
+ if ( isFinite( min ) && isFinite( max ) ) {
+
+ if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI;
+
+ if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI;
+
+ if ( min <= max ) {
+
+ this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) );
+
+ } else {
+
+ this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ?
+ Math.max( min, this._spherical.theta ) :
+ Math.min( max, this._spherical.theta );
+
+ }
+
+ }
+
+ // restrict phi to be between desired limits
+ this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) );
+
+ this._spherical.makeSafe();
+
+
+ // move target to panned location
+
+ if ( this.enableDamping === true ) {
+
+ this.target.addScaledVector( this._panOffset, this.dampingFactor );
+
+ } else {
+
+ this.target.add( this._panOffset );
+
+ }
+
+ // Limit the target distance from the cursor to create a sphere around the center of interest
+ this.target.sub( this.cursor );
+ this.target.clampLength( this.minTargetRadius, this.maxTargetRadius );
+ this.target.add( this.cursor );
+
+ let zoomChanged = false;
+ // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
+ // we adjust zoom later in these cases
+ if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) {
+
+ this._spherical.radius = this._clampDistance( this._spherical.radius );
+
+ } else {
+
+ const prevRadius = this._spherical.radius;
+ this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale );
+ zoomChanged = prevRadius != this._spherical.radius;
+
+ }
+
+ _v.setFromSpherical( this._spherical );
+
+ // rotate offset back to "camera-up-vector-is-up" space
+ _v.applyQuaternion( this._quatInverse );
+
+ position.copy( this.target ).add( _v );
+
+ this.object.lookAt( this.target );
+
+ if ( this.enableDamping === true ) {
+
+ this._sphericalDelta.theta *= ( 1 - this.dampingFactor );
+ this._sphericalDelta.phi *= ( 1 - this.dampingFactor );
+
+ this._panOffset.multiplyScalar( 1 - this.dampingFactor );
+
+ } else {
+
+ this._sphericalDelta.set( 0, 0, 0 );
+
+ this._panOffset.set( 0, 0, 0 );
+
+ }
+
+ // adjust camera position
+ if ( this.zoomToCursor && this._performCursorZoom ) {
+
+ let newRadius = null;
+ if ( this.object.isPerspectiveCamera ) {
+
+ // move the camera down the pointer ray
+ // this method avoids floating point error
+ const prevRadius = _v.length();
+ newRadius = this._clampDistance( prevRadius * this._scale );
+
+ const radiusDelta = prevRadius - newRadius;
+ this.object.position.addScaledVector( this._dollyDirection, radiusDelta );
+ this.object.updateMatrixWorld();
+
+ zoomChanged = !! radiusDelta;
+
+ } else if ( this.object.isOrthographicCamera ) {
+
+ // adjust the ortho camera position based on zoom changes
+ const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 );
+ mouseBefore.unproject( this.object );
+
+ const prevZoom = this.object.zoom;
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
+ this.object.updateProjectionMatrix();
+
+ zoomChanged = prevZoom !== this.object.zoom;
+
+ const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 );
+ mouseAfter.unproject( this.object );
+
+ this.object.position.sub( mouseAfter ).add( mouseBefore );
+ this.object.updateMatrixWorld();
+
+ newRadius = _v.length();
+
+ } else {
+
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
+ this.zoomToCursor = false;
+
+ }
+
+ // handle the placement of the target
+ if ( newRadius !== null ) {
+
+ if ( this.screenSpacePanning ) {
+
+ // position the orbit target in front of the new camera position
+ this.target.set( 0, 0, - 1 )
+ .transformDirection( this.object.matrix )
+ .multiplyScalar( newRadius )
+ .add( this.object.position );
+
+ } else {
+
+ // get the ray and translation plane to compute target
+ _ray.origin.copy( this.object.position );
+ _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix );
+
+ // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
+ // extremely large values
+ if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) {
+
+ this.object.lookAt( this.target );
+
+ } else {
+
+ _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target );
+ _ray.intersectPlane( _plane, this.target );
+
+ }
+
+ }
+
+ }
+
+ } else if ( this.object.isOrthographicCamera ) {
+
+ const prevZoom = this.object.zoom;
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
+
+ if ( prevZoom !== this.object.zoom ) {
+
+ this.object.updateProjectionMatrix();
+ zoomChanged = true;
+
+ }
+
+ }
+
+ this._scale = 1;
+ this._performCursorZoom = false;
+
+ // update condition is:
+ // min(camera displacement, camera rotation in radians)^2 > EPS
+ // using small-angle approximation cos(x/2) = 1 - x^2 / 8
+
+ if ( zoomChanged ||
+ this._lastPosition.distanceToSquared( this.object.position ) > _EPS ||
+ 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS ||
+ this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) {
+
+ this.dispatchEvent( _changeEvent );
+
+ this._lastPosition.copy( this.object.position );
+ this._lastQuaternion.copy( this.object.quaternion );
+ this._lastTargetPosition.copy( this.target );
+
+ return true;
+
+ }
+
+ return false;
+
+ }
+
+ _getAutoRotationAngle( deltaTime ) {
+
+ if ( deltaTime !== null ) {
+
+ return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime;
+
+ } else {
+
+ return _twoPI / 60 / 60 * this.autoRotateSpeed;
+
+ }
+
+ }
+
+ _getZoomScale( delta ) {
+
+ const normalizedDelta = Math.abs( delta * 0.01 );
+ return Math.pow( 0.95, this.zoomSpeed * normalizedDelta );
+
+ }
+
+ _rotateLeft( angle ) {
+
+ this._sphericalDelta.theta -= angle;
+
+ }
+
+ _rotateUp( angle ) {
+
+ this._sphericalDelta.phi -= angle;
+
+ }
+
+ _panLeft( distance, objectMatrix ) {
+
+ _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
+ _v.multiplyScalar( - distance );
+
+ this._panOffset.add( _v );
+
+ }
+
+ _panUp( distance, objectMatrix ) {
+
+ if ( this.screenSpacePanning === true ) {
+
+ _v.setFromMatrixColumn( objectMatrix, 1 );
+
+ } else {
+
+ _v.setFromMatrixColumn( objectMatrix, 0 );
+ _v.crossVectors( this.object.up, _v );
+
+ }
+
+ _v.multiplyScalar( distance );
+
+ this._panOffset.add( _v );
+
+ }
+
+ // deltaX and deltaY are in pixels; right and down are positive
+ _pan( deltaX, deltaY ) {
+
+ const element = this.domElement;
+
+ if ( this.object.isPerspectiveCamera ) {
+
+ // perspective
+ const position = this.object.position;
+ _v.copy( position ).sub( this.target );
+ let targetDistance = _v.length();
+
+ // half of the fov is center to top of screen
+ targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 );
+
+ // we use only clientHeight here so aspect ratio does not distort speed
+ this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix );
+ this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix );
+
+ } else if ( this.object.isOrthographicCamera ) {
+
+ // orthographic
+ this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix );
+ this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix );
+
+ } else {
+
+ // camera neither orthographic nor perspective
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
+ this.enablePan = false;
+
+ }
+
+ }
+
+ _dollyOut( dollyScale ) {
+
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
+
+ this._scale /= dollyScale;
+
+ } else {
+
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
+ this.enableZoom = false;
+
+ }
+
+ }
+
+ _dollyIn( dollyScale ) {
+
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
+
+ this._scale *= dollyScale;
+
+ } else {
+
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
+ this.enableZoom = false;
+
+ }
+
+ }
+
+ _updateZoomParameters( x, y ) {
+
+ if ( ! this.zoomToCursor ) {
+
+ return;
+
+ }
+
+ this._performCursorZoom = true;
+
+ const rect = this.domElement.getBoundingClientRect();
+ const dx = x - rect.left;
+ const dy = y - rect.top;
+ const w = rect.width;
+ const h = rect.height;
+
+ this._mouse.x = ( dx / w ) * 2 - 1;
+ this._mouse.y = - ( dy / h ) * 2 + 1;
+
+ this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize();
+
+ }
+
+ _clampDistance( dist ) {
+
+ return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) );
+
+ }
+
+ //
+ // event callbacks - update the object state
+ //
+
+ _handleMouseDownRotate( event ) {
+
+ this._rotateStart.set( event.clientX, event.clientY );
+
+ }
+
+ _handleMouseDownDolly( event ) {
+
+ this._updateZoomParameters( event.clientX, event.clientX );
+ this._dollyStart.set( event.clientX, event.clientY );
+
+ }
+
+ _handleMouseDownPan( event ) {
+
+ this._panStart.set( event.clientX, event.clientY );
+
+ }
+
+ _handleMouseMoveRotate( event ) {
+
+ this._rotateEnd.set( event.clientX, event.clientY );
+
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
+
+ const element = this.domElement;
+
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
+
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
+
+ this._rotateStart.copy( this._rotateEnd );
+
+ this.update();
+
+ }
+
+ _handleMouseMoveDolly( event ) {
+
+ this._dollyEnd.set( event.clientX, event.clientY );
+
+ this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart );
+
+ if ( this._dollyDelta.y > 0 ) {
+
+ this._dollyOut( this._getZoomScale( this._dollyDelta.y ) );
+
+ } else if ( this._dollyDelta.y < 0 ) {
+
+ this._dollyIn( this._getZoomScale( this._dollyDelta.y ) );
+
+ }
+
+ this._dollyStart.copy( this._dollyEnd );
+
+ this.update();
+
+ }
+
+ _handleMouseMovePan( event ) {
+
+ this._panEnd.set( event.clientX, event.clientY );
+
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
+
+ this._pan( this._panDelta.x, this._panDelta.y );
+
+ this._panStart.copy( this._panEnd );
+
+ this.update();
+
+ }
+
+ _handleMouseWheel( event ) {
+
+ this._updateZoomParameters( event.clientX, event.clientY );
+
+ if ( event.deltaY < 0 ) {
+
+ this._dollyIn( this._getZoomScale( event.deltaY ) );
+
+ } else if ( event.deltaY > 0 ) {
+
+ this._dollyOut( this._getZoomScale( event.deltaY ) );
+
+ }
+
+ this.update();
+
+ }
+
+ _handleKeyDown( event ) {
+
+ let needsUpdate = false;
+
+ switch ( event.code ) {
+
+ case this.keys.UP:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateUp( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( 0, this.keyPanSpeed );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ case this.keys.BOTTOM:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateUp( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( 0, - this.keyPanSpeed );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ case this.keys.LEFT:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateLeft( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( this.keyPanSpeed, 0 );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ case this.keys.RIGHT:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateLeft( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( - this.keyPanSpeed, 0 );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ }
+
+ if ( needsUpdate ) {
+
+ // prevent the browser from scrolling on cursor keys
+ event.preventDefault();
+
+ this.update();
+
+ }
+
+
+ }
+
+ _handleTouchStartRotate( event ) {
+
+ if ( this._pointers.length === 1 ) {
+
+ this._rotateStart.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._rotateStart.set( x, y );
+
+ }
+
+ }
+
+ _handleTouchStartPan( event ) {
+
+ if ( this._pointers.length === 1 ) {
+
+ this._panStart.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._panStart.set( x, y );
+
+ }
+
+ }
+
+ _handleTouchStartDolly( event ) {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const dx = event.pageX - position.x;
+ const dy = event.pageY - position.y;
+
+ const distance = Math.sqrt( dx * dx + dy * dy );
+
+ this._dollyStart.set( 0, distance );
+
+ }
+
+ _handleTouchStartDollyPan( event ) {
+
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
+
+ if ( this.enablePan ) this._handleTouchStartPan( event );
+
+ }
+
+ _handleTouchStartDollyRotate( event ) {
+
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
+
+ if ( this.enableRotate ) this._handleTouchStartRotate( event );
+
+ }
+
+ _handleTouchMoveRotate( event ) {
+
+ if ( this._pointers.length == 1 ) {
+
+ this._rotateEnd.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._rotateEnd.set( x, y );
+
+ }
+
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
+
+ const element = this.domElement;
+
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
+
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
+
+ this._rotateStart.copy( this._rotateEnd );
+
+ }
+
+ _handleTouchMovePan( event ) {
+
+ if ( this._pointers.length === 1 ) {
+
+ this._panEnd.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._panEnd.set( x, y );
+
+ }
+
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
+
+ this._pan( this._panDelta.x, this._panDelta.y );
+
+ this._panStart.copy( this._panEnd );
+
+ }
+
+ _handleTouchMoveDolly( event ) {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const dx = event.pageX - position.x;
+ const dy = event.pageY - position.y;
+
+ const distance = Math.sqrt( dx * dx + dy * dy );
+
+ this._dollyEnd.set( 0, distance );
+
+ this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) );
+
+ this._dollyOut( this._dollyDelta.y );
+
+ this._dollyStart.copy( this._dollyEnd );
+
+ const centerX = ( event.pageX + position.x ) * 0.5;
+ const centerY = ( event.pageY + position.y ) * 0.5;
+
+ this._updateZoomParameters( centerX, centerY );
+
+ }
+
+ _handleTouchMoveDollyPan( event ) {
+
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
+
+ if ( this.enablePan ) this._handleTouchMovePan( event );
+
+ }
+
+ _handleTouchMoveDollyRotate( event ) {
+
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
+
+ if ( this.enableRotate ) this._handleTouchMoveRotate( event );
+
+ }
+
+ // pointers
+
+ _addPointer( event ) {
+
+ this._pointers.push( event.pointerId );
+
+ }
+
+ _removePointer( event ) {
+
+ delete this._pointerPositions[ event.pointerId ];
+
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
+
+ if ( this._pointers[ i ] == event.pointerId ) {
+
+ this._pointers.splice( i, 1 );
+ return;
+
+ }
+
+ }
+
+ }
+
+ _isTrackingPointer( event ) {
+
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
+
+ if ( this._pointers[ i ] == event.pointerId ) return true;
+
+ }
+
+ return false;
+
+ }
+
+ _trackPointer( event ) {
+
+ let position = this._pointerPositions[ event.pointerId ];
+
+ if ( position === undefined ) {
+
+ position = new Vector2();
+ this._pointerPositions[ event.pointerId ] = position;
+
+ }
+
+ position.set( event.pageX, event.pageY );
+
+ }
+
+ _getSecondPointerPosition( event ) {
+
+ const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ];
+
+ return this._pointerPositions[ pointerId ];
+
+ }
+
+ //
+
+ _customWheelEvent( event ) {
+
+ const mode = event.deltaMode;
+
+ // minimal wheel event altered to meet delta-zoom demand
+ const newEvent = {
+ clientX: event.clientX,
+ clientY: event.clientY,
+ deltaY: event.deltaY,
+ };
+
+ switch ( mode ) {
+
+ case 1: // LINE_MODE
+ newEvent.deltaY *= 16;
+ break;
+
+ case 2: // PAGE_MODE
+ newEvent.deltaY *= 100;
+ break;
+
+ }
+
+ // detect if event was triggered by pinching
+ if ( event.ctrlKey && ! this._controlActive ) {
+
+ newEvent.deltaY *= 10;
+
+ }
+
+ return newEvent;
+
+ }
+
+}
+
+function onPointerDown( event ) {
+
+ if ( this.enabled === false ) return;
+
+ if ( this._pointers.length === 0 ) {
+
+ this.domElement.setPointerCapture( event.pointerId );
+
+ this.domElement.ownerDocument.addEventListener( 'pointermove', this._onPointerMove );
+ this.domElement.ownerDocument.addEventListener( 'pointerup', this._onPointerUp );
+
+ }
+
+ //
+
+ if ( this._isTrackingPointer( event ) ) return;
+
+ //
+
+ this._addPointer( event );
+
+ if ( event.pointerType === 'touch' ) {
+
+ this._onTouchStart( event );
+
+ } else {
+
+ this._onMouseDown( event );
+
+ }
+
+ if ( this._cursorStyle === 'grab' ) {
+
+ this.domElement.style.cursor = 'grabbing';
+
+ }
+
+}
+
+function onPointerMove( event ) {
+
+ if ( this.enabled === false ) return;
+
+ if ( event.pointerType === 'touch' ) {
+
+ this._onTouchMove( event );
+
+ } else {
+
+ this._onMouseMove( event );
+
+ }
+
+}
+
+function onPointerUp( event ) {
+
+ this._removePointer( event );
+
+ switch ( this._pointers.length ) {
+
+ case 0:
+
+ this.domElement.releasePointerCapture( event.pointerId );
+
+ this.domElement.ownerDocument.removeEventListener( 'pointermove', this._onPointerMove );
+ this.domElement.ownerDocument.removeEventListener( 'pointerup', this._onPointerUp );
+
+ this.dispatchEvent( _endEvent );
+
+ this.state = _STATE.NONE;
+
+ if ( this._cursorStyle === 'grab' ) {
+
+ this.domElement.style.cursor = 'grab';
+
+ }
+
+ break;
+
+ case 1:
+
+ const pointerId = this._pointers[ 0 ];
+ const position = this._pointerPositions[ pointerId ];
+
+ // minimal placeholder event - allows state correction on pointer-up
+ this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } );
+
+ break;
+
+ }
+
+}
+
+function onMouseDown( event ) {
+
+ let mouseAction;
+
+ switch ( event.button ) {
+
+ case 0:
+
+ mouseAction = this.mouseButtons.LEFT;
+ break;
+
+ case 1:
+
+ mouseAction = this.mouseButtons.MIDDLE;
+ break;
+
+ case 2:
+
+ mouseAction = this.mouseButtons.RIGHT;
+ break;
+
+ default:
+
+ mouseAction = - 1;
+
+ }
+
+ switch ( mouseAction ) {
+
+ case MOUSE.DOLLY:
+
+ if ( this.enableZoom === false ) return;
+
+ this._handleMouseDownDolly( event );
+
+ this.state = _STATE.DOLLY;
+
+ break;
+
+ case MOUSE.ROTATE:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enablePan === false ) return;
+
+ this._handleMouseDownPan( event );
+
+ this.state = _STATE.PAN;
+
+ } else {
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleMouseDownRotate( event );
+
+ this.state = _STATE.ROTATE;
+
+ }
+
+ break;
+
+ case MOUSE.PAN:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleMouseDownRotate( event );
+
+ this.state = _STATE.ROTATE;
+
+ } else {
+
+ if ( this.enablePan === false ) return;
+
+ this._handleMouseDownPan( event );
+
+ this.state = _STATE.PAN;
+
+ }
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ if ( this.state !== _STATE.NONE ) {
+
+ this.dispatchEvent( _startEvent );
+
+ }
+
+}
+
+function onMouseMove( event ) {
+
+ switch ( this.state ) {
+
+ case _STATE.ROTATE:
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleMouseMoveRotate( event );
+
+ break;
+
+ case _STATE.DOLLY:
+
+ if ( this.enableZoom === false ) return;
+
+ this._handleMouseMoveDolly( event );
+
+ break;
+
+ case _STATE.PAN:
+
+ if ( this.enablePan === false ) return;
+
+ this._handleMouseMovePan( event );
+
+ break;
+
+ }
+
+}
+
+function onMouseWheel( event ) {
+
+ if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return;
+
+ event.preventDefault();
+
+ this.dispatchEvent( _startEvent );
+
+ this._handleMouseWheel( this._customWheelEvent( event ) );
+
+ this.dispatchEvent( _endEvent );
+
+}
+
+function onKeyDown( event ) {
+
+ if ( this.enabled === false ) return;
+
+ this._handleKeyDown( event );
+
+}
+
+function onTouchStart( event ) {
+
+ this._trackPointer( event );
+
+ switch ( this._pointers.length ) {
+
+ case 1:
+
+ switch ( this.touches.ONE ) {
+
+ case TOUCH.ROTATE:
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleTouchStartRotate( event );
+
+ this.state = _STATE.TOUCH_ROTATE;
+
+ break;
+
+ case TOUCH.PAN:
+
+ if ( this.enablePan === false ) return;
+
+ this._handleTouchStartPan( event );
+
+ this.state = _STATE.TOUCH_PAN;
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ break;
+
+ case 2:
+
+ switch ( this.touches.TWO ) {
+
+ case TOUCH.DOLLY_PAN:
+
+ if ( this.enableZoom === false && this.enablePan === false ) return;
+
+ this._handleTouchStartDollyPan( event );
+
+ this.state = _STATE.TOUCH_DOLLY_PAN;
+
+ break;
+
+ case TOUCH.DOLLY_ROTATE:
+
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
+
+ this._handleTouchStartDollyRotate( event );
+
+ this.state = _STATE.TOUCH_DOLLY_ROTATE;
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ if ( this.state !== _STATE.NONE ) {
+
+ this.dispatchEvent( _startEvent );
+
+ }
+
+}
+
+function onTouchMove( event ) {
+
+ this._trackPointer( event );
+
+ switch ( this.state ) {
+
+ case _STATE.TOUCH_ROTATE:
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleTouchMoveRotate( event );
+
+ this.update();
+
+ break;
+
+ case _STATE.TOUCH_PAN:
+
+ if ( this.enablePan === false ) return;
+
+ this._handleTouchMovePan( event );
+
+ this.update();
+
+ break;
+
+ case _STATE.TOUCH_DOLLY_PAN:
+
+ if ( this.enableZoom === false && this.enablePan === false ) return;
+
+ this._handleTouchMoveDollyPan( event );
+
+ this.update();
+
+ break;
+
+ case _STATE.TOUCH_DOLLY_ROTATE:
+
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
+
+ this._handleTouchMoveDollyRotate( event );
+
+ this.update();
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+}
+
+function onContextMenu( event ) {
+
+ if ( this.enabled === false ) return;
+
+ event.preventDefault();
+
+}
+
+function interceptControlDown( event ) {
+
+ if ( event.key === 'Control' ) {
+
+ this._controlActive = true;
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+
+ document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
+
+ }
+
+}
+
+function interceptControlUp( event ) {
+
+ if ( event.key === 'Control' ) {
+
+ this._controlActive = false;
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+
+ document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
+
+ }
+
+}
+
+export { OrbitControls };
diff --git a/src/core/static/libs/SkeletonUtils-0.184.0.js b/src/core/static/libs/SkeletonUtils-0.184.0.js
new file mode 100644
index 000000000..836c2e2bf
--- /dev/null
+++ b/src/core/static/libs/SkeletonUtils-0.184.0.js
@@ -0,0 +1,496 @@
+import {
+ AnimationClip,
+ AnimationMixer,
+ Matrix4,
+ Quaternion,
+ QuaternionKeyframeTrack,
+ SkeletonHelper,
+ Vector3,
+ VectorKeyframeTrack
+} from 'three';
+
+/**
+ * @module SkeletonUtils
+ * @three_import import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
+ */
+
+function getBoneName( bone, options ) {
+
+ if ( options.getBoneName !== undefined ) {
+
+ return options.getBoneName( bone );
+
+ }
+
+ return options.names[ bone.name ];
+
+}
+
+/**
+ * Retargets the skeleton from the given source to the target.
+ *
+ * Both `target` and `source` can be a 3D object with a skeleton property (e.g. a skinned mesh)
+ * or a {@link Skeleton} directly.
+ *
+ * @param {Object3D|Skeleton} target - The target object.
+ * @param {Object3D|Skeleton} source - The source object.
+ * @param {module:SkeletonUtils~RetargetOptions} options - The options.
+ */
+function retarget( target, source, options = {} ) {
+
+ const quat = new Quaternion(),
+ scale = new Vector3(),
+ relativeMatrix = new Matrix4(),
+ globalMatrix = new Matrix4();
+
+ options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true;
+ options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true;
+ options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;
+ options.hip = options.hip !== undefined ? options.hip : 'hip';
+ options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3( 1, 1, 1 );
+ options.scale = options.scale !== undefined ? options.scale : 1;
+ options.names = options.names || {};
+
+ const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),
+ bones = target.isObject3D ? target.skeleton.bones : getBones( target );
+
+ let bone, name, boneTo,
+ bonesPosition;
+
+ // reset bones
+
+ if ( target.isObject3D ) {
+
+ target.skeleton.pose();
+
+ } else {
+
+ options.useTargetMatrix = true;
+ options.preserveBoneMatrix = false;
+
+ }
+
+ if ( options.preserveBonePositions ) {
+
+ bonesPosition = [];
+
+ for ( let i = 0; i < bones.length; i ++ ) {
+
+ bonesPosition.push( bones[ i ].position.clone() );
+
+ }
+
+ }
+
+ if ( options.preserveBoneMatrix ) {
+
+ // reset matrix
+
+ target.updateMatrixWorld();
+
+ target.matrixWorld.identity();
+
+ // reset children matrix
+
+ for ( let i = 0; i < target.children.length; ++ i ) {
+
+ target.children[ i ].updateMatrixWorld( true );
+
+ }
+
+ }
+
+ for ( let i = 0; i < bones.length; ++ i ) {
+
+ bone = bones[ i ];
+ name = getBoneName( bone, options );
+
+ boneTo = getBoneByName( name, sourceBones );
+
+ globalMatrix.copy( bone.matrixWorld );
+
+ if ( boneTo ) {
+
+ boneTo.updateMatrixWorld();
+
+ if ( options.useTargetMatrix ) {
+
+ relativeMatrix.copy( boneTo.matrixWorld );
+
+ } else {
+
+ relativeMatrix.copy( target.matrixWorld ).invert();
+ relativeMatrix.multiply( boneTo.matrixWorld );
+
+ }
+
+ // ignore scale to extract rotation
+
+ scale.setFromMatrixScale( relativeMatrix );
+ relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );
+
+ // apply to global matrix
+
+ globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );
+
+ if ( target.isObject3D ) {
+
+ if ( options.localOffsets ) {
+
+ if ( options.localOffsets[ bone.name ] ) {
+
+ globalMatrix.multiply( options.localOffsets[ bone.name ] );
+
+ }
+
+ }
+
+ }
+
+ globalMatrix.copyPosition( relativeMatrix );
+
+ }
+
+ if ( name === options.hip ) {
+
+ globalMatrix.elements[ 12 ] *= options.scale * options.hipInfluence.x;
+ globalMatrix.elements[ 13 ] *= options.scale * options.hipInfluence.y;
+ globalMatrix.elements[ 14 ] *= options.scale * options.hipInfluence.z;
+
+ if ( options.hipPosition !== undefined ) {
+
+ globalMatrix.elements[ 12 ] += options.hipPosition.x * options.scale;
+ globalMatrix.elements[ 13 ] += options.hipPosition.y * options.scale;
+ globalMatrix.elements[ 14 ] += options.hipPosition.z * options.scale;
+
+ }
+
+ }
+
+ if ( bone.parent ) {
+
+ bone.matrix.copy( bone.parent.matrixWorld ).invert();
+ bone.matrix.multiply( globalMatrix );
+
+ } else {
+
+ bone.matrix.copy( globalMatrix );
+
+ }
+
+ bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
+
+ bone.updateMatrixWorld();
+
+ }
+
+ if ( options.preserveBonePositions ) {
+
+ for ( let i = 0; i < bones.length; ++ i ) {
+
+ bone = bones[ i ];
+ name = getBoneName( bone, options ) || bone.name;
+
+ if ( name !== options.hip ) {
+
+ bone.position.copy( bonesPosition[ i ] );
+
+ }
+
+ }
+
+ }
+
+ if ( options.preserveBoneMatrix ) {
+
+ // restore matrix
+
+ target.updateMatrixWorld( true );
+
+ }
+
+}
+
+/**
+ * Retargets the animation clip of the source to the target 3D object.
+ *
+ * The `source` can be a 3D object with a skeleton property (e.g. a skinned mesh)
+ * or a {@link Skeleton} directly.
+ *
+ * @param {Object3D} target - The target 3D object. Must have a `skeleton` property.
+ * @param {Object3D|Skeleton} source - The source object.
+ * @param {AnimationClip} clip - The animation clip.
+ * @param {module:SkeletonUtils~RetargetOptions} options - The options.
+ * @return {AnimationClip} The retargeted animation clip.
+ */
+function retargetClip( target, source, clip, options = {} ) {
+
+ options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;
+
+ // Calculate the fps from the source clip based on the track with the most frames, unless fps is already provided.
+ options.fps = options.fps !== undefined ? options.fps : ( Math.max( ...clip.tracks.map( track => track.times.length ) ) / clip.duration );
+ options.names = options.names || [];
+
+ if ( ! source.isObject3D ) {
+
+ source = getHelperFromSkeleton( source );
+
+ }
+
+ const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),
+ delta = clip.duration / ( numFrames - 1 ),
+ convertedTracks = [],
+ mixer = new AnimationMixer( source ),
+ bones = getBones( target.skeleton ),
+ boneDatas = [];
+
+ let positionOffset,
+ bone, boneTo, boneData,
+ name;
+
+ mixer.clipAction( clip ).play();
+
+ // trim
+
+ let start = 0, end = numFrames;
+
+ if ( options.trim !== undefined ) {
+
+ start = Math.round( options.trim[ 0 ] * options.fps );
+ end = Math.min( Math.round( options.trim[ 1 ] * options.fps ), numFrames ) - start;
+
+ mixer.update( options.trim[ 0 ] );
+
+ } else {
+
+ mixer.update( 0 );
+
+ }
+
+ source.updateMatrixWorld();
+
+ //
+
+ for ( let frame = 0; frame < end; ++ frame ) {
+
+ const time = frame * delta;
+
+ retarget( target, source, options );
+
+ for ( let j = 0; j < bones.length; ++ j ) {
+
+ bone = bones[ j ];
+ name = getBoneName( bone, options ) || bone.name;
+ boneTo = getBoneByName( name, source.skeleton );
+
+ if ( boneTo ) {
+
+ boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };
+
+ if ( options.hip === name ) {
+
+ if ( ! boneData.pos ) {
+
+ boneData.pos = {
+ times: new Float32Array( end ),
+ values: new Float32Array( end * 3 )
+ };
+
+ }
+
+ if ( options.useFirstFramePosition ) {
+
+ if ( frame === 0 ) {
+
+ positionOffset = bone.position.clone();
+
+ }
+
+ bone.position.sub( positionOffset );
+
+ }
+
+ boneData.pos.times[ frame ] = time;
+
+ bone.position.toArray( boneData.pos.values, frame * 3 );
+
+ }
+
+ if ( ! boneData.quat ) {
+
+ boneData.quat = {
+ times: new Float32Array( end ),
+ values: new Float32Array( end * 4 )
+ };
+
+ }
+
+ boneData.quat.times[ frame ] = time;
+
+ bone.quaternion.toArray( boneData.quat.values, frame * 4 );
+
+ }
+
+ }
+
+ if ( frame === end - 2 ) {
+
+ // last mixer update before final loop iteration
+ // make sure we do not go over or equal to clip duration
+ mixer.update( delta - 0.0000001 );
+
+ } else {
+
+ mixer.update( delta );
+
+ }
+
+ source.updateMatrixWorld();
+
+ }
+
+ for ( let i = 0; i < boneDatas.length; ++ i ) {
+
+ boneData = boneDatas[ i ];
+
+ if ( boneData ) {
+
+ if ( boneData.pos ) {
+
+ convertedTracks.push( new VectorKeyframeTrack(
+ '.bones[' + boneData.bone.name + '].position',
+ boneData.pos.times,
+ boneData.pos.values
+ ) );
+
+ }
+
+ convertedTracks.push( new QuaternionKeyframeTrack(
+ '.bones[' + boneData.bone.name + '].quaternion',
+ boneData.quat.times,
+ boneData.quat.values
+ ) );
+
+ }
+
+ }
+
+ mixer.uncacheAction( clip );
+
+ return new AnimationClip( clip.name, - 1, convertedTracks );
+
+}
+
+/**
+ * Clones the given 3D object and its descendants, ensuring that any `SkinnedMesh` instances are
+ * correctly associated with their bones. Bones are also cloned, and must be descendants of the
+ * object passed to this method. Other data, like geometries and materials, are reused by reference.
+ *
+ * @param {Object3D} source - The 3D object to clone.
+ * @return {Object3D} The cloned 3D object.
+ */
+function clone( source ) {
+
+ const sourceLookup = new Map();
+ const cloneLookup = new Map();
+
+ const clone = source.clone();
+
+ parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {
+
+ sourceLookup.set( clonedNode, sourceNode );
+ cloneLookup.set( sourceNode, clonedNode );
+
+ } );
+
+ clone.traverse( function ( node ) {
+
+ if ( ! node.isSkinnedMesh ) return;
+
+ const clonedMesh = node;
+ const sourceMesh = sourceLookup.get( node );
+ const sourceBones = sourceMesh.skeleton.bones;
+
+ clonedMesh.skeleton = sourceMesh.skeleton.clone();
+ clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );
+
+ clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {
+
+ return cloneLookup.get( bone );
+
+ } );
+
+ clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );
+
+ } );
+
+ return clone;
+
+}
+
+// internal helper
+
+function getBoneByName( name, skeleton ) {
+
+ for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {
+
+ if ( name === bones[ i ].name )
+
+ return bones[ i ];
+
+ }
+
+}
+
+function getBones( skeleton ) {
+
+ return Array.isArray( skeleton ) ? skeleton : skeleton.bones;
+
+}
+
+
+function getHelperFromSkeleton( skeleton ) {
+
+ const source = new SkeletonHelper( skeleton.bones[ 0 ] );
+ source.skeleton = skeleton;
+
+ return source;
+
+}
+
+function parallelTraverse( a, b, callback ) {
+
+ callback( a, b );
+
+ for ( let i = 0; i < a.children.length; i ++ ) {
+
+ parallelTraverse( a.children[ i ], b.children[ i ], callback );
+
+ }
+
+}
+
+/**
+ * Retarget options of `SkeletonUtils`.
+ *
+ * @typedef {Object} module:SkeletonUtils~RetargetOptions
+ * @property {boolean} [useFirstFramePosition=false] - Whether to use the position of the first frame or not.
+ * @property {number} [fps] - The FPS of the clip.
+ * @property {Object} [names] - A dictionary for mapping target to source bone names.
+ * @property {function(string):string} [getBoneName] - A function for mapping bone names. Alternative to `names`.
+ * @property {Array} [trim] - Whether to trim the clip or not. If set the array should hold two values for the start and end.
+ * @property {boolean} [preserveBoneMatrix=true] - Whether to preserve bone matrices or not.
+ * @property {boolean} [preserveBonePositions=true] - Whether to preserve bone positions or not.
+ * @property {boolean} [useTargetMatrix=false] - Whether to use the target matrix or not.
+ * @property {string} [hip='hip'] - The name of the source's hip bone.
+ * @property {Vector3} [hipInfluence=(1,1,1)] - The hip influence.
+ * @property {number} [scale=1] - The scale.
+ * @property {Object} [localOffsets] - Per-bone local offset matrices, keyed by bone name.
+ * @property {Vector3} [hipPosition] - An additional position offset applied to the hip bone.
+ **/
+
+export {
+ retarget,
+ retargetClip,
+ clone,
+};
diff --git a/src/core/tests/test_get_elements.py b/src/core/tests/test_get_elements.py
index 50a87b643..0d5ac82a5 100644
--- a/src/core/tests/test_get_elements.py
+++ b/src/core/tests/test_get_elements.py
@@ -133,7 +133,7 @@ def test_object_pagination_first_page(self):
"""Test object pagination on first page"""
self.client.login(username="testuser", password="testpass123")
- with patch.object(settings, "MODAL_PAGE_SIZE", 8):
+ with patch.object(settings, "OBJECT_MODAL_PAGE_SIZE", 8):
response = self.client.get(
reverse("get-element"),
{"element_type": "object", "page": "1"},
diff --git a/src/core/tests/test_html_thumbnail_generators.py b/src/core/tests/test_html_thumbnail_generators.py
index 58aa40f88..35e270a62 100644
--- a/src/core/tests/test_html_thumbnail_generators.py
+++ b/src/core/tests/test_html_thumbnail_generators.py
@@ -1,9 +1,8 @@
+from django.template import engines
from django.test import TestCase
from django.urls import reverse
from core.models import (
- DEFAULT_MARKER_THUMBNAIL_HEIGHT,
- DEFAULT_MARKER_THUMBNAIL_WIDTH,
ExhibitTypes,
)
from core.tests.factory import (
@@ -15,7 +14,14 @@
from core.tests.utils import get_example_object
-class TestMarkerThumbnailGenerators(TestCase):
+def render_template(template_name, context):
+ """Render a Jinja2 template with the given context."""
+ jinja_engine = engines["jinja2"]
+ template = jinja_engine.get_template(template_name)
+ return template.render(context)
+
+
+class TestMarkerThumbnailTemplates(TestCase):
def setUp(self):
self.marker = MarkerFactory(title="Test Marker", author="Test Author")
@@ -29,33 +35,41 @@ def test_marker_as_html(self):
assert " paginator.num_pages:
page = paginator.num_pages
@@ -564,13 +569,13 @@ def _get_mr_exhibit_context_data(form, edit=False):
objects = Object.objects.all().order_by("-created")
sounds = Sound.objects.all().order_by("-created")
- paginator_objects = Paginator(objects, settings.MODAL_PAGE_SIZE)
- paginator_sounds = Paginator(sounds, settings.MODAL_PAGE_SIZE)
+ paginator_objects = Paginator(objects, settings.OBJECT_MODAL_PAGE_SIZE)
+ paginator_sounds = Paginator(sounds, settings.OBJECT_MODAL_PAGE_SIZE)
context = {
"form": form,
- "objects": objects[: settings.MODAL_PAGE_SIZE],
- "sounds": sounds[: settings.MODAL_PAGE_SIZE],
+ "objects": objects[: settings.OBJECT_MODAL_PAGE_SIZE],
+ "sounds": sounds[: settings.OBJECT_MODAL_PAGE_SIZE],
"total_object_pages": paginator_objects.num_pages,
"total_sound_pages": paginator_sounds.num_pages,
}
diff --git a/src/users/jinja2/users/components/userbox.jinja2 b/src/users/jinja2/users/components/userbox.jinja2
index f2f295d06..b10813208 100644
--- a/src/users/jinja2/users/components/userbox.jinja2
+++ b/src/users/jinja2/users/components/userbox.jinja2
@@ -2,42 +2,30 @@
{% set objects_qty = objects|length %}
{% set exhibits_qty = ar_exhibits|length + mr_exhibits|length %}
{% set artworks_qty = artworks|length %}
-
-
+
+
{% if markers_qty %}
{{ markers_qty }} {{ _(" marker(s)") }}
{% else %}
{{ _("No uploads yet.") }}
{% endif %}
-
+
{% if objects_qty %}
{{ objects_qty }} {{ _(" Object(s)") }}
{% else %}
{{ _("No uploads yet.") }}
{% endif %}
-
{% if artworks_qty %}
-
+
{{ _("Jandig Artist") }}
{{ artworks_qty }} {{ _(" Artworks") }}
{% else %}
-
+
{{ _("No Artworks yet.") }}
@@ -46,14 +34,14 @@
{% endif %}
{% if exhibits_qty %}
-
+
{{ _("Jandig Curator") }}
{{ exhibits_qty }} {{ _(" Exhibits") }}
{% else %}
-
+
{{ _("No Exhibitions yet.") }}
diff --git a/src/users/jinja2/users/login.jinja2 b/src/users/jinja2/users/login.jinja2
index 1559b45a7..29344b52c 100644
--- a/src/users/jinja2/users/login.jinja2
+++ b/src/users/jinja2/users/login.jinja2
@@ -1,4 +1,4 @@
-{% extends '/core/arviewer.jinja2' %}
+{% extends '/core/focused_layout.jinja2' %}
{% block content %}
{# FIXME: maybe this can be improved #}