The issue of updating a GLSL uniform variable during an animation in three.js using TypeScript remains unresolved

Running a three.js TypeScript application, I developed custom GLSL shaders using the THREE.ShaderMaterial() class. Now, I aim to enhance my code by switching to the THREE.MeshStandardMaterial class.

This is an entirely new experience for me, and despite encountering minor setbacks during the refactoring process, everything progressed smoothly except for updating the uTime uniform in the animation loop as shown below:

material.userData.shader.uniforms.uTime.value = timeDivided;

An error has surfaced ever since, indicating:

index.ts:71 Uncaught TypeError: Cannot read properties of undefined (reading 'uniforms')
    at animate (stackOverflowQuestion.ts:71:28)
    at onAnimationFrame (three.module.js:28991:1)
    at onAnimationFrame (three.module.js:13332:1)
animate @ stackOverflowQuestion.ts:71

The complete simplified app code is presented below:

index.ts:


    import * as THREE from "three";
    import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
    import vertexShaderParse from "./shaders/vertexParse.glsl";
    import vertexMain from "./shaders/vertexMain.glsl";
    import textureImage from "./assets/images/test-image-1.jpeg";
    
    // setting up renderer, scene, camera, lights, controls, etc.
    
    const material = new THREE.MeshStandardMaterial();
    
    // main object implementation with custom shaders
    // shader logic and materials setup
    
    const mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);
    
    const animate = (time: number) => {
      const timeDivided = time / 10000;
      // problematic part where the error occurs ↓, uncommenting breaks the application
      material.userData.shader.uniforms.uTime.value = timeDivided;
      renderer.render(scene, camera);
    };
    renderer.setAnimationLoop(animate);

vertexMain.glsl:


    // vertex shader logic

vertexMain.glsl:


    // additional vertex shader logic
    

If anyone could provide insights on resolving this issue related to animating the uTime uniform, it would be greatly appreciated.

Answer №1

Before the initial rendering in the animate() function, trying to access material.userData.shader will result in it being undefined because onBeforeCompile() has not been executed yet. To resolve this issue, you can make a simple adjustment like below:

const shader = material.userData.shader;

if ( shader !== undefined ) {

   shader.uniforms.uTime.value = timeDivided;

} 

renderer.render(scene, camera);

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

What is the best way to deliver a file in Go if the URL does not correspond to any defined pattern?

I am in the process of developing a Single Page Application using Angular 2 and Go. When it comes to routing in Angular, I have encountered an issue. For example, if I visit http://example.com/, Go serves me the index.html file as intended with this code: ...

The functionality of mousepick(raycaster) in three.js seems to be ineffective when applied to loaded

Having an issue with mouse picking - when the mouse is over a mesh, it shows as picked but does not actually select it when the mouse is over a loaded 3D model. Here is my code snippet: // Raycasting export function cameraPick() { raycaster.setFromC ...

The error message "Module 'electron' not found" is commonly encountered when working with Electron and TypeScript

Hey there! I'm having some trouble with Electron not supporting TypeScript on my setup. I'm using vscode 1.16.1 and here is an overview of my package.json: { [...] "devDependencies": { "electron": "^1.6.13", "ts-loader": "~2.3.7", ...

Utilizing Angular 14 and Typescript to fetch JSON data through the URL property in an HTML

Is there a way to specify a local path to a JSON file in HTML, similar to how the src attribute works for an HTML img tag? Imagine something like this: <my-component data-source="localPath"> Here, localPath would point to a local JSON fil ...

The module declaration is triggering a lint error that reads "Unexpected token, expecting '{'"

To address the absence of available types for a library, I created the file omnivore.d.ts in TypeScript. Within this file, I added the following line: declare module '@mapbox/leaflet-omnivore' Upon running vue-cli-service lint in my project, an ...

Encountering Typescript errors while compiling an Angular module with AOT enabled

I am currently in the process of manually constructing an Angular module with Webpack, opting not to use the CLI. While a normal build is functioning without any issues, encountering errors during an AOT build! Here's how my tsconfig.aot.json file ...

What is the most effective method for designing a scalable menu?

What is the most effective way to create a menu similar to the examples in the attached photos? I attempted to achieve this using the following code: const [firstParentActive, setFirstParentActive] = useState(false) // my approach was to use useState for ...

PlaneGeometry at x=0 y=0 z=0 for three.js on a flat surface

Hi there! I have a code snippet that currently renders an image vertically, and I'm looking to modify it so that the PlaneGeometry is drawn horizontally instead. Rather than rotating it with mesh.rotation.x=THREE.Math.degToRad(-90);, I'd like it ...

There is no overload that fits the current call | Typescript, React, and Material UI

Embarking on my TypeScript journey with React and Material UI, I am hitting a roadblock with my initial component. // material import { Box } from '@material-ui/core'; // ---------------------------------------------------------------------- ...

Can child directives in Angular 2 harness the power of parent providers?

I am facing an issue while trying to utilize a service as a provider for general use in a Directive rather than a Component. The problem arises when the service is not being received in the child Directive, despite my expectation to use it within the direc ...

Issue with locating module in Visual Studio 2015 when using Angular5 and TypeScript version TS2307

I'm currently attempting to integrate Angular in Visual Studio 2015 update 3, but encountering the following error: TS2307 cannot find module '../node_modules/@angular/core'. The error is shown in the image linked here. Can anyone help me fi ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...

Error in the THREE.WebGLProgram shader due to the presence of constant v1 being defined

While working with Three.js, I encountered an error when attempting to load an HDR as an environment map for the scene. Here is the error message: https://i.sstatic.net/YhXiM.png The problematic line of code is: https://i.sstatic.net/XmpU3.png It seems ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Utilizing the MapToIterable Angular Pipe with TypeScript

Exploring the implementation of a pipe in Angular. Discovered that ngFor doesn't work with maps, prompting further research to find a solution. It seems that future features may address this issue, but for now, utilizing a mapToIterable pipe is the re ...

Issue: The UserComponent is attempting to set the property 'id' of an undefined object, resulting in an error

An error has occurred indicating that the property 'id' cannot be set as it is undefined in the UserComponent file of user.component.ts. Here is the TypeScript code: import { Component, OnInit } from "@angular/core"; import { ActivatedRoute, Rou ...

Implementing cursor-based pagination in Next.js API Route with Prisma and leveraging the power of useSWRInfinite

I am working on implementing cursor-based pagination for a table of posts using Next.js API Route, Prisma, and useSWRInfinite. Currently, I am fetching the ten most recent posts with Prisma in a Next.js API Route and displaying them using useSWR, sorted b ...

Having trouble loading Three.js in JavaScript file using npm install?

I am encountering a problem when trying to include Three.js in my JavaScript file without using the HTML script element. The error message I receive is "Uncaught SyntaxError: Cannot use import statement outside a module". Although my Three.js code runs suc ...

Guide on accessing mobile information and sim card details with Ionic 3 and Cordova on Android devices

Just started using Ionic and I'm looking for guidance on how to retrieve mobile and sim details with Ionic 3 and Cordova for Android. Any help is greatly appreciated in advance! ...

Is it time to release the BufferGeometry?

My scene objects are structured around a single root Object3D, with data loaded as a tree of Object3Ds branching from this root. Meshes are attached to the leaf Object3Ds using BufferGeometry/MeshPhongMaterial. To clear the existing tree structure, I use t ...