The GlTF model does not appear correctly when rendered in three.js

I recently downloaded a model from Sketchfab and imported it into my scene, but unfortunately, the model does not appear correctly, especially the glass blur effect.

https://i.sstatic.net/sXppq.png

https://i.sstatic.net/A7ToY.png

Here is the code snippet I am using:

import "./sass/main.scss";

import { Scene, PerspectiveCamera, WebGLRenderer, DirectionalLight, ACESFilmicToneMapping, sRGBEncoding, Object3D, Mesh, MeshStandardMaterial, ReinhardToneMapping, AmbientLight, EquirectangularReflectionMapping,
} from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const scene = new Scene();
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new WebGLRenderer({
    canvas: document.querySelector("canvas#webgl"),
    antialias: true
});
renderer.toneMapping = ACESFilmicToneMapping;
renderer.outputEncoding = sRGBEncoding;
renderer.physicallyCorrectLights = true;
renderer.toneMappingExposure = 1
renderer.shadowMap.enabled = true;

const controls = new OrbitControls(camera, renderer.domElement);
camera.rotation.reorder("YXZ")
camera.position.set(2, 1.5, 3.5);
camera.rotation.set(-0.25, Math.PI * 0.25, 0);
renderer.setSize(window.innerWidth, window.innerHeight)

const gltfLoader = new GLTFLoader();
const rgbeLoader = new RGBELoader();

const environmentMap = await rgbeLoader.loadAsync("./assets/environment/puresky.hdr")
environmentMap.mapping = EquirectangularReflectionMapping;
scene.environment = environmentMap;

await gltfLoader.loadAsync("./assets/models/scene.gltf").then(gltf => {
    scene.add(gltf.scene);
});

mapAllElements();

function render() {

    renderer.render(scene, camera);

    requestAnimationFrame(render);
}

render();

function mapAllElements() {
    scene.traverse((child) => {
        if (child instanceof Mesh && child.material instanceof MeshStandardMaterial) {
            child.material.envMap = environmentMap;
            child.material.envMapIntensity = 1;
            child.material.needsUpdate = true;
        }
    })
}

I have tried searching online for a solution to my issue but haven't found anything helpful. I also attempted using other GLTF models from Sketchfab, but they also did not display correctly in the scene.

It's worth noting that my code utilizes the top-level-await feature, which I have enabled in the webpack.config.js file.

Answer №1

The appearance of the model is dependent on the Viewer it is loaded into. To achieve similar effects, you can generate a new material using the THREE.MeshPhysicalMaterial class. This type of material is designed to mimic realistic lighting and textures.

Here is a basic example:

scene.traverse((child) => {
    if (child instanceof Mesh && child.material instanceof MeshStandardMaterial) {
      if (child.name.includes("glass")) {
        // Create a new MeshPhysicalMaterial for the glass object
        const glassMaterial = new THREE.MeshPhysicalMaterial({
          color: 0xffffff,
          metalness: 0,
          roughness: 0.1,
          transparent: true,
          transmission: 0.9,
          opacity: 0.7,
          envMap: environmentMap,
          envMapIntensity: 1,
          side: THREE.DoubleSide,
        });
        // Update the material of the glass object
        child.material = glassMaterial;
      } else {
        // Apply the environment map to non-glass objects
        child.material.envMap = environmentMap;
        child.material.envMapIntensity = 1;
      }
      child.material.needsUpdate = true;
    }
  });
}

If you prefer not to start from scratch, you can explore WebGi, which offers a comprehensive plugin system for precise control over the rendering process.

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

The character is having trouble displaying correctly in the ajax response

I've been searching for solutions but nothing seems to help. The issue I'm facing is with reading characters from an AJAX response. How can I properly read characters that are coming from an AJAX response in the form of a JSON object? ["label" ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...

Encountered an error while running npm run dev on a Laravel Vue 3 project: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],

I am facing an issue in my Laravel 9 Vue 3 project. When I run php artisan serve and then npm run dev, I encounter the following error: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'di ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

Inject additional content into mesh using data from node server

If you're unfamiliar with OWF (Ozone Widget Framework), it's essentially a system of widgetized HTML pages that communicate through a server-based subscription service. For example, take a look at this demonstration: While I can easily add text ...

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

Determining the Nearest Form to an Element using jQuery

I developed a JavaScript/jQuery script that allows me to check all checkboxes within a form. The function works effectively, but the issue is that it checks all checkboxes on the page regardless of their form wrapper. Here is the function: function toggl ...

Jest-Native encountered an error: "SyntaxError: Unable to use import statement outside of a module"

Trying to perform unit testing using https://github.com/callstack/react-native-testing-library along with https://github.com/testing-library/jest-native. I am able to test plain JavaScript files without any issues, but I am facing an error when testing com ...

I encountered an issue where vue-toastr fails to function properly within an inertia.js environment

While working on a page with Inertia.js, I encountered an issue when trying to integrate vue-toastr into my Vue template file. Unfortunately, it doesn't seem to be functioning as expected and I'm unsure of how to resolve this issue. Any suggestio ...

Encountering a Node.js error when executing the JavaScript file

When I try to run my Node.js application using the command "node main.js" in the terminal, I encounter an error saying "Error: Cannot find module 'D:\nodeP\main.js'". This is confusing for me as I have set the environment variable path ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Leveraging jQuery within Node.js

Greetings, I am a newcomer here and I hope that my message is clear. My current challenge involves trying to incorporate jQuery into node.js, but unfortunately, all my efforts have ended in failure. I have spent hours attempting to resolve this issue to no ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Retrieving string-based JSON information

Within my text box, the user inputs strings separated by commas. These strings are split on the front end, then sent to the backend to retrieve data in JSON format. The interesting part is that when I directly entered the key of the JSON, like this, it wo ...

"Discover the best way to sort through an array of complex objects with varying levels of nesting using a specified search

I have come across similar answers, but none of them go beyond two levels deep. Therefore, I believe this is not a duplicate problem. My task is to filter an array of objects where each object may contain nested objects of unknown depth. In my data structu ...

Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section. This is an example illustrating the structure of the data: const head = { rel_data: [ { rel: &quo ...

Retrieve the visitor's IP address following the submission of an AJAX form

Currently, I am facing an issue with my HTML form and JavaScript method integration. Whenever a visitor submits the form, a JavaScript method is triggered which sends an AJAX request to a PHP file on my server. The problem arises when trying to retrieve ...

Ways to move all the elements within a given array

The code checks each variant within the variant array and displays all objects that match the condition or 'undefined' if not. However, in this code snippet, a new array is being created for each item like so: [{id: 'something'}] [{id: ...