The geometry texture in webgl seems to have disappeared following the gl.bindTexture command

In my scene, there is a textured cube that renders well until I draw a quad. When I draw the quad, the texture on the cube disappears. Here is the sequence of rendering:

  // draw the textured cube
  gl.render(scene, camera);
 
  // draw a quad on the screen for checking purposes (different texture from the cube)  
  drawQuad(tex);

The pseudo code inside the drawQuad function is as follows:

  setupVertexBuffer();
  gl.activeTexture(...);
  gl.bindTexture(...);
  gl.drawArrays(...);
  gl.bindTexture(null);

I suspect the issue lies in gl.bindTexture replacing TEXTURE0 with null or another texture. Therefore, when rendering the textured cube, its texture is either missing or incorrect. Shouldn't WebGL re-bind the texture for geometries every time before rendering?

To remedy this, I attempted to rebind the texture to the textured cube right before rendering the scene like so:

  cube.map.texture = cubeTexture;
  gl.render(scene, camera);

However, this approach did not yield the desired results.

Subsequently, I tried to backup the old texture before binding a new one in drawQuad as shown below:

const lastTex = gl.getParameter(gl.TEXTURE_BINDING_2D);

Unfortunately, the value of lastTex always turned out to be undefined, thus rendering this method ineffective as well.

What would be the most effective way to ensure that both components work correctly simultaneously?

Answer №1

When it comes to working with THREE.JS, simply relying on documentation may not always be sufficient. By diving into the source code of THREE.JS, I discovered WebGLState, which plays a crucial role in texture binding within the framework. It became evident that directly altering external texture bindings could disrupt WebGLState, leading to unforeseen complications. The solution? Implement the following approach:

  const gl = renderer.getContext();

  // Execute rendering with webgl shaders
  {
    setupVertexBuffer(...);

    gl.activeTexture(gl.TEXTURE0 + 0); // bind webgltexture tex0
    gl.bindTexture(gl.TEXTURE_2D, tex0); 
  
    gl.activeTexture(gl.TEXTURE0 + 1); // bind webgltexture tex1
    gl.bindTexture(gl.TEXTURE_2D, tex1);   

    gl.drawArrays(...);

    gl.bindTexture(gl.TEXTURE_2D, null); // deactivate slot 1

    gl.activeTexture(gl.TEXTURE0 + 0);
    gl.bindTexture(gl.TEXTURE_2D, null); // deactivate slot 0
  }

  // Notify THREE.js that no textures are currently bound to slot0 and slot1
  renderer.state.bindTexture(gl.TEXTURE_2D, null, 0);
  renderer.state.bindTexture(gl.TEXTURE_2D, null, 1);

  // Allow THREE.JS to render its scene
  renderer.render(scene, camera);

The vital aspect here lies in informing THREE.js.WebGLState about the altered texture binding for proper state management during rendering.

  renderer.state.bindTexture(gl.TEXTURE_2D, null, 0);
  renderer.state.bindTexture(gl.TEXTURE_2D, null, 1);

Task completed.

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

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

Incorporating bcryptjs alongside MongoDB

I am currently developing a feature to securely encrypt user passwords using Bcrypt for my Angular application, which is integrated with MongoDB for the backend operations. Here is the implemented code snippet: Data Model var mongoose = require('mo ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Variable for Sweet Alert Input Box

I am completely new to PHP and JavaScript, so my question is fairly straightforward... I have a JavaScript code snippet (Sweetalert2 text field) and I'm looking to capture the information entered by users in a separate PHP file using AJAX. I've b ...

Utilize a Material UI GridList to transform images into a captivating background display

Incorporating a GridList displaying a variety of images fetched from an external source, I have successfully created an ever-changing image gallery. Now, my goal is to convert this dynamic image gallery into grayscale or transparency and utilize it as a ba ...

Maintain Vue Router Query Parameters Across Parent Components

In my application, I have a component named Foo, which serves as the template for a route called app/foo. Within this component, there are child components that also act as templates for routes such as app/foo/bar and app/foo/baz. I've implemented a ...

Synchronous execution of functions in Node.js

I need to ensure that func2 is only called after func1 has completed its execution. { func1(); func2();// } However, the issue arises when func1() starts running and func2() does not wait for it to finish. This leads to a runtime error as func2() require ...

The option list in AngularJS is cleared when an option is selected

In my current project, I am developing a django-tastypie api application with angularjs as the JavaScript framework. The main part of this application involves managing curriculum objects, each containing a list of grade objects and each grade object furth ...

Tips for enhancing contrast in MUI dark theme modals

Currently, I am implementing MUI dark mode for my Next.js application. While the MUI modal functions perfectly in light mode, I am struggling with visibility issues when using it in dark mode. The contrast is not strong enough, making it difficult to disti ...

Activate JavaScript when FullCalendar detects an event overlap

Can anyone help with triggering a JavaScript function when two events overlap? I've searched online but can't seem to find a way to detect this overlap. Any assistance would be much appreciated. ...

Convert a pandas dataframe into a JSON object with nested structures

Someone raised a similar question in a different forum, which was expertly answered by user1609452 using R. However, I believe there is more to explore with this topic. Let's consider a table (MyData) that looks like this: ID Location L_size L_co ...

What influence does the number of particles have on color rendering in three.js?

Hey there, I'm currently working on creating a flame effect in a particle system. However, I've noticed that when I adjust the number of particles, the color of the flame changes. Check out the difference between 1 particle and 100 particles. As ...

Is there a way to completely remove an element from the dom once the ajax call has returned

I've been struggling to completely remove LI elements and their content, including the checkbox input, from the DOM without success. After an ajax callback, I am calling the following function, but it only removes the contents and not the element its ...

Error occurs despite successful 200 response from Ajax delete request

I've been working on setting up a simple API for my project and encountered an issue. When I send a DELETE request using jQuery Ajax, the request goes through successfully, deletes the specified entry in the database, returns a status of 200, but trig ...

Embedding various files onto a webpage using the file attribute

I came across some code that allowed me to add multiple files using a single input element on my page. The code can be found here: However, as someone who is new to JavaScript, I faced difficulties in customizing it to my needs. What I really want is to h ...

Twists and turns as I mix up Kineticjs

After scrambling my puzzle, I now need it to be rotated. Can anyone help me with this? Thanks :) fillPatternImage:imageObj, x:-pieceWidth*i/2, y:-pieceHeight*j/2, stroke: "#000000", ...

I have a query related to material-ui 4, specifically the material-ui/pickers component that is reporting an error regarding a non-existent "mask" property

Recently, I upgraded a reactjs project that uses Material-UI (mui) from version 3 to version 4 by following the recommended migration guide. In the process, I also replaced material-ui-pickers 2.2.1 with @material-ui/pickers. However, after the upgrade, t ...

Display the X button solely once text has been inputted into the textbox

I have integrated a text clearing plugin from here in my project to allow users to clear the input field by clicking on an X button. However, I want to modify the code so that the X button only appears when there is text entered in the textbox. I attempt ...

How can I prevent buttons from interfering with an onPaste event?

I've created an image modal that allows users to upload or paste an image. Everything is working well, except for the fact that the buttons on the modal are capturing the focus. This means that pasting only works if the user manually clicks outside th ...