Creating a unique shader in Three.js to seamlessly blend with the default rendering algorithm

Looking to improve performance, my goal is to showcase hundreds of moving tetrahedrons in a scene by using instancedbuffergeometry along with a custom shader.

Within the scene, there are also objects with regular geometry (non-buffer) and some lights. To see a simplified version of the setup, check out this snippet: https://jsfiddle.net/negan/xs3k1yz4/.

The issue arises with the shading of the tetrahedrons, as they do not blend well with the lighting of the rest of the scene. This mismatch in lighting may be attributed to the custom shader I have developed:

<script id="vertexShader" type="x-shader/x-vertex">
attribute vec3 offset;
attribute vec4 color;
varying vec4 vColor;
varying vec3 vNormal;
void main() {
vColor = color;
vNormal = normalMatrix * vec3(normal);
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position*1.0+offset,1.0);
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
varying vec4 vColor;
varying vec3 vNormal;

void main() {  
float di = 0.4*dot(vNormal,normalize(vec3(1.,1.,0.)))+0.4*dot(vNormal,normalize(vec3(1.,0.,1.)));
di = di+0.2;
vec4 vColor2= vColor*vec4(1.0,1.,1.,0.2)*di;
gl_FragColor = vColor2;// adjust the alpha
}
</script>

I am seeking guidance on how to modify the custom shader to better integrate with the established lights in the scene. The current rendering of the faces does not accurately depict directed light, and I am striving for a uniform illumination across individual faces rather than vertex-interpolated colors, despite my failed attempts to achieve this.

Appreciate any pointers or assistance in solving this issue.

Answer ā„–1

Check out this gist that contains the complete fragment and vertex shader source for a Three.js MeshPhongMaterial shader, specifically for r83 version.

When it comes to Three.js shaders, they are built using a string concatenation system, making it nearly impossible to determine the source of a shader just by looking at the Three.js source code.

The Gist mentioned above was created by utilizing the shader editor Chrome extension. By visiting a Three.js example page featuring a MeshPhongMaterial like this one, you can use the shader editor to examine the full source of a running shader program:

https://i.sstatic.net/BX7ll.png

Three.js automatically passes all default uniforms, including lighting data, to all shader programs. This means that if you implement a custom shader using the code from the provided Gist, elements like lights, bones, etc., will function seamlessly.

To incorporate your own logic, you can manually insert the results of your calculations into the existing gl_FragColor = ...

Looking ahead, my tool ShaderFrog will enable you to effortlessly integrate any Three.js shader feature (lights, bones, morph targets, etc.) into a custom shader. While ShaderFrog can currently automatically combine shaders, further work is required to fully support Three.js features.

Answer ā„–2

If you're looking to achieve mesh instancing in three.js without the need for shader materials, check out the InstancedMesh module. This handy tool patches the existing material to make instancing possible. Learn more about it here: https://github.com/pailhead/three-instanced-mesh

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

Content not being displayed by Javascript

I'm having trouble displaying content using JavaScript DOM. Every time I try to run my code, the page comes up blank. Here is an example of my HTML file: <!DOCTYPE html> <html> <head> <title>Radiant HQ</titl ...

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...

Tips for generating a universal regulation in vee-validate version 3

Is it possible to create a universal validation rule that can be applied to multiple elements? universalRule: { required:'required', min:'min', etc.. } On the form <ValidationProvider name="universalRule" rules=&qu ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Nuxt.js transition issue: How to fix transitions not working

LOGIC: The pages/account.vue file consists of two child components, components/beforeLogin and components/afterLogin. The inclusion of child components is based on a conditional check within pages/account.vue using a string result ('x') stored in ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Tips for incorporating JSON data into an HTML table

https://i.sstatic.net/WEdge.jpgIn an attempt to showcase JSON data in an HTML table, I want the schoolClassName value to be displayed as a header (th) and the first names of students belonging to that specific schoolClass to appear in a column beneath the ...

The current layout of the div is hindering the ability to switch from vertical scrolling to horizontal scrolling

I'm currently utilizing this scroll converter tool to transform vertical scrolling into horizontal scrolling. However, despite correct script inclusion and initialization, the conversion is not working as expected. It seems like there might be an issu ...

When setValue is called on VCheckbox in Vuetify, it emits an event called "update:modelValue"

After setting a value for the checkbox, I encountered a warning message: [Vue warn]: Component emitted event "update:modelValue" but it is neither declared in the emits option nor as an "onUpdate:modelValue" prop. Example.vue <script setup lang="t ...

How to create buttons in React to increase and decrease a value?

Just starting out with React and attempting to create a ticket counter. The goal is to increase or decrease by 1 based on the direction of the arrow clicked. However, I'm facing an issue where nothing is displaying on my webpage. Any ideas on what mig ...

What is the optimal placement for promises in Angular: Factory or Controller?

In my application, I have a basic factory to manage API calls. Currently, the structure looks like this: .factory('apiFactory', function($http){ var url = 'http://192.168.22.8:8001/api/v1/'; return { getReports: function() { ...

The SSR React application rendering process and asynchronous code execution

When using SSR with React, how is the content that will be sent to the client constructed? Is there a waiting period for async actions to finish? Does it wait for the state of all components in the tree to stabilize in some way? Will it pause for async ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

Error: The index $_GET[...] is not defined

When transferring a javascript variable to a php file, I encounter an issue where $_GET['something'] keeps returning as an undefined index. Despite this error, the correct result is displayed and written into the xml. However, when I attempt to ...

Constructing a hierarchical tree structure using an array of objects that are initially flat

My goal is to create a hierarchical tree structure from a flat array: The original flat array looks like this: nodes = [ {id: 1, pid: 0, name: "kpittu"}, {id: 2, pid: 0, name: "news"}, {id: 3, pid: 0, name: "menu"}, {id: 4, pid: 3, name: ...

How to modify a variable in the Config.json using a Discord.js command

Lately, I enhanced my bot's functionality by allowing it to retrieve the color for embeds from a file specified in my config.json. All I need to do is modify something like: "embedcolor": "00A950" to "embedcolor": "0 ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

What is the best way to clear the cache in AngularJS?

It is crucial for the cache to be cleared consistently. However, no matter if a client is created, updated, or deleted, the same result always occurs. Only when I manually delete the cache (Ctrl+Shift+Supr), am I able to view the new data. .factory(' ...

Running PHP scripts from JavaScript

Currently working on a PHP project that involves a dropdown select button in a webpage. The goal is to call a JavaScript function whenever the value of the dropdown changes, and then pass this selected value to retrieve additional details from a MySQL da ...

Is it possible to adjust the range of a range slider based on the selection of a radio button or other input method?

I have a query and Iā€™m hopeful you can assist: function UpdateTemperature() { var selectedGrade = $( "input[name='radios']:checked" ).val(); $( ".c_f" ).text(selectedGrade); var value1 = $("#tempMin").val(); var value2 = $("#tempM ...