From 79c190b9d8f382e9e553d42c9361a85e588ff36f Mon Sep 17 00:00:00 2001 From: Garima Date: Thu, 4 Jul 2024 21:33:30 +0530 Subject: [PATCH] Solves issue #7059 --- src/core/environment.js | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/core/environment.js b/src/core/environment.js index cf4444bc65..75ed27c53e 100644 --- a/src/core/environment.js +++ b/src/core/environment.js @@ -1078,6 +1078,48 @@ function exitFullscreen() { } } + +/** + * Converts 3D world coordinates to 2D screen coordinates. + * + * This function takes a 3D vector and converts its coordinates + * from the world space to screen space. This is useful for placing + * 2D elements in a 3D scene or for determining the screen position + * of 3D objects. + * + * @method worldToScreen + * @param {p5.Vector} worldPosition The 3D coordinates in the world space. + * @return {p5.Vector} A vector containing the 2D screen coordinates. + * @example + *
+ * + * + *
+ * @alt + * A 3D scene with a rotating box and a red ellipse at the screen coordinates of the world origin. + */ +p5.prototype.worldToScreen = function(worldPosition) { + const renderer = this._renderer; + if (renderer.drawingContext instanceof CanvasRenderingContext2D) { + // Handle 2D context + const transformMatrix = new DOMMatrix() + .scale(1 / pixelDensity()) + .multiply(renderer.drawingContext.getTransform()); + const screenCoordinates = transformMatrix.transformPoint( + new DOMPoint(worldPosition.x, worldPosition.y)); + return createVector(screenCoordinates.x, screenCoordinates.y); + } else{ + // Handle WebGL context + const cameraCoordinates = renderer.uMVMatrix.multiplyPoint(worldPosition); + const normalizedDeviceCoordinates = + renderer.uPMatrix.multiplyAndNormalizePoint(cameraCoordinates); + const screenX = (0.5 + 0.5 * normalizedDeviceCoordinates.x) * this.width; + const screenY = (0.5 - 0.5 * normalizedDeviceCoordinates.y) * this.height; + const screenZ = (0.5 + 0.5 * normalizedDeviceCoordinates.z); + return createVector(screenX, screenY, screenZ); + } +}; + /** * Returns the sketch's current * URL