Visualization of geometrical shapes in Three.js using Json formatting

I am seeking help with displaying the wireframe of a parallelepiped defined by vertexes in Json format using Three.js code. Here is the code snippet I am working with:

var testCube ={
                "metadata":{
                "version":json['version'],
                "type":json['type'],
                "uvs":json['n_uvs'],
                "normals":json['n_normals'],
                "faces":json['n_faces'],
                "generator":"io_three",
                "vertices":json['n_vertices'],
                                            },
                "faces":json['faces'],
                "vertices":json['vertices'],
                "normals":json['normals'],
                "uvs":[],
                "name":json['name']}

var loader = new THREE.JSONLoader();

var model = loader.parse( testCube );

meshBox = new THREE.Mesh( model.geometry, model.materials[ 0 ] );

var geo = new THREE.EdgesGeometry( meshBox.geometry );

var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 });

var wireframe = new THREE.LineSegments( geo, mat );

scene.add( wireframe );

Currently, the visualization produced by this code looks like this:

https://i.sstatic.net/UMB39.jpg

However, I would like to achieve a visualization where both the external and internal wireframes are visible, similar to this:

https://i.sstatic.net/50KCj.png

Question: Is there a way to modify the above Three.js code to achieve a full wireframe as shown in the second image?

Update: By utilizing the function WireframeGeometry, you get the following result:

https://i.sstatic.net/8Vpxp.png

It appears that diagonals are present on each face of the mesh. Is there a different function available that does not produce these diagonals?

Thank you for any assistance provided!

Answer №1

The solution is not perfect and requires further refinement and optimization.

To create a geometrical shape that can be shared between two instances of THREE.LineSegments() representing opposite sides of a box.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-15, 10, 10);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.setScalar(10);
scene.add(light);

var box = new THREE.Mesh(new THREE.BoxGeometry(10, 5, 5, 5, 5, 5), new THREE.MeshLambertMaterial({color:"gray"}));
scene.add(box);

var material = new THREE.LineBasicMaterial({
vertexColors: THREE.VertexColors
});
var params = box.geometry.parameters;
var geometryGridXY = Grid(params.width, params.height, params.widthSegments, params.heightSegments, "yellow");
var gridXYFront = new THREE.LineSegments(geometryGridXY, material);
gridXYFront.position.z = params.depth / 2 + 0.001;
box.add(gridXYFront);
var gridXYBack = new THREE.LineSegments(geometryGridXY, material);
gridXYBack.position.z = -params.depth / 2 - 0.001;
box.add(gridXYBack);

var geometryGridYZ = Grid(params.height, params.depth, params.heightSegments, params.depthSegments, "aqua");
var gridYZLeft = new THREE.LineSegments(geometryGridYZ, material);
gridYZLeft.position.x = -params.width / 2 - 0.001;
gridYZLeft.rotation.y = -Math.PI * .5;
box.add(gridYZLeft);

render();

function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);

}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script>

function Grid(width, height, widthSegments, heightSegments, color) {

width = width || 1;
height = height || 1;
widthSegments = widthSegments || 1;
heightSegments = heightSegments || 1;
color = new THREE.Color(color !== undefined ? color : 0x444444);

var stepWidth = width / widthSegments;
var stepHeight = height / heightSegments;
var halfWidth = width / 2;
var halfHeight = height / 2;

var vertices = [],
colors = [], j = 0;

for (let i = 0, k = -halfHeight; i <= heightSegments; i++, k += stepHeight) {

vertices.push(-halfWidth, k, 0, halfWidth, k, 0);

color.toArray(colors, j); j += 3;
color.toArray(colors, j); j += 3;
}

for (let i = 0, k = -halfWidth; i <= widthSegments; i++, k += stepWidth) {

vertices.push(k, halfHeight, 0, k, -halfHeight, 0);

color.toArray(colors, j); j += 3;
color.toArray(colors, j); j += 3;
}

var geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3));
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));

return geometry;

}

</script>

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

How can we effectively manage error responses and retry a failed call in NodeJS without getting tangled in callback hell?

I am in search of an effective approach to handle the given situation. I am curious if employing promises would be a helpful solution? Situation Overview: When a call retrieves a callback, and this callback receives an error object as a parameter. My obj ...

I can't seem to get anything to show up on my React

After starting to work with routing on react.JS, I encountered a challenge where the simple products.jsx file is supposed to display a simple message upon clicking, but it's not showing anything. Here is the code from Index.JS import React from &apos ...

Tips for utilizing the standard search functionality of Select2 while also implementing a remote data source

Even though I am able to populate the dropdown from the data source, there is an issue with filtering the results using the search field at the top. If I make an AJAX request to the API, fetch the data, create <option> elements for each result, and a ...

Is there another method to retrieve event.target from a React functional component?

Currently, I am creating a form and obtaining input from a mui textfield. I have successfully stored the value of the textfield to a value object. To handle the key and value of the form fields, I have implemented an onValueChanged function. My goal is to ...

Updating the redux state in react by passing a variable from a child component to the parent

I'm currently in the process of updating my Redux state within a component by utilizing a variable that has been passed up to the component from a child, specifically through a form submission callback. The form is responsible for submitting a user&ap ...

Enhance Your Browsing Experience with this Chrome Extension for Page Interactions

Recently, I came across Chrome extensions and have been intrigued by their functionality. One question that has been on my mind is: how can I programmatically trigger a button click when the extension runs? For instance, there is a button with the id &apos ...

Issue with looping in Javascript with jQuery

Can anyone explain why this for loop returns "bob" but "undefined" for "jacob"? $(function(){ count = 1; for(x=0; x <= count; x++) { track = $('#track' + x).val(); document.write(track ...

Does Javascript support annotation? If not, what is the best way to easily switch between debug and productive modes in a declarative manner?

I have a question that has been on my mind. I have searched Google but couldn't find any helpful links, so I thought it would be best to seek advice from experts here. My main concern is whether there is a way to create annotations in JavaScript sour ...

The state in useState is failing to update correctly following selections made within the dropdown menus

I am currently facing an issue with my dropdown disabling function, which is not enabling the dropdown properly. I suspect that this is due to asynchronous problems stemming from the use of useState. const [homeSelect, setHomeSelect] = useState('Home& ...

Gulp is failing to convert SCSS files into CSS

I'm having trouble getting gulp to compile my SASS code into CSS automatically. What could be the issue? file structure: public -css --styles.css -index.html sass -styles.scss gulpfile.js package.json Gulpfile: var gulp = require('gulp') ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Node.js implementation for processing batches of data from the Youtube Data API

I'm looking to leverage the Youtube API for batch processing multiple video ids in a single request. Currently, I'm able to successfully make individual requests by appending the video id, request parameters, and API key to the following url: ? ...

What is the best way to determine which id has been clicked using jQuery?

Can someone help me figure out how to determine which button has been clicked using jQuery? Here is the HTML code I am working with: <div class="row"> <div class="col-md-6"> <div class="well " id="option_a"> </div& ...

utilize angular4 to dynamically link images from twitter based on certain conditions

Currently, I am attempting to retrieve the URL of images from tweets only if the tweet contains an image. I have been successful in fetching tweets and some images, but the issue arises when a tweet does not have an image, causing it to break and stop disp ...

Finding the nearest value by searching through data attributes using numeric values

How can I target the first div with a data-score value just above a specified user score? The code snippet I have tried doesn't seem to be working. Any suggestions? var userscore = $("#userScore").val(); var next = $("div[data-score >=" + users ...

What is the reason for instanceof Map returning false?

Utilizing the Draft.js plugin called Mention. When accessing editorState.content.entityMap.mention, I am able to retrieve the value by: mention.get('address') However, when I attempt to verify if it is a Map using: console.log('mention&a ...

Storing events from FullCalendar into a database

I have been working on implementing the following markup: Within my project, I am using a fullcalendar instance. When a user clicks on a day, it triggers the dayClick callback function which opens a bootstrap modal. The user can then enter a title, start/ ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

What is the best way to divide my discord.py balance among multiple servers?

I have implemented an economy system in my discord.py bot where users can earn coins. However, the issue is that everyone's balance (coin amount) is connected across all servers. Below is the code snippet responsible for managing the .json file: async ...

A large canvas displaying a single optimized image

Hello, I have a large image on the canvas that measures around 10,000 pixels by 10,000 pixels. I am looking for zoom in/out functionality. Can you recommend what technology I should use? Should I consider splitting the image into smaller segments like Go ...