I'm attempting to create a mirror-like reflection of a WebGL scene on a plane using ogl, similar to how a mirror would behave. I tried implementing a basic version of the three.js reflector but ended up with a distorted image that doesn't accurately portray a real reflection.
https://i.sstatic.net/yZ8Qf.png
I understand the concept behind the reflector - rendering the scene from the virtual reflected viewpoint of the original camera, adjusting the projection matrix of the virtual camera to only render what projects onto the plane, and then mapping the resulting texture to the plane. However, I'm not fully knowledgeable about all the computations involved (especially for the last two steps I mentioned).
All I did was replicate line by line the three.js reflector code and modify function names or references, but I can't pinpoint where I went wrong or what I may have overlooked. Any assistance would be greatly appreciated!
// objects/Reflector.js
import { Transform, Mesh, Plane, Program, RenderTarget, Camera, Vec3, Vec4, Quat, Mat4 } from 'ogl'
import { dot } from 'ogl/src/math/functions/Vec4Func'
// Import shaders
// Import math functions
export class Reflector extends Mesh {
constructor(gl, {
scene,
camera,
renderSize = 512,
clipBias = 0
}) {
// Initialize variables and setup render target...
// More implementation details...
}
update() {
// Update method coded here...
// More computations...
// Rendering logic...
}
}
// shaders/reflector.vert
precision highp float;
attribute vec3 position;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform mat4 textureMatrix;
varying vec4 vUv;
void main() {
vUv = textureMatrix * vec4(position, 1.);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.);
}
// shaders/reflector.frag
precision highp float;
uniform sampler2D diffuseMap;
varying vec4 vUv;
void main() {
vec3 diffuse = texture2DProj(diffuseMap, vUv).rgb;
gl_FragColor = vec4(diffuse, 1.);
}
Here are several self-implemented math functions needed for the project:
// math/Mat4Func.js
import { length } from 'ogl/src/math/functions/Vec3Func'
// Function definition for getRotationMatrix...
// math/PlaneFunc.js
// Function definitions for transformMat4, getCoplanarPoint, setFromNormalAndCoplanarPoint...
// math/Vec3Func.js
// Function definition for reflect...