Issue with setting .mtl properties in a custom shader in three.js

In my custom three.js application, I am loading an OBJ/MTL model for rendering. I am trying to apply a custom shader to the model, but the color and specular uniforms that I manually pass to the RawShaderMaterial are not updating correctly. Instead, they all have the same value, resulting in my model being displayed in the same color.

Below is some sample code. If there is a simple solution or a better approach, I would greatly appreciate any insights.

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath(path);
mtlLoader.load(mtlName, function(materials) {
var objLoader = new THREE.OBJLoader();
materials.preload();


objLoader.setMaterials(materials);


objLoader.setPath(path);
objLoader.load(objName, function(object) {
    if (shader) {
        object.traverse(function (child) {
            if (child instanceof THREE.Mesh) {
                var customShader = shader;
                var color = child.material["color"];
                customShader.uniforms["color"] = {type: 'v3', value: color};
                customShader.uniforms["specular"] = {type: 'v3', value: child.material["specular"]};

                child.material = customShader; 
            }
       });
    }
}

Vertex Shader: precision mediump float; precision mediump int;

    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;

    attribute vec3 position;
    attribute vec3 normal;
    attribute vec2 uv;

    varying vec3 Normal;
    varying vec2 UV;

    void main() {
        Normal = normal;
        UV = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }

Fragment Shader: precision mediump float; precision mediump int;

    uniform vec3 color;
    uniform vec3 specular;

    varying vec3 Normal;
    varying vec2 UV;

    void main() {
        gl_FragColor = vec4(color, 1.0);
    }

Answer â„–1

After some investigation, I managed to identify the root of my problem.

It turns out that the issue stemmed from incorrectly cloning my ShaderMaterial.

object.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
            var customShader = shader.clone();
            var color = child.material["color"];
            customShader.uniforms["color"] = {type: 'v3', value: color};
            customShader.uniforms["specular"] = {type: 'v3', value: child.material["specular"]};

            child.material = customShader; 
        }
   });

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

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...

Having trouble understanding why the other parts of my header are not displaying

<head> This special function runs when the webpage is loaded. <body onload="myOnload()"> A distinctive div at the top with a unique graphic <div id="header"> <img src="resumeheader.png" alt="Header" style="width:750px;h ...

Is there a way for me to access the current templating in AngularJS?

I am looking to retrieve the HTML page as a string after AngularJS has finished rendering the template. My goal is to send this content to the server. .controller('MyCtrl', ['$scope', '$location', function ( $scope, $location ...

Watching a live video stream in real-time using WebRTC with React

Here is the HTML code <video ref={videos} autoPlay ></video> <Button onClick={() => navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((mediaStream) => { videos.srcObject = mediaStream; videos.onloadedmetad ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

What is the best way to capture dynamic import errors in JavaScript?

I am currently developing a website using Next.js. My goal is to utilize dynamic import import() to load a module dynamically, even if it may not exist. If the module does not exist, I am fine with suppressing it: const Blog = async () => { let L ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

Contrast in executing an Arrow Function versus a regular Function when passing them as Props in REACTJS

Here is the component code: <SelectCampanha titulo="Preenchimento obrigatório" listaOpcoes={ category ? riskModel.filter((item) => item.CategoryType.includes(categoria) ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...

You do not have permission to access the restricted URI, error code: 1012

What is the best solution for resolving the Ajax cross site scripting issue in FireFox 3? ...

Newbie React Developer Struggling to Implement Material-UI Example in React Project, State Functioning Differently from Hooks

I am currently in the early stages of learning React and trying to create a form for a project management web application. For this, I am using material-ui library. I referred to one of the select box component examples from the material-ui documentation ...

regular expression for replacing only alphanumeric strings

I'm currently developing a tool that tags alphanumeric words based on the option selected from the right-click context menu. However, I am facing issues when a group of words containing special characters is selected. I have been using the following ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

Exploring the possibilities of ThreeJS: Fine-tuning projections and refining raycasting

In the ThreeJS sketch, there is a cube at Vector3(0.0, 0.0, 0.0) that is rotated with one edge facing the viewer. The code extracts some screen points from the left and right edges, transforms them to 3D world coordinates, and further projects them onto th ...

Utilizing a Mocking/Spying Tool in Angular Unit Testing

I have a file named myHelpers.ts which contains multiple functions: myHelpers.ts export function multiply(a, b) { return a * b; } export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; } The above file al ...

Having trouble uploading several files with Multer functionality?

I've encountered an issue with Multer in Node.js where I can't seem to select and upload multiple files. In a previous exercise, I had no trouble uploading a single file, but now I'm struggling with enabling multiple uploads. What am I mis ...

What is the best way to ensure Leaflet-Search functionality remains active even when a layerGroup is toggled off using L.control.layers

I am encountering challenges while using the Leaflet.Control.Search plugin by Stefano Cudini in conjunction with Leaflet's built-in function L.control.layers. When all layers are active, there are no issues with locating a specific area. However, wh ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

Gaining access to the isolated scope of a sibling through the same Angular directive led to a valuable discovery

I am currently working on an angularjs directive that creates a multi-select dropdown with a complex template. The directives have isolated scopes and there is a variable called open in the dropdown that toggles its visibility based on clicks. Currently, t ...