Create a 3D rendering of an .obj file using Three.js without relying on the

I have a challenge of drawing a .obj file without loading it. Let's consider an example where the .obj file contains the following content:

v 0.1 0.2 0.3
v 0.2 0.1 0.5
vt 0.5 -1.3
vn 0.7 0.0 0.7
f 1 2 3

By reading and parsing this file, I am able to extract its data into a JavaScript object.

{
  v: [
    {x:0.1, y: 0.2, z: 0.3}
    {x:0.2, y: 0.1, z: 0.5}
  ],
  vt: [
    {u: 0.5, v: -1.3}
  ],
  vn: [
    {x: 0.7, y: 0.0, z: 0.7}
  ],
  f: [
    // ...
  ]
}

Now, my task is to visually represent this data using three.js. Despite going through the documentation, I couldn't find any relevant examples or descriptions on how to achieve this. Can anyone provide insights or methods to accomplish this?

Answer №1

One question that arises is, why choose not to utilize THREE.ObjLoader? The rationale behind this decision remains murky to me. There are numerous potential test scenarios for loading obj files, making it advantageous to opt for THREE.ObjLoader.

If, however, you are unable to employ that method, I would suggest creating a THREE.BufferGeometry. This entails generating several THREE.BufferAttribute instances from the arrays within your JavaScript object. Each vertex attribute will be represented by one THREE.BufferAttribute, along with setting the index buffer. Below is a function accomplishing these tasks:

function make_3D_object(js_object) {

    let vertices = new Float32Array(js_object.v);
    let uvs = new Float32Array(js_object.vt);
    let normals = new Float32Array(js_object.vn);

    let indices = new Uint8Array(js_object.f);

    // Ensuring 0 indexing
    for(let i = 0; i < indices.length; i++)
        indices[i]--;


    let geom = new THREE.BufferGeometry();
    geom.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
    geom.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
    geom.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));
    geom.setIndex(new THREE.BufferAttribute(indices, 1));


    let material = new THREE.MeshPhongMaterial( {
        map: js_object.texture, // Assuming texture is available
        color: new THREE.Color().setRGB(1, 1, 1),
        specular: new THREE.Color().setRGB(0, 0,0 )
    } );


    let obj_mesh = new THREE.Mesh(geom, material);

    return obj_mesh;
}

This code assumes the presence of a singular body, a solitary material containing only a texture. Additionally, it should be noted that this code has not been subjected to testing.

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 steps do I need to take to run my Angular project locally using globally installed npm packages?

I'm interested in maintaining all my packages globally, similar to how node package itself operates. For instance, if I have a package named "Highcharts" listed in my package.json file, I prefer to install it globally instead of creating a local node_ ...

Transforming Lapton images into JPEG format on the fly

I have been working on a project where I am compressing jpeg images to .lep format. Now, I have created an .exe file that can convert the .lep image back to jpeg. My goal is to write a simple JSP script that can decode the .lep image on-the-fly and displ ...

What could possibly be causing the notification to fail to function in my deferred scenario?

I'm currently delving into the world of jquery deferred and making good progress, but I have encountered a hurdle when it comes to the notify feature. In my code snippet, you will notice that I attempted to use the notify method, only to find out that ...

Ag-Grid is failing to display MenuTabs

I need help getting the columns menu tab to appear in Ag-Grid. It should be a simple task. I want both the general and columns tabs, similar to the demo shown here Currently, when I specify both tabs, only the general tab is displayed. If I specify just t ...

Numerous Data Tables on a single page with varying parameters

I'm facing a scenario where I have two dataTables on the same page. Referencing this example: https://datatables.net/examples/basic_init/multiple_tables.html Everything seems to be working fine, but both tables share common parameters such as buttons ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

Upon initial server-side rendering load in Nuxt 3, Vercel fails to transmit the client's IP address to the Laravel backend

I'm encountering an issue with my setup where the actual client's IP address is not being forwarded correctly during the initial Server-Side Rendering (SSR) load of a page. Backend: Running Laravel on a VPS Frontend: Utilizing Nuxt 3 deployed on ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

How can we merge all the values of keys within an object into a new array using ES6?

My objective is to transform dynamic data into an array based on the keys of the toolset object, which does not have a constant number of keys. { toolset:{ info1:{ event-date:{}, event-time:{}, }, info ...

Tips for troubleshooting when document.queryselector isn't functioning properly in NextJS for server-side rendering (SSR)

I encountered an issue with my circular progress bar code on a Next.js page. Whenever I try to update the "progressEndValue" variable to 67, it triggers a page refresh but doesn't reflect the new value on the progress bar. Instead, I receive the follo ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

I don't understand why the texture image is inverted in this Dart ThreeJS demonstration

Can anyone explain why the image texture in the example program provided in Dart appears to be initially upside down instead of rotated? The texture seems to be flipped at the start. Any insights on this issue? You can see the example running here. I am r ...

Problem encountered when closing a lightbox on ASP.net using C# during page load

Can you explain the events that are triggered when the ASP.NET page load event occurs? I am currently using a lightbox for some insertion tasks, and after the insertion is complete, I want the parent page to reload with the new value displayed in the gri ...

Exploring the possibilities of video textures using Three.js in combination with Google Cardboard

Looking to incorporate a video texture in Three.js by following the approach demonstrated in this example: . Additionally, I am keen on utilizing the Google Cardboard Chrome API for my site, as outlined here: . However, upon testing the program on Chrome ...

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...

Retrieving information from an object using a randomly generated identifier

Imagine having an object structured like this. var foo = { "dfsghasdgsad":{ "name":"bob", "age":"27" } }; The variable foo will consistently only have one object, but the key is dynamically created. How can I access the values "bob" and "27" ...

Why is it that a website is loading at a snail's pace on Angular?

Working on my college project has been going smoothly, except for one issue with slow loading times. It's frustrating how long it takes to load. I suspect that there might be an error in the deployment process or something else causing the delay. The ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...

What methods can I use to conceal elements of my object that do not align with my specified filter?

Currently, I have implemented a filter that searches for an object in a text field using the properties of title and name. If there are matches, the words are highlighted in yellow. I am interested in modifying this so that if there are matches, the other ...