Utilizing Normal Mapping with ShaderMaterial, TangentSpace, and fromGeometry in Three.js

I've been struggling to understand normal mapping with Three.js. Despite my efforts, I can't seem to get it right.

Below is the code I've been working on:

Javascript:

var bufferGeometry = new THREE.BufferGeometry();
bufferGeometry.fromGeometry(  new THREE.BoxGeometry(2,2,2) );

var positionAttributes = bufferGeometry.getAttribute('position');
var uvAttributes = bufferGeometry.getAttribute('uv');

// Rest of the JavaScript code...

Vertex shader:

 // Vertex shader code here...

Fragment shader:

 // Fragment shader code here...

Here is the outcome:
https://i.sstatic.net/3akfc.png

However, the end result doesn't look quite right. I've referenced a tutorial at , but I'm still unable to achieve the desired effect in Three.js. Any suggestions or insights would be greatly appreciated!

Answer №1

Ensure that the tangent space matrix is correctly specified by updating it to:

mat3 toTangentSpace = mat3( tang, bitang, norm );


The structure of a 4*4 matrix is as follows:

  c0  c1  c2  c3            c0  c1  c2  c3
[ Xx  Yx  Zx  Tx ]        [  0   4   8  12 ]     
[ Xy  Yy  Zy  Ty ]        [  1   5   9  13 ]     
[ Xz  Yz  Zz  Tz ]        [  2   6  10  14 ]     
[  0   0   0   1 ]        [  3   7  11  15 ]     

In GLSL, accessing columns in this manner:

vec4 c0 = m44[0].xyzw;
vec4 c1 = m44[1].xyzw;
vec4 c2 = m44[2].xyzw;
vec4 c3 = m44[3].xyzw;

An initialization method for a 4*4 matrix involves:

mat4 m44 = mat4(c0, c1, c2, c3);

A 3*3 matrix appears like this:

                         x   y   z 
[ Xx  Yx  Zx ]        [  0   4   8 ]     
[ Xy  Yy  Zy ]        [  1   5   9 ]     
[ Xz  Yz  Zz ]        [  2   6  10 ]     

In GLSL, column access can be achieved using:

vec3 x = m33[0].xyz;
vec3 y = m33[1].xyz;
vec3 z = m33[2].xyz;

The initialization process for a 3*3 matrix looks like this:

mat3 m33 = mat3(x, y, z);


Please note, the memory layout for a 4*4 matrix is represented like this:

[ Xx, Xy, Xz, 0, Yx, Yy, Yz, 0, Zx, Zy, Zz, 0, Tx, Ty, Tz, 1 ]

And for a 3*3 matrix, the memory image is structured like this:

[ Xx, Xy, Xz, Yx, Yy, Yz, Zx, Zy, Zz, Tx, Ty, Tz ]


Refer to the following resources for further information:

  • GLSL 4×4 Matrix Fields
  • How to calculate Tangent and Binormal?
  • GLSL Programming/Vector and Matrix Operations
  • Data Type (GLSL)

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

Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result. Here is my current code: axios .post("/post ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Securing AJAX Requests: Encrypting GET and POST Requests in JavaScipt using Node.js

Looking for a way to secure ajax post and get requests using JavaScript. The process would involve: Server generates private and public key upon request Server sends the public key to client Client encrypts data with public key Server decrypts data wit ...

Discontinuing the mobx autorun feature upon componentWillUnmount

In my componentDidMount, I have the following autorun function: componentDidMount() { this.autoUpdate = autorun(() => { this.setState({ rows: generateRows(this.props.data) }) }) } Unfortunate ...

What is the best method to transfer information from a What You See Is What You Get editor to a database using Vue.js?

I have recently started using the Vue2Editor in order to streamline my process of sending text and image data to my Firebase database. However, I am encountering an issue where the entered data is not being added successfully. Previously, with traditional ...

What is the process of memory allocation for variables in Javascript?

Can you explain to me how local variables are allocated memory in JavaScript? In languages like C and C++, local variables are typically stored on the stack. Is this also the case with JavaScript, or are all variables stored in the heap? ...

Using BeautifulSoup to Retrieve JPEG from an Image Tag's Src Attribute

Struggling with scraping this webpage for personal use. I am having trouble extracting the thumbnails of each item on the page. Despite being able to see image tags containing the required .jpgs when using "inspect" to view the html DOM, I cannot find the ...

How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this: { "options":[ { "optionId":"5ebbe0f56b197f36fc472168" }, { "optionId":"5ebbe1aa6b197f36fc47216e" } ] } The goal is to filter the data in a way that ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

How can I combine an onkeypress and onclick event listener in one method?

I have two inquiries, somewhat intertwined. 1) Is it feasible to merge the 2 functions below into a more efficient function, or do I need to create a function and then call it in both event listeners? input.addEventListener("keyup", () => { if (eve ...

When the program is executed, immediately use .trigger('click')

There is a spelling game that features a grid filled with hidden words. The objective of the game is to spell out these words by clicking on the letters of the alphabet, aided by hints such as images and sounds. Players are given the word they need to spe ...

A step-by-step guide on storing JSON data into a variable using NodeJS

Just starting out with Node.js and running into an issue. I need to figure out how to extract and save data from a JSON object retrieved from the GitHub API. var http = require("http"); var express = require('express'); var app = express(); var ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...

The issue with mocking collections using JSON files in Backbone is that it is not properly triggering the success callbacks in

For my project, I am exploring the use of .json files to mock GET requests in a backbone collection. Here is an example of my sample file: [ { "id": '11111', "name": "Abdominal Discomfort", "favori ...

Receiving alerts about props passed in MUI styled components triggering React's lack of recognition

I have a unique component design that requires dynamic props to determine its styling. Here is an example: const StyledTypography = styled(Typography)( ({ myColor = "black", isLarge = false }) => ({ "&&": { fontSi ...

A current issue lies in the fact that node.js is failing to update

I'm currently working on creating a functionality that involves reading a CSV file and checking if the headers are correct before proceeding. Below is the code snippet: let validHeaders = false; fs.createReadStream(path) .pipe(csv.parse({headers : ...

How can Javascript be used to interact with buttons and select options?

Can anyone help me with creating a JavaScript code that can select an option from a drop down, click on that option, and then add it to the cart by clicking another button? So far, I have attempted the following: browser.getelementbyid("id").invokemembe ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function ...

A Python program that creates an HTML webpage

I am currently working on a Python script that, when launched on localhost with Apache, will generate an HTML page. Here is the script (test.py): #!/usr/bin/python # -*- coding: utf-8 -*- import cgitb cgitb.enable() import cgi form = cgi.FieldStorage() ...