Exploring the vertices with the updated PlaneBufferGeometry feature in ThreeJS

I've recently learned that PlaneGeometry is no longer supported and suggest using PlaneBufferGeometry in the latest updates. While my code used to function properly in versions prior to R125, I am unsure how to modify it to work with PlaneBufferGeometry:

var flagGeom = new THREE.PlaneBufferGeometry(4.5, 2.2, 40, 100, 200); // Swapped "PlaneGeometry" for "PlaneBufferGeometry" here.
flagGeom.translate(2.2, 1.1, 0);
  
  
flagGeom.vertices.forEach(v => { // Encounter an undefined error at this point.
    v.init = v.clone()
});

Answer №1

It appears that your inquiry is related to a discussion on this specific forum topic.

One approach you could consider (not the definitive solution) is utilizing an additional array stored in the userData and implementing the .setXYZ() method.

body{
  overflow: hidden;
  margin: 0;
}
<script src="https://josephg.github.io/noisejs/perlin.js"></script>
<script type="module">
console.clear();
import * as THREE from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7d3cfd5c2c2e7978996959e8897">[email protected]</a>/build/three.module.js';
import { OrbitControls } from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10647862757550203e2122293e20">[email protected]</a>/examples/jsm/controls/OrbitControls.js';

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-1, 0.5, 2).setLength(2.5);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x401000);
document.body.appendChild(renderer.domElement);

var controls = new OrbitControls(camera, renderer.domElement);

var light = new THREE.DirectionalLight(0xff5500, 2);
light.position.setScalar(10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xff0000, 1));

var loader = new THREE.TextureLoader();

// flag
var flagGeom = new THREE.PlaneGeometry(4, 2, 40, 20);
flagGeom.translate(2, 1, 0);
let pos = flagGeom.attributes.position;
flagGeom.userData = {
  init: []
}
for(let i = 0; i &l t; pos.count; i++){
  flagGeom.userData.init.push(new THREE.Vector3().fromBufferAttribute(pos, i));
}
console.log(flagGeom.userData.init);

var flagMat = new THREE.MeshStandardMaterial({
  color: 0x777777,
  map: loader.load("https://cywarr.github.io/small-shop/PW_flag/PW_flag_map.png"),
  alphaMap: loader.load("https://cywarr.github.io/small-shop/PW_f lag/PW_flag_alphaMap.png"),
  alphaTest: 0.5,
  side: THREE.DoubleSide,
  metalness: 0.5,
  roughness: 0.5
});
var flag = new THREE.Mesh(flagGeom, flagMat);
flag.position.set(-2, -1, 0);
flag.rotation.x = THREE.Math.degToRad(-18);
scene.add(flag);

// staff
var staff = new THREE.Mesh(new THREE.CylinderGeometry(0.04, 0.04, 4, 8), new THREE.MeshStandardMaterial({
  color: "black"
}));
flag.add(staff);

// background canvas texture
var canvas = document.c reateElement("canvas");
canvas.width = 128;
canvas.height = 64;

var ctx = canvas.getContext('2d');

var image = ctx.createImageData(canvas.width, canvas.height);
var data = image.da ta;

var canvasTexture = new THREE.CanvasTexture(canvas);
scene.background = canvasTexture;

window.addEventListener( 'resize', onWindowResize );

var clock = new THREE.Clock();
var delta = 0;
var time = 0;
var v = new THREE.Vector3();

render();

function render() {
  requestAnimationFrame(render);
  delta = clock.getDelta();
  time += delta;
  flagGeom.userData.init.forEach( (vi, idx) =&g t; {
    
    v.copy(vi);
    let yFade = Math.sin(v.y / flagGeom.parameters.height * Math.PI) * 0.25;
    v.x = v.x + yFade;
    let xFade = (v.x / flagGeom.parameters.width);
    v.z = noise.perlin2((v.x - (time * 2)) / flagGeom.parameters.width * 4, v.y / flagGeom.parameters.height * 2) * xFade;
    
    pos.setXYZ(idx, v.x, v.y, v.z);
  });
  flagGeom.computeVertexNormals();
  pos.needsUpdate = true;

  drawFrame(time);
  canvasTexture.needsUpdate = true;
  renderer.render(scene, camera);
}

function drawFrame(time) {

  var cWidth = can vas.width;
  var cHeight = canvas.height;

  for (var x = 0; x < cWidth; x++) {
    for (var y = 0; y < cHeight; y++) {
      var value = Math.abs(noise.simplex3(x / cWidth, y / cHeight, time * 0.25));

      var cell = (x + y * cWidth) * 4;
      data[cell] = 128 + Math.floor(128 * value);
      data[cell + 1] = Math.floor(256 * value);
      data[counter][index + 2] = 0;
      data[cell + 3] = 255; // alpha.
    }
  }

  ctx.fillColor = 'black';
  ctx.fillRect(0, 0, 100, 100);
  ctx.putImageData(image, 0, 0);

}

function onWindowResize() {

  camera.aspect = window.innerWidth / wi ndow.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize( window.innerWidth, window.innerHeight );

}

</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

What is the mechanism behind jQuery triggering the execution of JavaScript code contained in script tags that are retrieved in an AJAX response?

What is the unique ability of jQuery that allows JavaScript code inside script tags in an AJAX response to be executed? In the absence of jQuery AJAX, using eval() has been a common method to achieve this functionality as discussed in posts such as: Cal ...

Tips for transferring information to a node server

Currently, I am working with Express and facing the challenge of dynamically sending data to the app.get() method. Specifically, on my index page, there is a list of topics, and upon clicking one, I need to send the name of that element as the required dat ...

Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields. Here is the HTML code for the form: <form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader"&g ...

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

Trigger function when the element is generated

Is there a way to execute a function only once while still having it run each time a new element is created using v-for? <div v-for"value in values"> <div @ function(value, domElement) if value.bool===true @> </div> ...

Having trouble with jQuery Ajax not transmitting data properly in a CodeIgniter project?

I am brand new to the Codeigniter MVC framework. Whenever I attempt to send data through ajax from the views to the controller, I encounter an error. Please click here to view the image for more details. Here is the code snippet: views/ajax_post_view.php ...

Error message in Node.js: Unable to establish connection to 127.0.0.1 on port 21 due to E

I am currently developing a simple application using node js, and I have encountered the following issue: Error: connect ECONNREFUSED 127.0.0.1:21 at Object exports._errnoException (util.js:1034:11) at exports _exceptionWithHostPort (util.js:1057: ...

Challenges with Cross-Origin Resource Sharing (CORS) when accessing Uber API OAuth

I am encountering an issue while attempting to make client-side JS calls to Uber API endpoints that require the OAuth Bearer token, such as /v1/me. The problem arises due to the absence of the Access-Control-Allow-Origin header in the response. I have suc ...

Retrieve a document through Django's rest framework after verifying the user's credentials

Currently, I'm immersed in a project employing Django as the backend. My focus lies on utilizing Django Rest Framework to manage an API for downloading files. @detail_route(methods=['GET'], permission_classes=[IsAuthenticated]) def test(sel ...

When a d3 event is triggered by clicking, the value should be saved in a textbox

After clicking the checkbox, I would like to have all the checked client IP values automatically populate a textbox within the div called "ip." Here is my code snippet: <html> <body> <div id="ipDiv"> Client_ip :<input ty ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

How can I invoke object functions stored in an array using Javascript?

I'm currently attempting to iterate through an array of game objects and invoke their update methods. The challenge is that game objects may have different update implementations - for example, the update function for an enemy is different from that o ...

Refresh Angular 2 data after a related data update

I am facing an issue with my <select> elements in Angular. One for the Districts and another for the Cities. The districts are fetched using the getDistricts() function within the ngOnInit() function without any problems. However, I am unsure how to ...

Tips for updating the class of a button upon clicking it

I have a dilemma with my two buttons - one is green and the other has no background. I want them to change appearance when clicked, from green to one with a dashed border-bottom style. Below is the HTML code for these buttons: <div class="btns"> ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...

Filtering Array Elements in Vue JS: A Step-by-Step Guide

In my Vue Js 2.0 application, I am working on filtering elements in an array format. Here is the code snippet: const search = this.search_by_name.toLowerCase() const searchContact = this.search_by_contact.toLowerCase() return this.meetings .map(i => ...

Exploring the functionality of CodePen's code editor in relation to developing a 2D shooting game

Recently, I created a straightforward 2D shooter game with all the code neatly organized in a single HTML file: (file_gist). When I tested the game in my chrome browser, everything worked flawlessly according to my intentions. However, upon transferring th ...

Using either Javascript or JQuery to update every cell in a particular column of a table

I need to use a button to add "OK" in the Status column of table tblItem, which is initially empty. How can I achieve this using JavaScript or JQuery? The table has an id of tblItem Id Item Price Status 1 A 15 2 B 20 3 C ...

utilizing object methods to retrieve object attributes

I am currently working on developing a new application named myApp. This application includes a property called regularNameErrors and a method called populateJSON. The populateJSON method utilizes an AJAX call to retrieve a JSON object, which is then added ...