Is there a way to effectively transfer both Vertex and Face normals to a Three.js shader?

It seems that the THREE.Geometry methods, .computeFaceNormals() & .computeVertexNormals(), assign values to a built-in attribute array called "normal."

If I want to utilize both vertex- & face-normals in one shader, I need to:

  1. Calculate face-normals
  2. Copy the results from 'normals' to a new attribute array, like 'fNormals'
  3. Compute vertex-normals
  4. Render...

Currently, following this method, my attempt looks like this:

var shader = new THREE.ShaderMaterial(
    {
        attributes: {
            fNormal: { type: "v3", value: [] }
        },
        //uniforms, vertexShader, etc...
    } );

//load a mesh & apply the shader to it...

//set up both vertex & face normals for use in the shader

mesh.geometry.computeFaceNormals();

//copy the face-normals to the 'fNormal' array:

for (var i=0; i < mesh.geometry.attributes[ 'normal' ].length; i++){
  var cloned = mesh.geometry.attributes[ 'normal' ].value[i];
  shader.attributes[ 'fNormal' ].value[i] = cloned;
}

//now compute vertex normals and store them in the 'normal' attribute:
mesh.geometry.computeVertexNormals();

EDIT: Correcting errors as I debug. Still figuring out how to handle the generated normals...

Appreciate any insights-

Answer №1

If you need access to the normals of faces, you can do so through mesh.geometry.faces[].normal.

for (let i=0; i < mesh.geometry.faces.length; i++){
    shader.attributes.fNormal.value[i] = mesh.geometry.faces[i].normal;
    //It's unnecessary to clone the normal vertex in this case
}

This method should work if you bind your attribute to the faces:

attributes: {
    fNormal: { type: "v3", value: [], boundTo: 'faces' }
},

You can see an example demonstrating how to use custom attributes in webgl_materials_wireframe

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

Initiate a button click event from the parent element situated within an Iframe

I am facing a challenge in accessing a button within an iframe. The path to the button is as follows: div.iframe-container > iframe#builder-frame > html > body > div#header > ul.header-toolbar.hide > li > span.deploy-button-group.butt ...

JavaScript: Can you clarify the value of this variable using five sets of double quotations?

Could you please review the code snippet below for me? <script type="text/javascript"> function recentpostslist(json) { document.write('<ul class="recommended">'); var i; var j; for (i = 0; i < json.feed.entry.length; i++) { ...

Verify if data is correct before refreshing user interface

When attempting to submit the HTML5 form, it stops the form submission if any required fields are missing a value or if there is another error such as type or length mismatch. The user interface then shows highlighted invalid fields and focuses on the firs ...

jQuery animation not executing as expected due to transition issues

I'm looking to create a cool effect where the previous quote disappears and a new one appears when I click on a button, all with a smooth transition effect. In my attempt below using jQuery .animate and opacity property, I'm struggling to make i ...

Tips for executing a script while updating npm version

Can a script be executed during the npm version command, after the release number has been incremented but before the git tag is created and pushed? ...

Label positioning for checkboxes

Is there a way to display the checkbox label before the actual checkbox without using the "for" attribute in the label tag? I need to maintain the specific combination of the checkbox and label elements and cannot use nested labels or place other HTML elem ...

Search for elements once they have been dynamically loaded using AJAX with the

I have a function called getItemID which searches for all the IDs under a specific parent ID (#search-output). This function works well when the ID (#test) is already loaded when the page loads. However, I am dynamically generating these IDs (#test) using ...

Vuex is exclusively eliminating the initial element

Currently, I have set up the code to remove the activeNote from the array called notes by using the DELETE_NOTE mutation. However, it seems that it only removes the first element of the array. The content of mutations.js is as follows: export const mutat ...

Mastering server requests in Angular 5

I have come across recommendations stating that server requests should be made via services and not components in order to ensure reusability of functions by other components. Ultimately, the server response is needed in the component. My query pertains t ...

Wildcard GET requests in Express cause routing issues when navigating to a React application

My project is derived from the React-Webpack boilerplate repository found at this link: (https://github.com/wallacyyy/webpack-heroku/blob/master/server.js). Initially, everything was working fine but now I want to add routing within my React application. T ...

Exploring VueJs 3: Strategies for loading and implementing actions on a component before mounting

Briefly: Can a virtual node be created outside of the DOM to preload images, seek videos... without ever being mounted in the real DOM? Detailed version: I want to ensure that the next slide appears only when it is fully initialized for a slideshow in Vu ...

How can I incorporate a child component into a separate component within Angular version 14?

Currently working with Angular 14 and facing a challenge with including a child component from another module into a standalone component. The structure of the standalone component is as follows: <div> <child-component></child-component& ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

Tips for sending a successful POST request with the MEAN stack

Currently, I am utilizing yeoman to set up a new project. My ultimate goal is to master the process of scaffolding CRUD operations. However, I have encountered an issue with a post request. For this reason, I opted for the angular-fullstack generator as I ...

Utilizing Ajax to dynamically submit specific form fields

I'm just starting out with Jquery ajax, and I'm experimenting with submitting specific fields for validation instead of the entire form. I've created a function to check if a username is available, and it's working well. However, I want ...

Ways to determine if a browser is currently loading a fresh webpage

I'm experiencing an issue with my web app where the 'safety' code triggers a page reload if the server (Socket.IO) connection becomes silent for more than 5 seconds, often due to customer site firewall or broken-proxy issues. Although the S ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

An issue has been detected in the constants.json file located in the constants-browserify

I organized my folders into client-side and server-side categories, but I failed to work from a parent folder perspective. Now, as I attempt to deploy to Heroku, I realize that I need one main folder for the deployment process. To address this issue, I dec ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

Switching the endpoint renders the middleware ineffective

I've encountered a puzzling issue with my NodeJs - Express server, which serves as the backend for my mobile application. The problem arises when I send post requests to certain endpoints like checkmail and checkusername using axios from the frontend ...