Using THREE.js to pass an array of vec2 to a shader

I've spent quite some time browsing the internet but haven't found the right solution yet. I came across a list of uniform types used by THREE.js and believe the code below should be accurate. I'm defining a uniform array of Vector2 at the last line.

uniforms: {
    "center":   { type: "v2", value: new THREE.Vector2( 0.5, 0.5 ) },
    "aspectRatio": { type: "f", value: null },
    "radius": { type: "f", value: 0.1 },
    "pointList":  { type: "v2v", value: [] },
},

In my JavaScript script, I pass this array as shown below. I believe this should also work:

// Add effects
effect = new THREE.ShaderPass( THREE.MetaBalls2D );
effect.renderToScreen = true;
effect.uniforms[ 'aspectRatio' ].value = window.innerWidth/window.innerHeight;
effect.uniforms[ 'pointList' ].value = pointList //is an array of THREE.Vector2;
composer.addPass( effect );

Now my question is, how can I retrieve this uniform variable (pointList in this case) from the fragmentshader?

Answer №1

When working with arrays, it is important to determine the maximum size needed. For example, if you have an array like this:

const myVectorArray = [
    new Vector(),
    new Vector(),
    new Vector(),
    ...
]

One approach is to initialize a shader using the array size:

const myShader = new ShaderMaterial({
    uniforms:{
        _myVectorUniformArray:{
            type:'v2v',
            value: myVectorArray
        }
    },
    vertexShader: 
        '#define ARRAYMAX '+ myVectorArray.length +'\n' + myVertexShader
}

In the vertex shader, initialize the array:

uniform vec2 _myVectorUniformArray[ARRAYMAX];

While populating the array is optional, exposing ARRAYMAX in JavaScript allows for managing the array effectively.

Answer №2

To ensure proper initialization, I recommend starting with some vectors:

"pointList":  { type: "v2v", value: [ new THREE.Vector2(), new THREE.Vector2() ] },

To incorporate this into your shader, you will need to include the following line:

uniform vec2 pointList[2];

If you prefer to avoid using Vector2 objects, you can opt for the 2fv uniform type:

"pointList":  { type: "2fv", value: [ 1, 0,  0, 1 ] }

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 preventing directly mutating a prop within a recursive component

The child operates on its own copy of the prop data and can notify the parent using `$emit` when a change occurs. Imagine dealing with a recursive tree structure, like a file system for example: [ { type: 'dir', name: 'music', childr ...

What is the most effective method to arrange absolute divs generated randomly in a grid-like formation?

Hey there! I'm facing an intriguing challenge with my app. It's designed to generate a variable number of divs which are always in absolute positioning. Unfortunately, making them relative is not an option due to some other factors within the app ...

"Bringing in" ES6 for Node

I am interested in utilizing import from ES6 instead of require from common.js in Node. Surprisingly, I initially assumed that import would function automatically in Node. However, it appears that it does not. Is there a specific npm package that needs t ...

[filepond] in order to enroll using the serverId value received from the server

Using 'filepond' within a Vue application is causing an issue. In the "process" function, the ID value obtained after transferring the file to the server (response.id) needs to be registered as 'serverId' of the file. Upon checking the ...

Generate an array of objects based on the attributes of img elements, extract their values, and display them using jQuery

I currently have a fullscreen plug-in that works with static URLs, but I want to switch to using dynamic image data generated by a CMS on the page. Here is a snippet of the HTML output from the CMS: <ul class="large-gallery"> <li> <a href ...

Using a for loop to cycle through an array and generate sibling div elements

I'm attempting to display the content of the gameTwo array in two child divs under the game2 element. However, the issue I'm facing is that the loop creates a child of a child on the second iteration. Could someone provide guidance on how I can a ...

Skipping every third index in a JQuery .each loop after removing an element

I have a project where I need to display elements in rows of 4, and when an element is deleted, I want the remaining elements to shift up. To achieve this, I am currently assigning a class "last" to every fourth item after a deletion and inserting a spacer ...

What steps can I take to modify the class of a button once it has been clicked using JQuery?

Currently, I am experimenting with Jquery to dynamically change the classes of bootstrap buttons when they are clicked. However, I have encountered a limitation while using toggleClass. The issue is that I am only able to toggle between two classes, whic ...

Nested modal in native app utilizes the React Carbon TextInput component for an uneditable input field

As a newcomer to React, I have encountered an issue with the Tauri framework used to bundle my React application as a desktop app. Specifically, I am facing a problem where the TextInput field, nested inside a modal and utilizing React Carbon components, i ...

What's the best way to make a popup link in my situation?

I'm attempting to use Angular to open a popup window in my situation. Here's what I've got: <a ng-href = "window.open('{{videoLink}}')" >open a video</a> When I try this, I get a 'Not found' error in the br ...

Using for loop in AJAX Done() function

I'm currently working on a for loop that loops through an array consisting of 3 different report numbers. For each value in the array, an AJAX request is sent out. What I want to achieve is having a unique behavior for the .done() function based on th ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Using React Router can sometimes lead to an issue where the React components are

My server side rendering is set up for performance, but I am encountering discrepancies between the client and server renderings. The client initially renders <!-- react-empty: 1 --> instead of components, which leads to a different checksum. As a re ...

Implementing relative pathing in front-end development while using ExpressJS for the back-end

I'm currently in the process of developing an application with Express 4.14. When it comes to routing, I have a situation where the incoming request is "https://example.com/page", and I am using res.sendFile(__dirname + "/../client/pages/page/index.ht ...

Seeking a straightforward and powerful list for bugs and features that allows users to easily vote and prioritize

I am searching for a simple Javascript or PHP code that allows users to add items to two separate lists and either vote or rate those items. One list is for suggesting and rating features, while the other list is for identifying and voting on bugs that nee ...

What makes the ng-file-upload Upload service so special?

Why do I need to use the Upload service with ng-file-upload in this specific way? Upload.upload({ url: '/postMyFormHere', data: { fileToUpload: model.file, someField1: model.field1, someField2: model.field2, ...

Find and replace problem with findOneReplace

I am looking to locate a specific document in my database and update it with a new name and key information. Below is the Schema I'm working with: const Schema = mongoose.Schema; const vampireSchema = new Schema({ name: { type: String, required: t ...

Validation of user input alongside input masking using jQuery

One issue that I am encountering is that form inputs with assigned masks (as placeholders) are not being validated as empty by jQuery validation. I am using: https://github.com/RobinHerbots/jquery.inputmask https://github.com/1000hz/bootstrap-validator ...

Comparing totals with PHP across a multidimensional array

I have an array containing values for three consecutive dates and I need to calculate the difference between the total of values from each date. Can anyone provide suggestions on the best way to achieve this calculation? Thank you. Array ( [Nov 18, 2011 ...

Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have: <%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %> In my application.js file, I have the following code: $( document ...