@polygonjs/polygonjs
Version:
node-based WebGL 3D engine https://polygonjs.com
69 lines (68 loc) • 2.46 kB
JavaScript
"use strict";
import {
OrthographicCamera,
ShaderMaterial,
Mesh,
WebGLRenderTarget,
PlaneGeometry
} from "three";
import { HorizontalBlurShader } from "three/examples/jsm/shaders/HorizontalBlurShader";
import { VerticalBlurShader } from "three/examples/jsm/shaders/VerticalBlurShader";
const PLANE_WIDTH = 1;
const PLANE_HEIGHT = 1;
const CAMERA_HEIGHT = 1;
const BLUR_MULT = 1 / (256 * 1e3);
export class CoreRenderBlur {
constructor(res) {
this._renderTargetBlur = this._createRenderTarget(res);
this._camera = this._createCamera();
this._blurPlane = this._createBlurPlane();
this._horizontalBlurMaterial = new ShaderMaterial(HorizontalBlurShader);
this._horizontalBlurMaterial.depthTest = false;
this._verticalBlurMaterial = new ShaderMaterial(VerticalBlurShader);
this._verticalBlurMaterial.depthTest = false;
}
dispose() {
this._horizontalBlurMaterial.dispose();
this._verticalBlurMaterial.dispose();
this._renderTargetBlur.dispose();
}
setSize(w, h) {
this._renderTargetBlur.setSize(w, h);
}
_createRenderTarget(res) {
const renderTarget = new WebGLRenderTarget(res.x, res.y);
renderTarget.texture.generateMipmaps = false;
return renderTarget;
}
_createCamera() {
const camera = new OrthographicCamera(
-PLANE_WIDTH / 2,
PLANE_WIDTH / 2,
PLANE_HEIGHT / 2,
-PLANE_HEIGHT / 2,
0,
CAMERA_HEIGHT
);
camera.position.z = CAMERA_HEIGHT * 0.5;
return camera;
}
_createBlurPlane() {
const planeGeometry = new PlaneGeometry(PLANE_WIDTH, PLANE_HEIGHT);
const plane = new Mesh(planeGeometry);
return plane;
}
applyBlur(renderTarget, renderer, amountH, amountV) {
const mult = Math.max(this._renderTargetBlur.width, this._renderTargetBlur.height);
this._horizontalBlurMaterial.uniforms.tDiffuse.value = renderTarget.texture;
this._horizontalBlurMaterial.uniforms.h.value = amountH * mult * BLUR_MULT;
this._blurPlane.material = this._horizontalBlurMaterial;
renderer.setRenderTarget(this._renderTargetBlur);
renderer.render(this._blurPlane, this._camera);
this._verticalBlurMaterial.uniforms.tDiffuse.value = this._renderTargetBlur.texture;
this._verticalBlurMaterial.uniforms.v.value = amountV * mult * BLUR_MULT;
this._blurPlane.material = this._verticalBlurMaterial;
renderer.setRenderTarget(renderTarget);
renderer.render(this._blurPlane, this._camera);
}
}