I am encountering issues with my THREE.js RawShaderMaterial

I haven't encountered any issues when loading shaders created by others into THREE.js, but I've hit a roadblock when trying to create and run my own shader. The shader works perfectly on the platform where I designed it (), but it doesn't function as expected when I attempt to implement it. I'm uncertain whether the problem lies within the javascript, three.js, or GLSL code, so any assistance would be immensely helpful.

Here's the snippet of my js code:

function newCube(colour=0xffffff,height=1,width=height,depth=height){
  const geometry = new THREE.CubeGeometry(height,depth,width);
  const material = new THREE.MeshBasicMaterial( {color: colour} );
  return(new THREE.Mesh( geometry, material ));
}
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight,1,10000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xaaaaaa, 1);
document.body.appendChild(renderer.domElement);
const cube = newCube(0x220033,1);
var material= new THREE.RawShaderMaterial({
  "id": 5472,
  "name": "Fragmented",
  "fragmentShader": "precision highp float;\nprecision highp int;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\nuniform float time;\nuniform vec3 color;\nuniform vec3 lightPosition;\nvarying vec3 vPosition;\nvarying vec3 vNormal;\nvarying vec3 vColor;\nvarying vec2 vUv;\nvarying vec2 vUv2;\n\nvoid main() {\n    vec3 worldPosition = ( modelMatrix * vec4( vPosition, 1.0 )).xyz;\n    vec3 worldNormal = normalize( vec3( modelMatrix * vec4( vNormal, 0.0 ) ) );\n    vec3 lightVector = normalize( lightPosition - worldPosition );\n    float brightness = dot( worldNormal, lightVector );\n    gl_FragColor = vec4( color * brightness, 1.0 );\n}",
  "vertexShader": "precision highp float;\nprecision highp int;\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\nuniform float time;\nuniform vec3 color;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nattribute vec2 uv2;\nvarying vec3 vPosition;\nvarying vec3 vNormal;\nvarying vec2 vUv;\nvarying vec2 vUv2;\nvoid main() {\n    vNormal = normal;\n    vUv = uv;\n    vUv2 = uv2;\n    vPosition = position;\n    gl_Position= projectionMatrix * modelViewMatrix * vec4( position+sin(position*time)/10., 1. );\n}",
  "uniforms": {
    "time": {
      "name": "time",
      "displayName": null,
      "type": "f",
      "glslType": "float",
      "useGridHelper": false,
      "useRange": false,
      "range": null,
      "isRandom": false,
      "randomRange": null,
      "useToggle": false,
      "toggle": null,
      "description": "",
      "value":0
    },
    "color": {
      "name": "color",
      "displayName": null,
      "type": "c",
      "glslType": "vec3",
      "useGridHelper": false,
      "useRange": false,
      "range": null,
      "isRandom": false,
      "randomRange": null,
      "useToggle": false,
      "toggle": null,
      "description": "Example light color"
    },
    "lightPosition": {
      "name": "lightPosition",
      "displayName": null,
      "type": "v3",
      "glslType": "vec3",
      "useGridHelper": false,
      "useRange": false,
      "range": null,
      "isRandom": false,
      "randomRange": null,
      "useToggle": false,
      "toggle": null,
      "description": ""
    }
  }
});
scene.add(cube);
cube.material=material;
camera.position.z = 3;

function render() {
  cube.material.uniforms.time.value+=0.1;
  renderer.render(scene, camera);
  cube.mesh.rotation.x += 0.05;
  cube.mesh.rotation.y -= 0.05;
  requestAnimationFrame(render);
}

render();

Answer №1

Your code has been enhanced to display a visual output:

body{
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2b372d3a3a1f6f716e6c6c">[email protected]</a>";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight,1,10000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xaaaaaa, 1);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry();
var material= new THREE.RawShaderMaterial({
  "fragmentShader": "precision highp float;\nprecision highp int;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\nuniform float time;\nuniform vec3 color;\nuniform vec3 lightPosition;\nvarying vec3 vPosition;\nvarying vec3 vNormal;\nvarying vec3 vColor;\nvarying vec2 vUv;\nvarying vec2 vUv2;\n\nvoid main() {\n    vec3 worldPosition = ( modelMatrix * vec4( vPosition, 1.0 )).xyz;\n    vec3 worldNormal = normalize( vec3( modelMatrix * vec4( vNormal, 0.0 ) ) );\n    vec3 lightVector = normalize( lightPosition - worldPosition );\n    float brightness = dot( worldNormal, lightVector );\n    gl_FragColor = vec4( color * brightness, 1.0 );\n}",
  "vertexShader": "precision highp float;\nprecision highp int;\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\nuniform float time;\nuniform vec3 color;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nattribute vec2 uv2;\nvarying vec3 vPosition;\nvarying vec3 vNormal;\nvarying vec2 vUv;\nvarying vec2 vUv2;\nvoid main() {\n    vNormal = normal;\n    vUv = uv;\n    vUv2 = uv2;\n    vPosition = position;\n    gl_Position= projectionMatrix * modelViewMatrix * vec4( position+sin(position*time)/10., 1. );\n}",
  "uniforms": {
    "time": {
      "value":0
    },
    "color": {
      "value": new THREE.Color(0x320064)
    },
    "lightPosition": {
      "value": new THREE.Vector3().setScalar(5)
    }
  }
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 3;

function render() {
  cube.material.uniforms.time.value+=0.1;
  renderer.render(scene, camera);
  cube.rotation.x += 0.01;
  cube.rotation.y -= 0.01;
  requestAnimationFrame(render);
}

render();
</script>

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

Tips for retrieving the final element from a corrupt JSON string using JavaScript

I've encountered an issue with a nodejs speech recognition API that provides multiple texts in a JSON like structure which renders the data invalid and useless. { "text": "Play" } { "text": "Play astronaut" } ...

Creating a unique WooCommerce product category dropdown shortcode for your website

I am having trouble implementing a WooCommerce categories dropdown shortcode. Although I can see the drop-down menu, selecting a category does not seem to trigger any action. Shortcode: [product_categories_dropdown orderby="title" count="0" hierarchical=" ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

Is there a way to transform a callback into promises using async/await, and convert a prototype function into a standard

I need help converting a code callback function to promises. When attempting to convert the prototype to a normal function, I encounter an error that I can't fix on my own. I am eager to utilize the ES7 async-await feature to avoid callbacks. functio ...

Establishing the NumbroJS cultural settings

I have been attempting to modify numbro's culture. I initially tried the straightforward method, but encountered an error: Unknown culture : ' + code numbro.culture('fr-FR'); My attempt looked like this: const br = require('numb ...

React: Applying the active class to mapped elements

I have a component that iterates over an array to generate 10 navigation items. I want to implement an onClick method that will add an active class to the clicked item. Are there any best practices using Hooks or the newer React patterns for achieving this ...

The response to ajax requests does not appear in Chrome Dev Tools

I'm experiencing an issue with my nodejs application where I encounter a peculiar situation when making ajax requests using jQuery. When I make a redirection in the callback function of the AJAX request, the response in the developer tools appears emp ...

implementing ajax form submission in codeigniter

After submitting my form, validation is checked in the JavaScript file, and then the kickerLogin() function is called. I receive an alert message of datastring. However, the data is not sent to the specified URL in the AJAX request, but the form still ge ...

What additional requirements are needed for Rails and remote AJAX with the "true" setting?

I'm a bit confused about the purpose of remote:true in Rails forms. I initially thought that it required some Javascript to enable asynchronous functionality, but instead it seems to be causing issues with my page. Below is a simple index.html.haml f ...

Implement a code to apply to an image that is loaded dynamically

I have a situation on a page where an image is loaded via ajax within a wrapping div. I need to execute some code as soon as that image is loaded. Unfortunately, I am unable to modify the ajax call, which means using on('success') directly on the ...

Utilizing PHP, Javascript, and jQuery in mobile technology gadgets

Can anyone recommend mobile technology products that have been developed using PHP, Javascript, and jQuery? What are the newest mobile products available on the market that have been built using these languages? Do popular devices like iPhone, BlackBerry ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

I am experiencing issues with launching chromium while running Puppeteer on Windows 11 using node js v19.4

Upon following the installation instructions in the documentation to install puppeteer with npm install puppeteer, I attempted to run the example for downloading a webpage as a PDF. However, every time I try to execute the code, Node.js returns the followi ...

What is the best way to store XHR data in a browser's cache?

I have been seeking a solution to locally cache an XHR request on my computer for future use. Whenever I visit an online shop, I often encounter a form in the order page that includes a field with XHR. After filling out this field, I have to submit the f ...

I need to confirm the validity of minDate and maxDate in a ReactJS component, ensuring that maxDate is always at least 5 years after min

start from today and select a date end 5 years from the starting date I haven't attempted anything yet. Seeking help for a solution. ...

Implementing a custom button specifically for the month view in JavaScript FullCalendar

I have successfully added a custom button to my JavaScript full calendar code, but I would like this button to be displayed only in the month view. $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ editable: tru ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Dynamic views loaded from ui-router can cause compatibility issues with running Javascript

Currently, I am facing an issue while attempting to load a template into a UI-View using UI-Router. Although the JavaScript is loaded, it does not run on the loaded views. The situation unfolds as follows: I have developed a template in HTML containing all ...

Leveraging babel-cli on your local machine

Is it possible to utilize the babel client without the need for global installation? Instead of following this method npm install -g babel-cli I am looking to achieve the same outcome by using npm install babel-cli --save-dev ...

No content found in jQuery .text() values within iframe

I am experiencing an unusual issue with assigning a value to a variable using jQuery. I am unable to retrieve the values from .text() specifically on Spotify, while other functions on different sites are working fine. Even after the elements have loaded, i ...