Creating ID rendering and diffuse rendering effects using THREE.js

I am currently exploring the integration of an id material override function using onBeforeRender in my THREEjs application. While this is a common feature in rendering applications, it seems like I will need to create my own solution based on my research.

Here is my approach:

When I create objects:

...
      m.onBeforeRender = function (){
        if(Renderer._renderID){
            this.material = new THREE.MeshBasicMaterial(this.userData.idColor.getHex());
            this.material.needsUpdate = true;

            // Attempting to use a shader material
            //this.material = Renderer._idMat;
            //this.material.uniforms.idColor.value = this.userData.idColor;
            //this.material.uniforms.needsUpdate = true;
        }
      }
      m.onAfterRender = function (){
            if(Renderer._renderID){
                this.material = this.userData.material;
            }
      }
...

In the render loop:

...
        var idTarget = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight);
        Renderer._renderID = true;
        Renderer._renderer.render(Renderer._scene, Renderer._camera, idTarget);
        Renderer._renderID = false;
...

Currently, both the id buffer and diffuse buffer are being rendered with the diffuse material.

If anyone has any advice or suggestions, I would greatly appreciate it. Feel free to ask for more information, and I will update this post accordingly.

Answer №1

Check out the official Three.js GPU picking example here.

The approach of rendering in two different scenes with vertex colors is interesting. I believe there are multiple ways to achieve similar results without necessarily relying on changing uniforms as suggested in a comment.

There are various techniques one can use to tackle this problem.

Avoid creating new materials within tight loops, as it can have negative performance implications.

Here's an example of what not to do:

  m.onBeforeRender = function (){
    if(Renderer._renderID){
        this.material = new THREE.MeshBasicMaterial(this.userData.idColor.getHex()); //not recommended
        this.material.needsUpdate = true; //unnecessary, default behavior for new material

For a custom override or similar functionality:

const myMesh = new Mesh()
myMesh.myMaterials = [
  someRenderMaterial,
  someIDMaterial,
]

scene.traverse(o=>{if(o.myMaterials) o.material = o.myMaterials[1]})
renderer.render(scene,camera)

scene.traverse(o=>{if(o.myMaterials) o.material = o.myMaterials[0]})
renderer.render(scene,camera)

Remember, there are countless approaches you can take. Whether it's using separate scenes, custom override materials, or rendering vertex colors directly, explore different options based on your specific requirements.

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

Emphasizing specific lines using an array

There is a block of text containing multiple lines, each wrapped within a span with an incremented value at the end (like line-1, line-2, line-3, and so on) to distinguish between them. <div id="textbody"> <span id="line-1">what is love< ...

AngularJS directive scope and $compile - issue with variable not displaying any value

Encountering a small challenge with Angular that is puzzling me. I have a feeling it may be related to scope, but I'm not entirely certain. Here is the snippet of my HTML: <i class="icon-question-sign" popover data-placement="top" data-trigger="h ...

Steps to avoid IE11 prompt (Do you really want to leave this site)

In the midst of making a webpage, I find myself faced with the peculiar issue of only having a dropdown to select. To make matters worse, when attempting to navigate to the next page in IE11, a pesky message pops up. Curious about the default behavior of ...

Creating Dynamic Tables with jQuery

I have written a code to fetch values using jQuery and Ajax. The data is coming fine but I am facing an issue with populating the rows in my table. The loop doesn't seem to work properly. Here is my HTML table code: <div class="panel-body"> ...

Within the ng-repeat loop, every switch button undergoes a status change

Utilizing ng-repeat, I have implemented a feature to display multiple content with on/off buttons. However, when toggling the off button for a specific content, all button states are being changed instead of just the selected one. <div ng-repeat="setti ...

What sets srcset apart from media queries?

Can you explain the contrast between srcset and media query? In your opinion, which is more optimal and what scenarios are ideal for each? Appreciate it! ...

Is there a way to prevent this JavaScript code from deleting the initial row of my table?

Looking at the code provided, it's evident that creating and deleting new rows is a straightforward process. However, there seems to be an issue where the default/origin/first row (A-T) gets deleted along with the rest of the rows. The main requiremen ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

Tips for triggering an API request when props are updated

I've embarked on a project to create my own version of Hacker News using this API Below is the basic structure of my components: -main |--menubar |--articles |--searchbar Displayed next is my code snippet responsible for fetching data from ...

Sharing JSON data between components securely without displaying it in the URL through routing

Seeking to pass JSON through routing URL, my code in app.route.ts looks like this: {path: 'calculator', component: CalculatorComponent,data : {some_data : null}}, The code used to route the data is as follows: this.router.navigate(['/home ...

Experiencing issues with properly rendering the Bootstrap year calendar and encountering difficulties with the date picker functionality

Having trouble implementing the bootstrap-year-calendar on my website. The JavaScript functionality and the display of the calendar are not working as expected. I want to show the calendar horizontally like the example in the link, but it is currently dis ...

Unable to modify the .Css file for the VueJs plugin

I've been utilizing the vue-js-modal plugin and inside, there is a style.css file. I attempted to customize the modal style by making changes to this file, but even after saving my modifications and running the application, the modal page still reflec ...

Add a component to another component in real-time

Check out my StackBlitz demo: DEMO I'm attempting to insert the 'table' component into the #test section of the app component when the visualization type is 'table'. To achieve this, I am using the createTable() function which gen ...

Issue encountered while trying to load gltf file using GLTFLoader: RangeError - The typed array length specified is invalid: 4

My code can successfully load almost 100 GLTF files without any problems. However, there is one file that consistently triggers this error message: "RangeError: Invalid typed array length: 4" Do you have any insight into what might be causing this issue ...

Encountering a duplicate key error in ExpressJS collection

Whenever I try to create a new event with categories that already exist in my database, such as creating an event with the category "javascript" and then attempting to create another event with categories "javascript, html, css", I encounter the error mess ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Creating a clickable widget to manipulate an item

I am building a website using A-Frame and struggling to create a button that will reset the position of a ball with the ID "test" to 0 8 0. I have attempted to use the setAttribute script, but it is not working as expected. Below is the current JavaScript ...

What is the best way to include JSX in a separate HTML file?

Currently developing a PWA using create-react-app. Upon inspecting the index.html page, I realized there are no links to any JS files, leading me to assume that CRA injects JSX into the 'root' div of index.html. Now, my goal is to include an offl ...

The content section sits discreetly behind the sidebar

Upon loading my Bootstrap 5 webpage, the toggle button successfully moves the navbar and body section to show or hide the full sidebar. However, an issue arises where the body section goes behind the sidebar when using the toggle button. Below is a portio ...