Utilizing ObjectLoader for loading JSON featuring a BufferGeometry with multiple materials is not successful

I have successfully crafted a sphere using multiple materials in the following manner:

const materials = [
    new THREE.MeshPhongMaterial({});
    new THREE.ShaderMaterial({ visible: false});
]

const geometry = new THREE.SphereBufferGeometry(2,100,100);
geometry.addGroup(0, Infinity, 0);
geometry.addGroup(0, Infinity, 1);

const mesh = new THREE.Mesh(geometry, materials);
scene.add(mesh);

The scene, light, and camera have been defined as well (although not detailed here as they are functioning appropriately).

Initially, everything works flawlessly when the page loads.

However, when I try to export the entire scene with scene.toJSON() and then load it back in to replace the scene, I encounter an issue. Here is the code snippet I'm using for this process:

const loader = new THREE.ObjectLoader();
loader.parse(jsonObject, function(object) {

    // instance holds various elements, including the current scene
    // Hence, I swap the existing scene with the newly loaded one from the JSON

    instance.scene = object;
}

Although the scene is replaced correctly, the object does not appear (despite being sure of the correct JSON format).

I attempted creating the sphere using:

const geometry = new THREE.SphereGeometry(2,100,100);

Surprisingly, with this change, the object displays perfectly after loading the JSON.

I prefer utilizing SphereBufferGeometry(), but I am puzzled by its failure. What could be missing or incorrect in my approach?

Two examples are provided below. Both display a blank sphere, however only #2 is functional:

  1. Using SphereBufferGeometry: https://codepen.io/anon/pen/BgQmMq
  2. Using SphereGeometry: https://codepen.io/anon/pen/agBEbp

Answer №1

Your code has a couple of issues that need to be addressed.

  • When utilizing the built-in geometry generators in three.js, it is assumed that you will not alter the geometry data. However, by adding groups, you are actually making modifications that can get lost during serialization/deserialization. The recommended approach is to create a new BufferGeometry object and transfer the buffer attributes and indices over to it. This allows you to freely define new data or overwrite existing ones without any data loss.
  • Additionally, using Infinity as a value is not ideal since it cannot be serialized. Instead, it is advised to set the value representing the last vertex for non-indexed geometry or the last index for indexed geometry. I have made these corrections in your updated codepen.

Link to your updated codepen

Using three.js R105 version

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to extract text from a temporary element

Here is my HTML code: <div class="p-login-info" ng-show="loggedOut()">My text.</div> This is the corresponding JavaScript code: var e = element(by.className('p-login-info')); e.getText() .then(function(text){ var logoutText = ...

Transferring JSON data to a non-RESTful WCF service

I am looking to implement a JavaScript function that can send an object as JSON to a WCF service for saving. Here is the current JavaScript code: <script> $(document).ready(function(){ $("#submitButton").click(function() ...

Using Javascript to choose an option from a dropdown menu

const salesRepSelect = document.querySelector('select[name^="salesrep"]'); for (let option of salesRepSelect.options) { if (option.value === 'Bruce Jones') { option.selected = true; break; } } Can someone please ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

When attempting to use the POST method with a JSON body in Postgresql, I encounter an error

Encountering an error: There seems to be an issue with a JSON token at position 197 while trying to parse it. It occurs in the following code snippet: at JSON.parse () at parse (C:\Users\hp\empServers\node_modules\body-parser&bso ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Send both queries using JSON

I am trying to pass company information using Json, and I also want to pass the areas using the same method. However, I am encountering some issues. Can anyone provide assistance? if($_GET['method']=="get_all_companies"){ $query = "SELECT co ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Vue has issued a warning stating that the type check for the "eventKey" prop has failed. The expected type was a String or Number, but an Array was provided instead. Additionally, it is advised to

The code I am currently using is producing the following errors in the console output: [Vue warn]: Avoid using non-primitive value as key, use string/number value instead. [Vue warn]: Invalid prop: type check failed for prop "eventKey". Expected String, ...

object stored in an array variable

I am looking to find out if there is a way to access a variable or function of an object that has been added to an array. I want to display all the objects in the array on a web page using a function that will return a string containing their content. Thi ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...

How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this: { "options":[ { "optionId":"5ebbe0f56b197f36fc472168" }, { "optionId":"5ebbe1aa6b197f36fc47216e" } ] } The goal is to filter the data in a way that ...

Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter. var particleCount = 14, particles = new THREE.Geometry(), pMaterial = new ...

I am facing an issue with my getServerSideProps function being undefined in my Next.js application, despite using a class component. Can anyone help me troub

Hey there, I'm currently facing an issue with retrieving props using getServerSideProps. I've tried various solutions but haven't been able to make it display properly. Below is the code snippet: import React, { Component } from 'react& ...

What is the ideal project layout for a React and Node.js application?

With all the latest trends in the JS world, it can be a bit overwhelming to figure out the best way to organize files and folders for a project. While there are some examples from Facebook on GitHub, they tend to be quite basic. You can also check out som ...

Using Reactjs to bind onClick event to a list component generated dynamically

If I have a render function that resembles the following: render() { var user_rows = [] this.state.user_list.forEach((user, index) => { user_rows.push( <tr key={user}> <td><div className="bt ...

Why are my API routes being triggered during the build process of my NextJS project?

My project includes an API route that fetches data from my DataBase. This particular API route is triggered by a CRON job set up in Vercel. After each build of the project, new data gets added to the database. I suspect this might be due to NextJS pre-exe ...

Displaying JavaScript Countdown in PHP Table

I have a database table with multiple fields and I am looking to create a countdown using the integer value from one of the fields (in minutes). How can I loop through and display the countdown for each row in a PHP table utilizing these values, with the a ...