Can multiple meshes share the same geometry while having different shaderMaterials applied to each?

After creating a single PlaneGeometry instance, I proceeded to create 200 meshes that share this geometry and each have their own unique shaderMaterial instance. Below is a simplified version of the code snippet:


...
var geom = new THREE.PlaneGeometry(10,10,2,2);
var meshes = [];
var material=null;

for (var i=0 ; i<200 ; i++)
{
   var elevations = getElevations(i); //return an array of 9 values, with different values for each mesh
   var mat = new THREE.ShaderMaterial({
               vertexShader : vsAlti, //process displacement on y coordinate of the vertex
               fragmentShader : fsAlti,
               attributes : { elevation :  { type : 'f',value : elevations }}
            };
   meshes.push(new THREE.Mesh(geometry , mat));
}
...

Despite having different elevation attribute values for each mesh in the array, it seems that only one value is being applied to all meshes. It appears that only one instance of shaderMaterial is being applied to all meshes, when the expected behavior would be for each mesh to have its own matching shader.

Edit :

You can view the jsfiddle here: http://jsfiddle.net/McNulty/L584j/119/

Answer №1

Sharing geometry while applying different materials to each mesh simultaneously is entirely feasible. Your implementation appears to be sound in this aspect. Have you confirmed that your shaders are responding correctly to varying elevation values?

If you were to generate two meshes with distinct geometries and assign them separate shader materials, would the functionality remain intact?

Answer №2

Feel free to test out this code and share your feedback on how it performs.

var geom = new THREE.PlaneGeometry(10,10,2,2);
var meshes = [];
var material=null;
var attrib = {
     elevations: {
        type: 'f',
        value: []
     }};
for (var i=0 ; i<20 ; i++){

    attrib.elevations.value[i] = (10*i) + 0.25 ; // just an example
}
var mat = new THREE.ShaderMaterial({ vertexShader : vsAlti, 
           fragmentShader : fsAlti,
           attributes : attrib });
var mesh = new THREE.Mesh(geometry , mat);
scene.add(mesh)

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

Is it mandatory for the npm install command to only be compatible with Node.js for the script

I've encountered an API that provides a JS SDK, and the instructions on its GitHub page suggest using npm install. My question is whether I need to have Node.js in order to use this SDK since it seems to be designed for it, or if I can simply work wit ...

Create a VueJS/VuetifyJS implementation inspired by the WhatsApp swipe between tabs animation

Currently, I am utilizing the VuetifyJS framework for VueJS and I am interested in replicating the swipe between tabs transition seen in WhatsApp for Android. In WhatsApp, you have the ability to swipe left or right to view a new section as you swipe. Vue ...

The time that was constructed is not a valid function

I am currently working on a puppeteer script that interacts with my browser extensions and navigates to a specific page. It clicks on a particular extension button and fills in an input. Unfortunately, I am encountering an issue with the following error me ...

The accuracy of dates in javascript may be unreliable

Currently, I am working on creating a calendar using React JS. Below is the code that generates the entire month: function generateWholeMonth(currentDate) { var result = []; var focusDate = new Date(currentDate); focusDate = new Date(focusDate. ...

Understanding the fundamentals of event handling in JavaScript

Is there a way to access the object that called the event handler within the event handler function itself? For example: marker.on('dragend', onDragEnd); In this case, marker is the object that triggers the ondragEnd function on the Dragend eve ...

Encountered an Internal Server Error (500) while attempting to create a new user through localhost:8800/api/auth/register

I'm currently working on setting up a website with registration, login, and logout functionalities using react and mysql. At the moment, I am facing some issues specifically in the registration process. When attempting to create a new user, I encounte ...

Having trouble configuring webpack for CSS Modules? You may be dealing with an invalid configuration object

Encountering an issue while setting up webpack for CSS Modules... An error message is appearing stating that the configuration object is invalid. It seems that the output path specified as "build" is not an absolute path, which is required. Below are ext ...

Associate the name of the input field with an array where the values of the input field serve as

My input fields are as follows: <input name='223' type='number' class='form-control score' value='70'> <input name='224' type='number' class='form-control score' value='65& ...

Pausing for the completion of AJAX calls within a $.each loop before proceeding with the function execution

I am looking to trigger a function only once all of the AJAX calls within my $.each loop have finished executing. What is the most effective approach to accomplish this task? function recalculateSeatingChartSeatIds() { var table_id = $(".seatingChar ...

What is the best way to extract the value from a React date picker every time the dates are modified?

Currently, I am utilizing a React library known as react-date-picker and my goal is to retrieve the date every time it is modified. Below is the default code given by the library for selecting the date from a dropdown: import React, { Component } from "r ...

Require assistance with try-catch statements

I am troubleshooting an issue with a try-catch block in my Protractor test. Take a look at the code snippet below: try { element(by.id('usernameas')).sendKeys(data); } catch(err) { console.log('error occurred'); } To test the ...

Dealing with errors when implementing an Angular 2 route guard that returns an Observable of type boolean can be a

My route guard is implemented as follows: @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private authenticationSvc: AuthenticationService) { } canActivate(): Observable<boolean> { return this. ...

The functionality to organize items appears to be malfunctioning. (Javascript)

I want to add a price sorting feature that allows users to sort by either 'high to low' or 'low to high' using a drop-down menu. The products I want to sort are the w3-containers, each representing a different product. However, nothin ...

Set the rowspan to 2 when the v-for index does not equal 2

This is the table I am working with: <table class="table table-condensed table-sm table-striped table-bordered" id="list"> <thead> <tr> <th v-for="(column, index) in columns" :key=& ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Combine div elements with identical class

Is there a way to utilize jQuery in order to enclose groups of elements with the same class within a div? I have been searching for a solution, but haven't found one yet. Here's an example of the HTML: <div class="view-content"> < ...

The back div is not retained on the second animation when flipping the card

In my card with a unique animation, clicking on the "Edit" button triggers the following actions: It smoothly transitions to the center of the screen. During this movement, it rotates by 180 degrees, revealing a blank green back content. Once the card r ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

Using document.createElement or HTML elements in JavaScript

I'm a bit confused about the different coding styles. I am interested in knowing which method is the most practical and efficient for inserting HTML tags into a document. One option is using JavaScript: document.getElementById('demoId').in ...

Indicator malfunctioning on Carousel feature

I created a carousel containing six photos, but I am encountering an issue with the carousel indicators below. The first three indicators work correctly – when clicked, they take me to the corresponding slide (e.g., clicking the 1st indicator takes me ...