Create a unique shader in Three.js that remains unaffected by the fog effect

I have implemented a custom shader to add glow to a sphere on my scene.

However, I noticed that the fog in the scene affects the sphere but not the glow. When I zoom out, the sphere disappears but the glow remains visible.

Is there a way to make the fog also affect the glow?

For reference, here is the complete scene on Codepen:

http://codepen.io/marjan-georgiev/pen/WrmPLY?editors=0010

Below is the code for my glow material:

glowMaterial(){
  return new THREE.ShaderMaterial({
    side: THREE.BackSide,
    blending: THREE.AdditiveBlending,
    transparent: true,
    fog: true,

    uniforms: THREE.UniformsUtils.merge([
      THREE.UniformsLib[ "fog" ],
      {
        "c":   { type: "f", value: 0 },
        "p":   { type: "f", value: 4.5 },
        glowColor: { type: "c", value: Node.defaults.glowColor },
        viewVector: { type: "v3", value: {x: 0, y: 0, z: 400} },
        fog: true
      },
    ]),

    fragmentShader: `
      uniform vec3 glowColor;
      varying float intensity;
      ${THREE.ShaderChunk[ "common" ]}
      ${THREE.ShaderChunk[ "fog_pars_fragment" ]}
      void main()
      {
        vec3 outgoingLight = vec3( 0.0 );
        vec3 glow = glowColor * intensity;
        ${THREE.ShaderChunk[ "fog_fragment" ]}
        gl_FragColor = vec4(glow, 1.0 );
      }
    `,

    vertexShader: `
      uniform vec3 viewVector;
      uniform float c;
      uniform float p;
      varying float intensity;
      void main()
      {
        vec3 vNormal = normalize( normalMatrix * normal );
        vec3 vNormel = normalize( normalMatrix * viewVector );
        intensity = pow( c - dot(vNormal, vNormel), p );

        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
      }
    `
  });
}

Answer №1

Refer to the fog fragment specifically for r70 (which is being utilized) HERE and you will notice that it is adding fog to gl_FragColor.
By relocating the fog_fragment code after setting gl_FragColor, you should see the fog affecting your shader.

fragmentShader: '
  uniform vec3 glowColor;
  varying float intensity;
  ${THREE.ShaderChunk[ "common" ]}
  ${THREE.ShaderChunk[ "fog_pars_fragment" ]}
  void main()
  {
    vec3 outgoingLight = vec3( 0.0 );
    vec3 glow = glowColor * intensity;
    gl_FragColor = vec4(glow, 1.0 );
    ${THREE.ShaderChunk[ "fog_fragment" ]}
  }
',

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

Update Input field by eliminating white spaces using jQuery version 3.2.1

I am currently developing an HTML/PHP form for user registration. Using the code below, I have managed to prevent any blank spaces from appearing in the input field: <!DOCTYPE html> <html> <head> <script> function stripspaces( ...

Discover the location following a designated distance along a direct path connecting two points in the Google Maps API

Using the Google Maps API, I have plotted a straight line from point P1 to point P2. Both points have latitude and longitude coordinates available. I am interested in finding a point (P) along this straight line, located at a specific distance from P1. F ...

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

Is it possible to build a Node.js (Express) application using a combination of JavaScript and TypeScript?

Currently, I have a Node.js project (Express REST API) that is written in JavaScript. My team and I have made the decision to gradually rewrite the entire project into TypeScript. Is it possible to do this incrementally, part by part, while still being ab ...

Save all user information annually from the date they first sign up

Greetings! I am facing an issue where every time a year is added, it gets inserted between the day and month in the date of entry for a user at our company. var yearOnCompany = moment(user.fecha_ingreso_empresa, "YYYYMMDD").fromNow(); var dateStart = mome ...

Setting maxFontSizeMultiplier for all Text components

Is there a way to apply the prop maxFontSizeMultiplier={1} to all instances of <Text/> in my app without the need for a custom component? ...

Res.write inexpressively proceeding without waiting for the completion of an array of promises

snippet const processAll = async (tasks) => { let processes = []; tasks.forEach(task => { if (task === "1") processes.push(asyncProcess1); if (task === "2") processes.push(asyncProcess2); if (task === "3&q ...

Durable Container for input and select fields

I need a solution for creating persistent placeholders in input and select boxes. For instance, <input type="text" placeholder="Enter First Name:" /> When the user focuses on the input box and enters their name, let's say "John", I want the pl ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

Personalized Element Commands and features

UniquePage.html <div ng-controller="UniquePageCtrl"> <unique-custom-directive arg1="{{currentObj.name}}"></my-custom-directive> <div> in UniquePageCtrl.js (Controller) app.controller("UniquePageCtrl", ["$scope", function ($sc ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...

Creating a group object based on ID using react-native and JavaScript - a step-by-step guide

I have an array of objects that I need to reorganize so that each object with the same guid is grouped together. For instance, given this array; [ {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","comment":"text&quo ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Guide on transmitting data between NextJS and MongoDB

I'm facing an issue where the data from a form is being sent to MongoDB as undefined using nextJS and MongoDB. NewPlayerPage component: const newPlayerPage = (props) => { console.log('props: ' + props); const handleAddPlayer = a ...

Firebug mistakenly detects phantom errors

<div id="video-player" data-src="http://www.youtube.com/embed..."></div> Inspect Element - Browser Developer Tools: Error: Access to property 'toString' denied I scanned the entire page (Ctrl+F) and could not find any reference t ...

What is the difference in speed between drawing on a transparent canvas and determining if a point is transparent compared to determining if a point is within a complex polygon?

I'm curious if anyone has done research on adding event support to a game engine. Specifically, I am working on incorporating pixel-perfect hover over 2D object event support into my own game engine. I am exploring different ways of achieving this eff ...

Executing a JavaScript function through C# code

Does anyone have a code snippet for calling a JavaScript function from C#? Here's the scenario: I have an ASP.NET page with an ASP button. When this button is clicked, I want to call a JavaScript function. For example: In my ASP.NET page, <but ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

Issues have arisen with the functionality of noneditable contents in tinymce

I am currently using the tinyMCE editor and I need to make certain content readonly (nonEditable). According to the documentation, if I apply the class "mceNonEditable" to specific elements, it should meet this requirement. However, when I select that ele ...