惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence
小众软件
小众软件
云风的 BLOG
云风的 BLOG
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
量子位
S
Secure Thoughts
G
GRAHAM CLULEY
C
CXSECURITY Database RSS Feed - CXSecurity.com
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
G
Google Developers Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 聂微东
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
S
Security Affairs
Help Net Security
Help Net Security
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
博客园 - 叶小钗
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
H
Heimdal Security Blog
W
WeLiveSecurity
C
Check Point Blog

WebGL Fundamentals

WebGL Using 2 or More Textures WebGL Implementing DrawImage WebGL 2D Matrices WebGL Implementing A Matrix Stack WebGL 2D Rotation WebGL 2D Scale WebGL 2D Translation WebGL - Rasterization vs 3D libraries WebGL 3D - Cameras WebGL 3D Geometry - Lathe WebGL 3D - Directional Lighting WebGL 3D - Point Lighting WebGL 3D - Normal Mapping WebGL 3D - Spot Lighting WebGL - Orthographic 3D WebGL 3D Perspective Correct Texture Mapping WebGL 3D Perspective WebGL Textures WebGL and Alpha WebGL - Animation WebGL Anti-Patterns WebGL Attributes WebGL Boilerplate WebGL - Cross Origin Images WebGL Cross Platform Issues WebGL Cubemaps WebGL 3D - Data Textures WebGL - Drawing Multiple Things WebGL Drawing Without Data WebGL Environment Maps (reflections) WebGL Fog WebGL Framebuffers WebGL Fundamentals WebGL GPGPU WebGL How It Works WebGL Image Processing Continued WebGL Image Processing WebGL Indexed Vertices WebGL Optimization - Instanced Drawing WebGL - Less Code, More Fun WebGL Load Obj with Mtl WebGL Load Obj WebGL Matrices vs Math Matrices WebGL Multiple Views, Multiple Canvases WebGL Picking WebGL Planar and Perspective Projection Mapping WebGL Points, Lines, and Triangles WebGL Post Processing WebGL Precision Issues WebGL Pulling Vertices Accessing textures by pixel coordinate in WebGL2 A simple way to show the load on the GPU's vertex and fragment processing? Apply a displacement map and specular map Can anyone explain what this GLSL fragment shader is doing? Can I mute the warning about vertex attrib 0 being disabled? Create image warping effect in WebGL Creating a smudge/liquify effect How to draw Depth Sprites Determine min/max values for the entire image Don't blend a polygon that crosses itself Drawing 2D image with depth map to achieve pseudo-3D effect Drawing a heightmap Drawing layers with different points Drawing Many different models in a single draw call Drawing textured sprites with instanced drawing Efficient particle system in javascript? (WebGL) Emulating palette based graphics in WebGL FPS-like camera movement with basic matrix transformations Get the size of a point for collision checking GLSL shader to support coloring and texturing How can I compute for 500 points which of 1000 line segments is nearest to each point? How can I create a 16bit historgram of 16bit data How can I get all the uniforms and uniformBlocks How can I move the perspective vanishing point from the center of the canvas? How to Achieve Moving Line with Trail Effects How to bind an array of textures to a WebGL shader uniform? How to blend colors across 2 triangles How to combine more text drawing into fewer draw calls How to control the color between vertices How to create a torus How to detect clipped triangles in the framgment shader How to determine the average brightness in a scene? How to draw correctly textured trapezoid polygons How to fade the drawing buffer How to figure out how much GPU work to do without crashing WebGL How to get audio data into a shader How to get code completion for WebGL in Visual Studio Code How to get the 3d coordinates of a mouse click How to get pixelize effect in webgl? How to implement zoom from mouse in 2D WebGL How to import a heightmap in WebGL How to load images in the background with no jank How to make a smudge brush tool How to make WebGL canvas transparent How to optimize rendering a UI How to prevent texture bleeding with a texture atlas How to process particle positions How to read a single component with readPixels How to render large scale images like 32000x32000 How to simulate a 3D texture in WebGL
Show a night view vs a day view on a 3D Earth sphere
WebGLFundame · 2025-02-26 · via WebGL Fundamentals

Question:

I am using Three.js as a framework for developing a space simulator and I am trying, but failing to get night lights working.

The simulator can be accessed here:

orbitingeden.com

and a page running the code snippet below can be found here:

orbitingeden.com/orrery/soloearth.html

The code for the sample page is here. I don't even know where to begin. I tried rendering two globes a few units apart, one closer to the sun (daytime version) and one further(nighttime version) but there are many problems, not the least of which is that they begin to overlap each other in strange dodecahedron kind of ways. I adopted the tDiffuse2 idea from this orrery, but couldn't get it working.

<!doctype html>
<html lang="en">
 <head>
  <title>three.js webgl - earth</title>
  <meta charset="utf-8">
  <script src="three.js/Detector.js"></script>
  <script src="three.js/Three.js"></script>
 </head>
 <body>
  <script>
   if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

   var radius = 6371;
   var tilt = 0.41;
   var rotationSpeed = 0.02;
   var cloudsScale = 1.005;
   var SCREEN_HEIGHT = window.innerHeight;
   var SCREEN_WIDTH  = window.innerWidth;
   var container, camera, scene, renderer;
   var meshPlanet, meshClouds, dirLight, ambientLight;
   var clock = new THREE.Clock();

   init();
   animate();

   function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    scene = new THREE.Scene();
    scene.fog = new THREE.FogExp2( 0x000000, 0.00000025 );

    camera = new THREE.PerspectiveCamera( 25, SCREEN_WIDTH / SCREEN_HEIGHT, 50, 1e7 );
    camera.position.z = radius * 5;
    scene.add( camera );

    dirLight = new THREE.DirectionalLight( 0xffffff );
    dirLight.position.set( -20, 0, 2 ).normalize();
    scene.add( dirLight );

    ambientLight = new THREE.AmbientLight( 0x000000 );
    scene.add( ambientLight );

    //initialize the earth
    var planetTexture = THREE.ImageUtils.loadTexture( "textures/earth-day.jpg" ),
    nightTexture      = THREE.ImageUtils.loadTexture( "textures/earthNight.gif" ),
    cloudsTexture     = THREE.ImageUtils.loadTexture( "textures/clouds.gif" ),
    normalTexture     = THREE.ImageUtils.loadTexture( "textures/earth-map.jpg" ),
    specularTexture   = THREE.ImageUtils.loadTexture( "textures/earth-specular.jpg" );
    var shader = THREE.ShaderUtils.lib[ "normal" ];
    var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
    uniforms[ "tNormal" ].texture = normalTexture;
    uniforms[ "uNormalScale" ].value = 0.85;
    uniforms[ "tDiffuse" ].texture = planetTexture;
    uniforms[ "tDiffuse2" ].texture = nightTexture;
    uniforms[ "tSpecular" ].texture = specularTexture;
    uniforms[ "enableAO" ].value = false;
    uniforms[ "enableDiffuse" ].value = true;
    uniforms[ "enableSpecular" ].value = true;
    uniforms[ "uDiffuseColor" ].value.setHex( 0xffffff );
    uniforms[ "uSpecularColor" ].value.setHex( 0x333333 );
    uniforms[ "uAmbientColor" ].value.setHex( 0x000000 );
    uniforms[ "uShininess" ].value = 15;
    var parameters = {
     fragmentShader: shader.fragmentShader,
     vertexShader: shader.vertexShader,
     uniforms: uniforms,
     lights: true,
     fog: true
    };
    var materialNormalMap = new THREE.ShaderMaterial( parameters );
    geometry = new THREE.SphereGeometry( radius, 100, 50 );
    geometry.computeTangents();
    meshPlanet = new THREE.Mesh( geometry, materialNormalMap );
    meshPlanet.rotation.y = 0;
    meshPlanet.rotation.z = tilt;
    scene.add( meshPlanet );

    // clouds
    var materialClouds = new THREE.MeshLambertMaterial( { color: 0xffffff, map: cloudsTexture, transparent: true } );
    meshClouds = new THREE.Mesh( geometry, materialClouds );
    meshClouds.scale.set( cloudsScale, cloudsScale, cloudsScale );
    meshClouds.rotation.z = tilt;
    scene.add( meshClouds );

    renderer = new THREE.WebGLRenderer( { clearColor: 0x000000, clearAlpha: 1 } );
    renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
    renderer.sortObjects = false;
    renderer.autoClear = false;
    container.appendChild( renderer.domElement );
   };

   function animate() {
    requestAnimationFrame( animate );
    render();
   };

   function render() {
    // rotate the planet and clouds
    var delta = clock.getDelta();
    meshPlanet.rotation.y += rotationSpeed * delta;
    meshClouds.rotation.y += 1.25 * rotationSpeed * delta;
    //render the scene
    renderer.clear();
    renderer.render( scene, camera );
   };
  </script>
 </body>
</html>

Answer:

If I understand your question....

I don't know three.js but in general I'd do this by having a shader that has gets passed both the day and night time textures and then selecting one or the other in the shader. For example

uniform sampler2D dayTexture;
uniform sampler2D nightTexture;
varying vec3 v_surfaceToLight;  // assumes this gets passed in from vertex shader
varying vec4 v_normal;          // assumes this gets passed in from vertex shader
varying vec2 v_texCoord;        // assumes this gets passed in from vertex shader

void main () {
   vec3 normal = normalize(v_normal);
   vec3 surfaceToLight = normalize(v_surfaceToLight);
   float angle = dot(normal, surfaceToLight);
   vec4 dayColor = texture2D(dayTexture, v_texCoords);
   vec4 nightColor = texture2D(nightTexture, v_texCoord);
   vec4 color = angle < 0.0 ? dayColor : nightColor;

   ...

   gl_FragColor = color * ...;
}

Basically you take the lighting calculation and instead of using it for lighting you use it to select the texture. A lighting calculation usually uses a dot product between the normal of the surface and the direction of the light (the sun) from the surface. That gives you the cosine of the angle between those to vectors. Cosine goes from -1 to 1 so if the value is from -1 to 0 it's facing away from the sun, if it's 0 to +1 it's facing toward the sun.

The line

   vec4 color = angle < 0.0 ? dayColor : nightColor;

selects the day or night. That's going to be a harsh cutoff. You might experiment with something more fuzzy like

   // convert from -1 <-> +1 to 0 <-> +1
   float lerp0To1 = angle * 0.5 + 0.5; 

   // mix between night and day
   vec4 color = mix(nightColor, dayColor, lerp0to1);

That would give you 100% day on the spot directly facing the sun and 100% night on the spot directly opposite the sun and a mix in-between. Probably not what you want but you can futs with the numbers. For example

   // sharpen the mix
   angle = clamp(angle * 10.0, -1.0, 1.0);

   // convert from -1 <-> +1 to 0 <-> +1
   float lerp0To1 = angle * 0.5 + 0.5; 

   // mix between night and day
   vec4 color = mix(nightColor, dayColor, lerp0to1);

Hopefully that made sense.


So I spent a little time working up a Three.js example, partly to learn Three.js. The sample is here.

The shader I used is this

uniform sampler2D dayTexture;
uniform sampler2D nightTexture;

uniform vec3 sunDirection;

varying vec2 vUv;
varying vec3 vNormal;

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

    // compute cosine sun to normal so -1 is away from sun and +1 is toward sun.
    float cosineAngleSunToNormal = dot(normalize(vNormal), sunDirection);

    // sharpen the edge beween the transition
    cosineAngleSunToNormal = clamp( cosineAngleSunToNormal * 10.0, -1.0, 1.0);

    // convert to 0 to 1 for mixing
    float mixAmount = cosineAngleSunToNormal * 0.5 + 0.5;

    // Select day or night texture based on mixAmount.
    vec3 color = mix( nightColor, dayColor, mixAmount );

    gl_FragColor = vec4( color, 1.0 );

    // comment in the next line to see the mixAmount
    //gl_FragColor = vec4( mixAmount, mixAmount, mixAmount, 1.0 );
}

The big difference from the one above is that since the sun is generally considered a directional light since it is so far away then all you need is it's direction. In other words, which way it's pointing relative to the earth.