developing a shader that transitions between day and night based on the movement of a light source

I've set up a scene with a sphere illuminated by a DirectionalLight to simulate the sun shining on Earth. My goal is to incorporate a shader that displays the earth at night on the unlit portions of the globe and during the day on the lit areas. Eventually, I plan to animate the DirectionalLight moving around the globe to update the shader based on real-time shadow positions. I stumbled upon a CodePen example that partially achieves what I'm aiming for: https://codepen.io/acauamontiel/pen/yvJoVv

In the provided CodePen demo, the day/night textures depend on the camera's view relative to the globe. However, my requirement is to tie these textures to the position of the light source rather than the camera.

    constructor(selector) {
        // Constructor function code here...
    }

    // Additional functions defined for setting up the scene, camera, renderer, controls, lights, rendering loop, etc...

    get dayNightShader() {
        return {
            // Vertex and fragment shaders code here...
        }
    }

    init() {
        // Initialization code for setting up the scene, camera, lights, renderer, etc...
    }
}

let canvas = new Canvas('#canvas');
canvas.init();

Based on my observations, it seems like the shader updates according to the camera settings within the get dayNightShader() method. The modelViewMatrix, projectionMatrix, and normalMatrix seem to rely on the camera parameters. I attempted to modify these matrices to use a fixed vector position instead of the camera viewpoint, but doing so only resulted in displaying the atmosphere texture while hiding the globe. Is there a way to utilize the light source's position to dictate the shader output rather than relying on the camera?

Answer №1

There seems to be an issue with the specific line of code:

float cosineAngleSunToNormal = dot(normalize(vNormal), sunDirection); 

This line is causing problems in the fragment shader. The vNormal variable represents a direction in view space because it undergoes transformation by the normalMatrix in the vertex shader. On the other hand, the sunDirection variable corresponds to a world space direction.

To resolve this issue, it is necessary to transform the sunlight direction using the view matrix in the vertex shader and then pass this transformed directional vector to the fragment shader.

vSunDir = mat3(viewMatrix) * sunDirection;

It's worth noting that the viewMatrix performs transformations from world space to view space. Using the viewMatrix instead of the normalMatrix is crucial because the latter transforms from model space to world space.

Vertex Shader:

varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vSunDir;

uniform vec3 sunDirection;

void main() {
    vUv = uv;
    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);

    vNormal = normalMatrix * normal;
    vSunDir = mat3(viewMatrix) * sunDirection;

    gl_Position = projectionMatrix * mvPosition;
}

Fragment Shader:

uniform sampler2D dayTexture;
uniform sampler2D nightTexture;

varying vec2 vUv;
varying vec3 vNormal;
varying vec3 vSunDir;

void main(void) {
    vec3 dayColor = texture2D(dayTexture, vUv).rgb;
    vec3 nightColor = texture2D(nightTexture, vUv).rgb;

    float cosineAngleSunToNormal = dot(normalize(vNormal), normalize(vSunDir));

    cosineAngleSunToNormal = clamp(cosineAngleSunToNormal * 5.0, -1.0, 1.0);

    float mixAmount = cosineAngleSunToNormal * 0.5 + 0.5;

    vec3 color = mix(nightColor, dayColor, mixAmount);

    gl_FragColor = vec4(color, 1.0);
}

Further Code Snippets...

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

Verifying the visibility of an element

I am facing a challenge with a list of apps displayed on a non-angular page. The availability of these apps depends on the subscription level purchased by the user. Even if an app has not been purchased, it is still listed but displayed with an overlay (pl ...

What is the best way to include two class names within a single div using Next.js?

Struggling to include two different CSS classes into a single div element, I encountered some issues. For reference, here is a screenshot: https://i.stack.imgur.com/UuCBV.png https://i.stack.imgur.com/sHNwq.png My code snippet looks like this: blog.js ...

What is the best way to display circles (generated from JSON data) in reverse order by incorporating a delay function?

I am currently working on creating an interactive visualization using circles that expand over a specified period, all centered at the same point. I have a script that generates these circles and saves the data in a JSON file. The smallest circle is posit ...

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

Discovering Unconventional Columns Through Sharepoint REST Api Filtration

I am working on recreating SharePoint's front end in my app and want to add columns to my table just like a user would in SP. The challenge I am facing is determining which columns were custom generated by the user rather than standard ones. Although ...

Discover the steps to inserting an icon into a tab using AngularJS

Hello, I am a beginner in angular js. Can someone please guide me on how to include an icon in a tab using angular js? Here is my current code: <tabset panel-tabs="true" panel-class="{{demoTabbedPanelClass}}" heading="{{demoTabbedPanelHeading}}"> ...

Node version 6.11.0 experiencing JavaScript heap error even with zero memory usage in the program

Encountering an out of memory error even though only two variables (i & j) are being used. Can someone please provide clarification? I am not storing anything in memory or saving it to any storage; whatever is generated is outputted to the console and the ...

JavaScript generated form fails to submit

I am currently facing an issue with submitting form data to a PHP file when it is generated using JavaScript. I am unsure of how to resolve this problem. The form submission works fine on a test .html file by itself, but not when it is generated by JavaScr ...

Check the dimensions of the image file entered using AngularJS on the client side

Before uploading an image to the server, I need to validate its dimensions on the client side. I have searched for solutions using img.Onload(), but that's not what I am looking for. All I want is for the user to choose the image from <input ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

What could be causing the React.js axios data to display on the console but not on the screen?

I am currently working on a React Axios Project using data from . The characters data includes another API link, so I implemented an Axios loop to display the names of the characters. While I can see the characters' names in the console, they are not ...

Is it possible to create a central hub for all routes in a large AngularJS application?

Developing a large angularjs application with the intention of utilizing require.js for lazy-loading additional modules. The main question at hand is whether to create a comprehensive route.js file containing all the routes to other modules, or if each mod ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Having trouble with AngularJS $location.path() not redirecting properly?

Why am I unable to redirect to a different URL using $location.path in angular.js? .controller('CheckCtrl', function($scope, $localStorage, $location) { $scope.check = function(){ if($localStorage.hasOwnProperty("accessToken") === t ...

Tips for automatically closing one element when another is clicked

My goal is to create a menu that displays when I click on a link, and if another menu is already open, it should close before displaying the new one. Essentially, I want to achieve an accordion menu where only one menu is open at a time. However, despite m ...

Implementing server authentication with Faye in Node.js

As a complete newbie to node.js and faye, I'm struggling with the basics and not sure what questions to ask. This is how my faye server setup looks like, running on Nodejitsu: var http = require('http'), faye = require('faye' ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...