Tips for effectively adjusting lighting in a customized shader material

Presenting a demonstration showcasing the use of a height map in three.js coupled with custom shader(s). Everything appears to be functioning smoothly now. The working demo can be found on this link. Below are the shader scripts:

<script id="vertexShader" type="x-shader/x-vertex">
        uniform sampler2D   vTexture;
        uniform float       vScale;
        uniform vec3        vLut[ 256 ];

        varying vec3        vColor;

        void main() {

            vec4 heightData = texture2D( vTexture, uv );

            // if the map is grayscale it doesn't matter if you use r, g, or b.
            float vAmount = heightData.r;

            // fetch the color from the lookup table so it gets passed to the fragment shader
            int index = int(heightData.r * 255.0);
            vColor = vLut[index];

            // move the position along the normal
            vec3 newPosition = position + normal * vScale * vAmount;

            gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
        }
    </script>

    <script id="fragmentShader" type="x-shader/x-vertex">

        varying vec3  vColor;

        void main() {

            gl_FragColor = vec4(vColor, 1.0);
        }
    </script>

The challenge lies in incorrect lighting and shading, suggesting that adjustments are needed. It is suspected that altering the vertex positions in the shader necessitates updating the vertex normals, among other potential solutions. Despite attempts to rectify the issue with various "*needsUpdating=true" methods, a conclusive solution remains elusive. Extensive exploration of three.js documentation and online resources has yet to yield a definitive resolution.

Any guidance or insights on resolving this issue would be greatly appreciated.

Answer №1

For those utilizing custom shaders, it is necessary to perform the lighting calculations within the shader itself. A helpful resource for this process can be found here: Using lights in three.js shader

Here is a comprehensive example demonstrating custom lighting (online demo):

<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min.js"> </script>
  <script id="vertShader" type="shader">
varying vec2 vUv;
varying vec3 vecPos;
varying vec3 vecNormal;

void main() {
  vUv = uv;
  // Additional calculations for lighting in the vertex shader...
</script>
  <script id="fragShader" type="shader">
precision highp float;

varying vec2 vUv;
varying vec3 vecPos;
varying vec3 vecNormal;

uniform float lightIntensity;
uniform sampler2D textureSampler;

struct PointLight {
  vec3 color;
  vec3 position; // Defining light properties
};

uniform PointLight pointLights[NUM_POINT_LIGHTS];

void main(void) {
  // Implementing basic lambertian lighting in the fragment shader...
</script>
</head>
<body style="margin: 0px;" onload="init()">
<script>
  // Initializing variables...
  var scene, camera, renderer, textureLoader, light;

  // Setting up the 3D object and functions...

  // Render scene
</script>
</body>
</html>

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

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Can a variable be assigned based on the current route being accessed?

Currently, I am using a sidenav component with the following structure: <MenuItems> <NavLink to="/contacts/new">New</NavLink> <NavLink to="/contacts/list">New (all)</NavLink> <NavLink to="/con ...

Using various conditions and operators to display or conceal HTML elements in React applications, particularly in NextJS

I am seeking ways to implement conditional logic in my React/Next.js web app to display different HTML elements. While I have managed to make it work with individual variable conditions, I am encountering difficulties when trying to show the same HTML if m ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...

JavaScript tabs function malfunctioning upon page load

I attempted to implement tabs on my website using this example: http://www.w3schools.com/howto/howto_js_tabs.asp Although everything is functioning correctly, the default tab isn't opening as expected. The tab opens, but the header color does not get ...

Tips for optimizing the speed of uploading multiple images/files from a client's browser to a server using JavaScript

We are seeking ways to enhance the file upload process in our application, particularly for managing large files. Any suggestions on accelerating this process would be greatly appreciated. ...

Is it possible to override values set in the constructor(props) in React? If not, what is the best way to set defaults that can be overwritten later?

I'm confident I know the solution to this problem because my setState({}) seems to have no effect. This is the constructor code that I currently have: constructor(props) { super(props); this.state = { percentiles: { incN ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

Is there a way to verify if the meteor.call function was executed successfully?

In my meteor/react application, I am working with two components. I need to pass a method from one component to the other: saveNewUsername(newUsername) { Meteor.call('setNewUsername', newUsername, (error) => { if(error) { ...

PHP may not be the only language that deals with website security concerns. This question on website security extends beyond just PHP and

Let's imagine we have files named "index.htm" and "routines.php". In the scenario, "index.htm" will eventually reach out to "routines.php" using JavaScript (AJAX). Now, here is the query: how can "routines.php" confirm that the request originated fr ...

When displaying text pulled from MYSQL in a div, white space is eliminated

I'm attempting to display a string that contains both spaces and line breaks. When I output the string as a value in an input field, the spaces are displayed correctly. <textarea rows={15} value={content} /> However, when I try to display ...

Issue with delayed chaining of class addition and removal in JQuery not functioning as expected

Here is the code snippet: $(document).ready(function () { $('.current-visitors').delay(3000).queue(function () { $(this).addClass('show').delay(1000).queue(function () { $(this).removeClass('sho ...

Using jQuery for Dragging and Dropping Elements within Dynamically Loaded Divs with

Is it possible to drag an element on the page into a droppable element inside an ajax loaded div? The code works fine when the droppable element is placed directly in the regular page, but not within the ajax loaded div. It seems like the issue may be rela ...

Creating a hexagonal grid pattern with the use of texture

I have conducted several experiments in the past to determine the most effective way to create large-scale hexagon grids. I attempted drawing the hexagons using THREE.Line and THREE.LineSegments. While this method was successful for small grids, the perfo ...

Is there a way to determine if any word within a given text is present in an array?

Imagine you have the following full text: var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy" And a given array like: ["Afghanistan", "Italy", "Albania", "United Arab Emirates"] How can we verify if the exact word Italy within that ent ...

JavaScript button for displaying and hiding all content in one click

I came across a tutorial on W3Schools that showed how to create collapsibles, and I thought it would be great to have buttons that could expand or collapse all at once. I've been trying to implement this feature using the code provided in the tutorial ...

Manipulating data in node.js as it arrives in separate chunks

Hey there, I am trying to make some changes to the data received from the server. All incoming data via the POST method is processed in chunks. <button id='helloButton'>Send hello!</button> <button id='whatsUpButton'>S ...

It seems like there may be an issue with the React Table Pagination in reactjs

As a newcomer to React JS, I have been utilizing react-table to create a component that can filter, sort, and paginate sample data from a JSON file. If you are interested in the tutorial I am following, you can find it here: Currently, I am encountering ...

Is there a way to properly access and interpret a .log extension file within a React component?

import React from "react"; import "./App.css"; function FileReaderComponent() { const readLogFile = () => { if (window.File && window.FileReader && window.FileList && window.Blob) { const preview = document.getElementByI ...

Is it possible to dynamically evaluate the fs argument?

When I tried to run npm run dev, I encountered the following error: An error occurred while attempting to evaluate the fs argument statically [0] 50 | // Read file and split into lines [0] 51 | var map = {}, [0] > 52 | content = fs.read ...