Unable to assign shader to OBJ file

Currently, I am encountering an issue with applying a new material shader (a basic normal map) to an OBJ model (a simple cube) in Three.js.
Upon attempting to do so, I receive the following error message from Three.js:

.WebGLRenderingContext: GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 2 

This section of code is responsible for loading the OBJ model and defining the material shader:

// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
    console.log(item, loaded, total);
};

var diffuse = THREE.ImageUtils.loadTexture("diffuse.jpg");
var normal = THREE.ImageUtils.loadTexture("normal.jpg");
var discplacement = THREE.ImageUtils.loadTexture("displacement.jpg");
var specular = THREE.ImageUtils.loadTexture("specular.jpg");


//

var specularColor = 0xcccccc;
var diffuseColor = 0x888888;
var ambiantColor = 0xffffff;

var shader = THREE.ShaderLib["normalmap"];
var uniforms = THREE.UniformsUtils.clone(shader.uniforms);


uniforms["enableAO"].value = true;
uniforms["enableDiffuse"].value = true;
uniforms["enableSpecular"].value = true;
uniforms["enableReflection"].value = true;
uniforms["enableDisplacement"].value = true;
uniforms["uShininess"].value = true;

uniforms["tAO"].texture = THREE.ImageUtils.loadTexture("AO.jpg");

uniforms["tNormal"].value = normal;
uniforms["uNormalScale"].value.set(1.0, 1.0);

uniforms["tSpecular"].value = normal;

uniforms["tDisplacement"].value = normal;
uniforms["uDisplacementScale"].value = 0;

uniforms["tDiffuse"].value = diffuse;

uniforms["uSpecularColor"].value.setHex(specularColor);
uniforms["uAmbientColor"].value.setHex(ambiantColor);

var parameters = {
    fragmentShader: shader.fragmentShader,
    vertexShader: shader.vertexShader,
    uniforms: shader.uniforms,
    lights: true
};
var material = new THREE.ShaderMaterial(parameters);
material.needsUpdate = true;

// When I use this snippet to load a mesh and apply the material, it functions correctly
//var geometry = new THREE.CubeGeometry(120, 120, 120);
//geometry.computeTangents();
//
//var mesh = new THREE.Mesh(geometry, material);
//scene.add( mesh );         


// OBJ Model
// However, when I attempt to load the mesh and apply the material using this portion of the code, it fails

var loader = new THREE.OBJLoader(manager);
loader.load('cube.obj', function (object) {

    object.buffersNeedUpdate = true;
    object.uvsNeedUpdate = true;

    object.traverse(function (child) {

        if (child instanceof THREE.Mesh) {

            child.material = material;
            //child.material.overdraw = true
            //child.material.map = texture;



        }

    });

scene.add(object);

});

The outcome observed: Three.js issues a warning and nothing gets displayed on the screen.

What steps can be taken to resolve this particular problem?

Answer №1

Hello there, I have a suspicion that the issue is related to the "tAO" uniform. Instead of:

uniforms["tAO"].texture = THREE.ImageUtils.loadTexture("AO.jpg");

Try changing .texture to .value

uniforms["tAO"].value = THREE.ImageUtils.loadTexture("AO.jpg");

The GL error might be due to the absence of the texture map. Other than that, the code seems to be in good shape. If nothing works, try enabling and focusing only on the normal and diffuse maps first to see if that helps you get started.

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 use an exported function in react-router-dom to redirect without requiring any parameters?

I've created a straightforward logout function that appears as follows: export const logout = () => { localStorage.removeItem('_id') localStorage.removeItem('token') localStorage.removeItem('refresh_token') re ...

Once a Javascript variable is declared for the first time, it cannot be overwritten

I am currently facing an issue with a function that should refresh the page based on the selected number: prodName="doesn't matter, not directly $.ajax related" function searchProduct() { var prodName = $("#admin-search-product").val().trim(); ...

The Raycaster.intersectObjects function in Three.js is only able to detect intersections with the front surface

My current project involves generating a world filled with blocks on the ground upon mouse click (using mouse click coordinates that I've calculated). To ensure that each new block doesn't intersect with existing ones, I implemented a check using ...

Processing images with PHP from an array using AJAX

I have designed a straightforward form for image uploading. I am storing the properties of the uploaded images in an array, and my goal is to send this array to a PHP file using ajax. However, when I attempt to access the uploaded image using $_FILES[&apos ...

I'm attempting to create a text toggle button for displaying more or less content

I am currently working on implementing a show more/show less button feature. However, the current version is not very effective as I only used slicing to hide content when the state is false and display it all when true. Now, my goal is to only show the ...

When trying to access a URL in a next.js application using the fetch() function, the router encountered an

I recently started working on a frontend project using Next.js v13.4 app router, with an additional backend. I have organized my routes and related functionalities in the api folder within the app directory. However, when I attempt to use the fetch() funct ...

Tips for transferring variables between two browser windows within the same session of Internet Explorer 11

Is there a way to prevent a parameter from displaying in the address bar and avoid storing it locally? For example, the parameter value is like vndfj/dfgdgdfg12/dg==. I attempted the following code, but it does not work on IE and Edge browsers: let data ...

Switching charset/encoding on load() using jQuery

Query: How can the encoding of a text file being loaded through jQuery's load() function be adjusted? I previously had a single page, index.html, where I consolidated all my css, js, and html content. Now, I aim to separate the header section from th ...

What is the process of including assetlinks.json in an Angular project to enable Android App Links?

Hey everyone, I could really use some assistance! I'm unsure about the specific directory to place the assetlinks.json file and what additional information needs to be included for it to function properly. I do have a SHA256 key and applicationId, so ...

A guide to filtering a JSON array by email address with JavaScript

How can I identify distinct elements in a JSON array using JavaScript? Below is the example of my JSON array. I need to determine the size of unique elements. [ { "_id": "5aaa4f8cd0ccf521304dc6bd", "email": "<a h ...

How can I ensure that I am only retrieving the first object within a "for loop" in vuejs and returning its value without getting the rest?

Why am I only able to retrieve the value of the first object in my "for loop" and not all three values as intended? var app = new Vue({ el: '#app', data: { myObj: [ {name: 'Hello', age: 10}, {name: ...

Yii - The jQuery.fn.yiiGridView function is causing an error of undefined when attempting to use the update() function

Here is the code snippet for a widget I have: $this->widget('bootstrap.widgets.TbGridView', array( 'dataProvider' => $model->search(), 'filter' => $model, 'ajaxUpdate' => true, 'a ...

What is the best way to transfer information from a single card within a collection of cards to a dialog window?

I'm facing a challenge in my CRUD application where I want to incorporate a confirmation step using a Material-UI dialog, but I'm struggling to pass the necessary data to the dialog. Currently, I have a list/grid of cards generated using .map(), ...

What is the process of importing a file as text into vite.config.js?

Within my project directory, there is a simple SCSS file that I need to access its content during the compilation process in order to transform it in vite.config.js. However, I am unsure of how to retrieve its content. I have successfully obtained the cont ...

Testing the functionality of an Angular service using unit tests

Confused about how to test a service in an Angular project that involves a small class with an observer? Can't seem to figure out why the test fails when calling the 'pop' method. Want to ensure that the public methods of this class perform ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...

Simultaneously opening the second submenu and closing the previous submenu with a height transition results in the second submenu being positioned off-screen

Sample: https://codesandbox.io/p/sandbox/navbar-k2szsq (or refer to the code snippet below) In my navbar, I have implemented multiple submenus with a height transition when the user opens or closes a submenu. However, only one submenu can be open at a tim ...

Creating visual content on a website

I'm currently working on a project where I need to showcase the results of a numerical model I am operating. My goal is to gather user input in the form of latitude/longitude coordinates, utilize php (or a similar tool) to trigger a python script that ...

Enable jquery offsetParent() function

$(document).ready(function(){ $("button").click(function(){ if ($("p").offsetParent().css("background-color") === "red") { $("p").offsetParent().css("background-color", "yellow"); } else { $("p").offsetParent().c ...

Find all instances of Javascript comments and delete them using Regular Express

Hey there! I'm currently working on removing all JavaScript comments (//) within the HTML document. Take a look at this example: <html> <img src="http://example.com/img.jpg" /> <script> //Some comments gallery: { enabled: t ...