Hi, I try to create a script that deform a mesh by texture input, but isn’t working - in the function "getDisplacementValue " appear the error “texture.ressources” is undefined but I have no idea why, can anyone help me?
var Deformation = pc.createScript('deformation');
Deformation.attributes.add('strength', { type: 'number', default: 50 });
Deformation.attributes.add('waveIntensity', { type: 'number', default: 0.01 });
Deformation.attributes.add('displacementTexture', { type: 'asset', assetType: 'texture' });
Deformation.prototype.initialize = function () {
// collect positions from all mesh instances to work on
this.allMeshes = [];
const renders = this.entity.findComponents("render");
renders.forEach((render) => {
// collect positions from all mesh instances on this render component
const meshInstances = render.meshInstances;
for (let i = 0; i < meshInstances.length; i++) {
const meshInstance = meshInstances[i];
// get positions from the mesh
const mesh = meshInstance.mesh;
const srcPositions = [];
mesh.getPositions(srcPositions);
// store it
this.allMeshes.push({
mesh: mesh,
srcPositions: srcPositions,
});
}
});
this.tempPositions = [];
this.time = 0;
};
Deformation.prototype.update = function (dt) {
this.time += dt;
const displacementTex = this.displacementTexture.resource;
if (!displacementTex) {
console.error("Displacement texture not loaded.");
return;
}
for (let i = 0; i < this.allMeshes.length; i++) {
this.tempPositions.length = 0;
const srcPositions = this.allMeshes[i].srcPositions;
// loop over all positions, and fill up tempPositions array with displacement from texture
for (let k = 0; k < srcPositions.length; k += 3) {
const displacementValue = this.getDisplacementValue(displacementTex, srcPositions[k + 1]);
this.tempPositions[k] = srcPositions[k] + this.strength * displacementValue;
this.tempPositions[k + 1] = srcPositions[k + 1];
this.tempPositions[k + 2] = srcPositions[k + 2] + this.strength * displacementValue;
}
const mesh = this.allMeshes[i].mesh;
mesh.setPositions(this.tempPositions);
mesh.update();
}
};
Deformation.prototype.getDisplacementValue = function (texture, yCoordinate) {
const normalizedY = yCoordinate / texture.height; // normalize y coordinate
const texelX = 0; // assume displacement information is stored in the first texel (adjust if needed)
const texelY = Math.floor(normalizedY * texture.height);
const pixels = new Uint8Array(4); // assuming RGBA format
texture.resource.getPixels(texelX, texelY, 1, 1, pixels);
const displacementValue = (pixels[0] / 255) * 2 - 1; // normalize to range [-1, 1]
return displacementValue;
};