Save the altered aircraft shapes as JSON files, utilizing the Three.js framework

I've been working on modifying the vertices of a plane geometry in order to create new shapes. However, I've run into an issue where when I export the modified geometry as JSON, the changes I made to the vertices are not included in the exported data.

Could someone help me figure out how to properly export my new geometry as JSON while retaining all the modifications I've made?

Below is the code snippet I've been using:

var seg = 5;
var dim = 70;
var zScale = 20;
var geometry = new THREE.PlaneGeometry(dim,  dim, seg, seg );
var index = 0;

for (var gridY = 0; gridY < seg; gridY++) {
    for (var gridX = 0; gridX < seg; gridX++) {
        var z = Math.random() * zScale;
        geometry.vertices[index].z = z;
        index++;
    }
}

geometry.elementsNeedUpdate = true;
geometry.verticesNeedUpdate = true;
var expJson = geometry.toJSON();
console.log(expJson);

However, the exported JSON data currently looks like this:

{
    height: 70
    heightSegments: 5
    metadata: {
        generator: "Geometry.toJSON"
        type: "PlaneGeometry"
    },
    version: 4.4
    type: "PlaneGeometry"
    uuid: "5F071B03-15EA-43CE-B4B3-4944E13D781C"
    width: 70
    widthSegments: 5
}

Answer №1

To understand why it is necessary to convert to either THREE.Geometry or THREE.BufferGeometry for accessing raw data, visit https://github.com/mrdoob/three.js/issues/5483.


A more straightforward approach is outlined in this suggestion (from Export ThreeJS Geometry to JSON)

var rawGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
var expJson = rawGeometry.toJSON();

Alternatively, you can use:

var rawGeometry = new THREE.Geometry();
rawGeometry.merge( geometry );
var expJson = rawGeometry.toJSON();

Answer №2

This is how I tackle this issue. If anyone has a more efficient solution, feel free to share. However, this method works well for me and is quite tidy.

My approach involves creating a new geometry object and then copying the vertices and faces from the plane geometry.

var seg = 5;
var dim = 70;
var zScale = 20;
var geometry = new THREE.PlaneGeometry(dim, dim, seg, seg);
var index = 0;

for (var gridY = 0; gridY < seg; gridY++) {
    for (var gridX = 0; gridX < seg; gridX++) {
        var z = Math.random() * zScale;
        geometry.vertices[index].z = z;
        index++;
    }
}

geometry.elementsNeedUpdate = true;
geometry.verticesNeedUpdate = true;

// The following code snippet fixes the issue ---
var neoGeo = new THREE.Geometry();
neoGeo.vertices = geometry.vertices;
neoGeo.faces = geometry.faces;
neoGeo.faceVertexUvs = geometry.faceVertexUvs;
// The fix ends here ---

var expJson = neoGeo.toJSON(); // Export JSON data from the new geometry object
console.log(expJson);

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

What is the significance of XmlHttpRequest's readyState being at 2 when receiving a 200 HTTP response

Currently, I am utilizing pure JavaScript (no jQuery) to send a file to the server. The PHP script on the server returns status code 200 upon completion, but the JavaScript is interpreting it as readyState == 2. The PHP code responds with status code 200: ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

Is Next.js Dynamic Routing Failing You?

Recently, I attempted to implement Dynamic routing for a recipe app but encountered an issue where the page was not found. This problem has left me puzzled as I am fairly inexperienced with TypeScript, although not with React. // pages/recipes/[recipeId].t ...

How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far: In my App ...

React is unable to locate an import statement for Material UI components

I am facing an issue while incorporating material UI components into my React project. The error message I receive is related to an invalid import. Snippet from My Component File import React from 'react' import './middle.css' import Mi ...

Submitting HTML forms in SilverStripe using Ajax

I need to transfer data from a basic HTML form to a controller using Ajax, then handle the data and send a response back. Currently, my setup looks like this: HomePage.ss <form method="POST" class="form-horizontal submit-form" onsubmit="return checkf ...

When using jQuery, the value of an input type text field remains constant despite any alerts

My issue involves an input text used to check if the corrected values are being displayed in an alert. However, when I modify a value in the form and check if the updated value appears in the alert box, it still shows the old value. Below is the relevant ...

Sorting after grouping in AngularJS is a breeze

After using lodash.js groupBy to organize my collection, the order is correct when I log it with console.debug. However, when I try to display it in the UI using ng-repeat, the ordering gets messed up. var list = [{id:1,categoryId:1,name:test1}, ...

Looking for consistent vertical and horizontal scrolling behavior in a React project

I am in need of assistance as I lack the necessary expertise in ReactJs to transform this design. Currently, it is written in Jquery but I would like guidance on how to recreate it in ReactJs. Specifically, I want the left div with the topic for each row t ...

Execute the cucumber cli programmatically in the index.js file of a node application

Recently, I received an automation framework built in CucumberJS and Node with Selenium. However, the framework is using an outdated version of Cucumber that relies on promises. Wanting to take advantage of the latest synchronous step feature, I decided to ...

Running Handlebars using NodeJS can sometimes result in a "Cannot find module './parser'" error

After successfully creating and implementing a Handlebars template in the Browser, my next goal is to utilize the Handlebars precompiler, which requires a NodeJS module. I have already downloaded Handlebars for NodeJS along with all dependencies locally (n ...

Leveraging numerous identifiers in jQuery

I created a small jQuery script to check if the input box value is greater than 5, but I have two tags with IDs and only one of them seems to be working. <div id="register"> <form id="register"> <input id="first" type="text" /> <a ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

Comparing the benefits of using npm cache clean versus npm cache verify

Can you explain the distinction between the two commands below? npm cache clean npm cache verify Additionally, what is the purpose of the force option? I am particularly interested in how these commands work in a Windows development environment. ...

The NGINX reverse proxy fails to forward requests to an Express application

I am currently in the process of setting up a dedicated API backend for a website that operates on /mypath, but I am encountering issues with NGINX not properly proxying requests. Below is the nginx configuration located within the sites-enabled directory ...

Node.js: Verifying the user's previous login status using Passport

My current express router for users handles user logins using a token system: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var Veri ...

JavaScript: Implementing a retry mechanism for asynchronous readFile() operation

My goal is to implement a JavaScript function that reads a file, but the file needs to be downloaded first and may not be immediately available. If an attempt to access the file using readFile() fails and lands in the catch block, I want to retry the actio ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

The problem with setting headers in Node Express MySQL: Error message indicating headers cannot be set after they have been sent

I'm currently working on a project using Node.js, Express.js, and a MySQL database. I have posts stored in the database that I want to display using the Pug.js view engine. I've managed to connect to the database and render the home route success ...

Error in jQuery sortable function occurs when dragging multiple elements

When using the sortable() function on multiple lists, I encountered a persistent bug. To drag more than one item, I added the following code to the start function: e.item.siblings(".selected").appendTo(e.item); However, a new issue arose where the plac ...