Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights.

AFRAME.registerComponent('instancing', {
  schema: {
    count: {type: 'int', default: 10000}
  },

  init: function () {
    this.count = this.data.count;
    this.model = null;
  },

  update: function () {
    if (this.model !== null) { return; }

    var data = this.data;
    var el = this.el;

    var count = this.count;

    var geometry = new THREE.InstancedBufferGeometry();
    geometry.copy(new THREE.BoxBufferGeometry(10, 5, 10));

    var translateArray = new Float32Array(count*3);
    var vectorArray = new Float32Array(count*3);
    var colorArray = new Float32Array(count*3);
    var vertices = new Float32Array(count * 24);

    // Populate vertices array with random height values
    for(var i = 0; i < count; i++){
      var y = Math.floor((Math.random() * 200) + 50);
      // Populate vertices for each face of the cube
      // Code snippet truncated for brevity.
   }

    // Additional code snippets omitted for brevity.

Unfortunately, I encountered an error stating [.Offscreen-For-WebGL-0x17d96d74a000]GL ERROR :GL_INVALID_VALUE : glVertexAttribPointer: size GL_INVALID_VALUE (index):1 [.Offscreen-For-WebGL-0x17d96d74a000]GL ERROR :GL_INVALID_OPERATION : glDrawElementsInstancedANGLE: attached to enabled attrib 1 : no buffer. I'm still learning and exploring Three.js's low-level functions and started with A-Frame, but it seems like I need a more specialized approach for my project to achieve optimal performance.

I aim to have multiple cubes of different sizes positioned at various locations. Any advice or suggestions would be greatly appreciated. Thank you in advance!

Here is TheJim's solution:

https://i.sstatic.net/i46iV.jpg

Answer №1

Initially, avoid re-defining the position. The ShaderMaterial already includes common attributes like position, causing conflicts with your definition. If you prefer to define everything on your own, consider exploring RawShaderMaterial.

Secondly, keep in mind that you're setting up the vertices, indices, and normals for a SINGLE cube before leveraging shaders/instancing for additional manipulation. Only instance-specific data should be designated as InstancedBufferAttributes.

Refer to this sample:

var cubeGeo = new THREE.InstancedBufferGeometry().copy(new THREE.BoxBufferGeometry(10, 10, 10));
//cubeGeo.maxInstancedCount = 8;

cubeGeo.addAttribute("cubePos", new THREE.InstancedBufferAttribute(new Float32Array([
  25, 25, 25,
  25, 25, -25, -25, 25, 25, -25, 25, -25,
  25, -25, 25,
  25, -25, -25, -25, -25, 25, -25, -25, -25
]), 3, 1));

var vertexShader = [
  "precision highp float;",
  "",
  "uniform mat4 modelViewMatrix;",
  "uniform mat4 projectionMatrix;",
  "",
  "attribute vec3 position;",
  "attribute vec3 cubePos;",
  "",
  "void main() {",
  "",
  " gl_Position = projectionMatrix * modelViewMatrix * vec4( cubePos + position, 1.0 );",
  "",
  "}"
].join("\n");
var fragmentShader = [
  "precision highp float;",
  "",
  "void main() {",
  "",
  " gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);",
  "",
  "}"
].join("\n");

var mat = new THREE.RawShaderMaterial({
  uniforms: {},
  vertexShader: vertexShader,
  fragmentShader: fragmentShader,
  transparent: true
});

var mesh = new THREE.Mesh(cubeGeo, mat);

scene.add(mesh);

Similar to your approach, I've generated one cube initially. I then introduce an InstancedBufferAttribute known as cubePos, responsible for changing the positions of the cubes (in this case, affecting ALL vertices). This is akin to your translate attribute.

In terms of stretching the cubes, it seems promising to utilize your position attribute. To potentially achieve the desired outcome, consider naming it uniquely, such as stretch.

Personally, if uniform stretching in both directions is intended, passing a single value per instance could suffice, allowing you to scale the cube accordingly.

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

JavaScript/jQuery Tutorial: Accessing the src attribute of images sharing a common class名

How can I extract the src values of images with the same class and display them in an empty div? For instance: <body> <img class="class1" src="http://www.mysite.com/img/image1.jpg" width="168" height="168" alt=""> <img class="class ...

Redux Dilemma: Stagnant Data in Redux Repository

Struggling to pass data fetched through axios into the Redux store for use in another component. While other actions and reducers are functioning correctly, this one seems to be causing issues. Here is the flow of data: Begin in the Filter component comp ...

What is the most efficient way to utilize a single connection to interact with MongoDB?

I have a series of functions that are responsible for running various queries. Here is the code I am working with: var MongoClient = require('mongodb').MongoClient; async function createDatabase() { MongoClient.connect(urlMongoDB, function(er ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Update the color of navigation items to reflect their active status

Here is the snippet of HTML code: <header> <nav> <a href="#" id="menu-icon"></a> <ul> <li><a href="#"">Home</a></li> <li><a href="#">About</a></li> & ...

Using jQuery to load content with a dynamic variable instead of specific element IDs

I am facing a minor jQuery issue. I am trying to load a specific area of an external HTML document into a div, but instead of loading just that particular area, the entire document is being loaded. Here's the code snippet for the trigger: $('a& ...

Delineating the execution of a PHP function through a button click using HTML/Javascript

I have a need to trigger a specific PHP function by simply clicking on a button. Currently, I am working with the following code snippet: <table class='standardtable'> <tr> <th>Event</th> <th>Group</th> ...

Navigating through tabs in a Meteor application: How to maintain the active tab when using the back button

I am working on a multi-page meteor application where each page includes a navigation template. To switch between pages, I am using iron-router. The user's current page is indicated by setting the appropriate navigation link's class to 'ac ...

Looking for a bootstrap table code that includes checkboxes and a save button, so that when the save button is clicked, it

Seeking a Bootstrap table code that includes row checkboxes. When the save button is clicked, it should return the selected checkbox rows. ...

There is an issue with the function of elem.autocomplete - it is not recognized

I'm new to Angular.JS and have been struggling for the past 6 hours. I've been working on reading data from an HTTP source and displaying it as an autocomplete feature on the view. Previously, the data was displayed in a select box, but I decide ...

Using Javascript within an HTML document may not provide the intended functionality

My script: <!DOCTYPE html> <html> <head> <script> $(document).ready(function () { document.getElementById("saveForm").click(); }); </script> </head> <!--<body onload="document.getElementById('saveForm&apos ...

How should dates be formatted correctly on spreadsheets?

Recently, I have been delving into Google Sheets formats. My approach involves utilizing fetch and tokens for writing data. rows: [{ values: [ { userEnteredValue: { numberValue: Math.round(new Date().getTime() / 1000) }, userEnteredFormat: { ...

Setting up the customized filename for precompiled Handlebars templates

When compiling Handlebars templates with the NPM package, is there a way to manually adjust the name/index that is generated? In my experience using Handlebars in various environments like Rails, NodeJS, and PHP, I've observed that the generated temp ...

What is the process for reading server responses following the delivery of an alert to a designated user through socket.io?

Recently, I started exploring Socket.io and encountered an interesting challenge. My goal is to retrieve real-time location data from an Android device. To achieve this, I developed a basic application to access the current GPS coordinates. Additionally, I ...

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

What about nested elements with percentages, set positions, and fixed placements?

Picture: https://i.sstatic.net/KFNR1.png I am working on a design with a yellow container div that I want to keep at 50% width of the window. Inside this container is a purple image div that stretches to 100% of the parent container's width, and ther ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

Multiplication cannot be performed on operands of type 'NoneType'

Hello everyone, I am attempting to calculate the unit price and quantity from this table using the following model: class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max ...