GithubHelp home page GithubHelp logo

pmndrs / postprocessing Goto Github PK

View Code? Open in Web Editor NEW
2.2K 36.0 205.0 155.3 MB

A post processing library for three.js.

License: zlib License

JavaScript 81.58% GLSL 12.60% SCSS 4.67% HTML 1.16%
post-processing image-effects real-time webgl image-processing three-js effects composer 2d-filter-effects

postprocessing's Introduction

Post Processing

CI Version

A post processing library for three.js.

Demo · Sandbox · Documentation · Wiki

Installation

This library requires the peer dependency three.

npm install three postprocessing

Usage

Post processing introduces the concept of passes and effects to extend the common rendering workflow with fullscreen image manipulation tools. The following WebGL attributes should be used for an optimal post processing workflow:

import { WebGLRenderer } from "three";

const renderer = new WebGLRenderer({
	powerPreference: "high-performance",
	antialias: false,
	stencil: false,
	depth: false
});

The EffectComposer manages and runs passes. It is common practice to use a RenderPass as the first pass to automatically clear the buffers and render a scene for further processing. Fullscreen image effects are rendered via the EffectPass. Please refer to the usage example of three.js for more information on how to setup the renderer, scene and camera.

import { BloomEffect, EffectComposer, EffectPass, RenderPass } from "postprocessing";

const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new EffectPass(camera, new BloomEffect()));

requestAnimationFrame(function render() {

	requestAnimationFrame(render);
	composer.render();

});

Output Color Space

New applications should follow a linear workflow for color management and postprocessing supports this automatically. Simply set WebGLRenderer.outputColorSpace to SRGBColorSpace and postprocessing will follow suit.

Postprocessing uses UnsignedByteType sRGB frame buffers to store intermediate results. This is a trade-off between hardware support, efficiency and quality since linear results normally require at least 12 bits per color channel to prevent color degradation and banding. With low precision sRGB buffers, colors will be clamped to [0.0, 1.0] and information loss will shift to the darker spectrum which leads to noticable banding in dark scenes. Linear, high precision HalfFloatType buffers don't have these issues and are the preferred option for HDR-like workflows on desktop devices. You can enable high precision frame buffers as follows:

import { HalfFloatType } from "three";

const composer = new EffectComposer(renderer, {
	frameBufferType: HalfFloatType
});

Tone Mapping

Tone mapping is the process of converting HDR colors to LDR output colors. When using postprocessing, the toneMapping setting on the renderer should be set to NoToneMapping (default) and high precision frame buffers should be enabled. Otherwise, colors will be mapped to [0.0, 1.0] at the start of the pipeline. To enable tone mapping, use a ToneMappingEffect at the end of the pipeline.

Note that tone mapping is not applied to the clear color when using only the renderer because clearing doesn't involve shaders. Postprocessing applies to the full input image which means that tone mapping will also be applied uniformly. Consequently, the results of tone mapping a clear color background with and without postprocessing will be different, with the postprocessing approach being correct.

Performance

This library provides an EffectPass which automatically organizes and merges any given combination of effects. This minimizes the amount of render operations and makes it possible to combine many effects without the performance penalties of traditional pass chaining. Additionally, every effect can choose its own blend function.

All fullscreen render operations also use a single triangle that fills the screen. Compared to using a quad, this approach harmonizes with modern GPU rasterization patterns and eliminates unnecessary fragment calculations along the screen diagonal. This is especially beneficial for GPGPU passes and effects that use complex fragment shaders.

Performance Test

Included Effects

The total demo download size is about 60 MB.

Custom Effects

If you want to learn how to create custom effects or passes, please check the Wiki.

Contributing

Please refer to the contribution guidelines for details.

License

This library is licensed under the Zlib license.

The original code that this library is based on, was written by mrdoob and the three.js contributors and is licensed under the MIT license.

postprocessing's People

Contributors

arpu avatar beilinson avatar chasedavis avatar codyjasonbennett avatar danrossi avatar donmccurdy avatar furiouzz avatar gitplus avatar hexafield avatar martin31821 avatar pontushorn avatar renaudcollet avatar superguigui avatar suprhimp avatar unphased avatar vanruesc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postprocessing's Issues

Texture pass and backgrounds demo

https://threejs.org/examples/?q=post#webgl_postprocessing_backgrounds

I've tried various combinations of TexturePass with no luck so far - however, everything else works great :) !

  this.composer = new POSTPROCESSING.EffectComposer( this.renderer );
  this.texturePass = new POSTPROCESSING.TexturePass();
  this.texturePass.renderToScreen = true;
  this.composer.addPass( this.texturePass );

  var self = this;
  var textureLoader = new THREE.TextureLoader();
  textureLoader.load( window.appBase + "/img/bg.jpg", function( map ) {
    self.texturePass.map = map; //Able to console log this out.
  });

Do you have any working examples of TexturePass being used with static backgrounds like in the example above?

OutlineEffect doesn't work

I try to use the outlineEffect, but it doesn't work,and there is no error or other useful info about it.
Can someone give me some help?

  initPostprocess() {
    this.composer = new EffectComposer(this.view.renderer, {
      stencilBuffer: true
    });
    this.renderPass = new RenderPass(this.world.scene, null);
    this.renderPass.renderToScreen = true;

    this.outlineEffect = new OutlineEffect(
      this.world.scene,
      this.viewer.camera,
      {
        edgeStrength: 10,
        pulseSpeed: 0.0,
        visibleEdgeColor: 0xffffff,
        hiddenEdgeColor: 0x22090a,
        blur: false,
        xRay: true
      }
    );
    this.outlinePass = new EffectPass(this.viewer.camera, this.outlineEffect);
    this.renderPass.renderToScreen = false;

    const mesh = new Mesh(
      new BoxBufferGeometry(1, 1, 1),
      new MeshPhongMaterial({
        color: 0x00ffff
      })
    );
    this.world.addObject(mesh);
    this.outlineEffect.setSelection([mesh]);
    this.composer.addPass(this.outlinePass);
  }

 update(delta) {
    this.composer.render(delta);
  }

FilmPass && SMAAPass == blackscreen

Hi,

I try to use postprocessing with aframe.

I can use FilmPass and SMAAPass individualy, but when i try to use both, boom black screen.

import { EffectComposer, FilmPass, RenderPass, SMAAPass } from "postprocessing"

const composer = new THREE.EffectComposer(renderer)
// have to use THREE.EffectComposer instead of EffectComposer because of aframe.
const renderPass = new RenderPass(scene, camera)

const filmPass = new FilmPass({
      grayscale: false,
	sepia: false,
	vignette: true,
	eskil: false,
	scanlines: false,
	noise: true,
	noiseIntensity: 0.5,
	scanlineIntensity: 0.5,
	scanlineDensity: 1.5,
	greyscaleIntensity: 1.0,
	sepiaIntensity: 1.0,
	vignetteOffset: 0.5,
	vignetteDarkness: 0.5
    })

    const smaaPass = new SMAAPass(Image)

    smaaPass.renderToScreen = true

    composer.addPass(renderPass)
    composer.addPass(filmPass)
    composer.addPass(smaaPass)

Maybe you can help ?

Thanks you !

Shockwave pass - delta undefined in the render loop

Actually I'm trying ShockWavePass but I had problems to make it work.
I noticed after some inspects that the problem comes from ShockWavePass.js

render(renderer, inputBuffer, outputBuffer, delta, stencilTest) {

		const epicenter = this.epicenter;
		const mainCamera = this.mainCamera;
		const screenPosition = this.screenPosition;

		const shockWaveMaterial = this.shockWaveMaterial;
		const uniforms = shockWaveMaterial.uniforms;
		const center = uniforms.center;
		const radius = uniforms.radius;
		const maxRadius = uniforms.maxRadius;
		const waveSize = uniforms.waveSize;

		this.copyMaterial.uniforms.tDiffuse.value = inputBuffer.texture;
		this.setFullscreenMaterial(this.copyMaterial);

		if(this.active) {

			// Calculate direction vectors.
			mainCamera.getWorldDirection(v);
			ab.copy(mainCamera.position).sub(epicenter);

			// Don't render the effect if the object is behind the camera.
			if(v.angleTo(ab) > HALF_PI) {

				// Scale the effect based on distance to the object.
				uniforms.cameraDistance.value = mainCamera.position.distanceTo(epicenter);

				// Calculate the screen position of the epicenter.
				screenPosition.copy(epicenter).project(mainCamera);
				center.value.x = (screenPosition.x + 1.0) * 0.5;
				center.value.y = (screenPosition.y + 1.0) * 0.5;

				uniforms.tDiffuse.value = inputBuffer.texture;
				this.setFullscreenMaterial(shockWaveMaterial);

			}

			// Update the shock wave radius based on time.
			this.time += delta * this.speed;
			radius.value = this.time - waveSize.value;

			if(radius.value >= (maxRadius.value + waveSize.value) * 2) {

				this.active = false;

			}

		}

		renderer.render(this.scene, this.camera, this.renderToScreen ? null : outputBuffer);

	}

where delta on my code it's undefined.
I made a quick test, set delta = 0.016 ( like a 60fps rate) and everything runs perfectly.
That's weird.

Help on focusing

Hi! First of all, thanks for the lib, it's a great one!

I'm trying to use the BokehPass, but I'm having troubles focusing the elements. Even though I have my meshes with considerable space between each other, I can only seem to focus all or none of them.

It looks like all of the meshes are on the same plane and I'm either focusing it or not — which is not true, they have different depth coordinates.

I can show a snippet of the setup, but I'm just following the code on the Demo.

I'm using version4.3.2 of the lib, with Chrome 64.0.3282.186 on a 2017 Macbook Pro.

Thanks in advance!

Question: Why you use #define to define a function ? What's the different ?

Hi, thanks for your great job!
I am learning SMAA and diving into the source code of it.
In smaa-weights/shader.frag, there is a line:

#define sampleLevelZeroOffset(t, coord, offset) texture2D(t, coord + float(offset) * texelSize, 0.0)

I don't know the different between #define sampleLevelZeroOffset and vec4 sampleLevelZeroOffset(...).
Could you tell me more about this ?
Thanks !

Better default value for Pass.needsSwap

Passes that render to the provided writeBuffer currently have to set a special needsSwap flag to true. This tells the EffectComposer that the writeBuffer must be swapped with the readBuffer before the next pass can be executed. In reality, though, almost all passes render to the writeBuffer. Passes that don't do it are special cases: TexturePass, RenderPass, ClearPass, MaskPass, ClearMaskPass and SavePass.

Three of these passes, namely the TexturePass, RenderPass and ClearPass, can easily be changed to render to the writeBuffer. The other two passes,ClearMaskPass and SavePass, are the only ones that can't render to the writeBuffer.

To reduce boilerplate code, the default value of the needsSwap flag should be inverted. Then, only the special passes that deviate from the usual input-output flow need to change the flag. It might also be a good idea to rename the readBuffer and writeBuffer to inputBuffer and outputBuffer to further clarify their purpose.

Angular CLI build --prod issue

I've added postprocessing to my project, but when I try to build it, I get the following error:

ERROR in vendor.f88364d9ba59a6c23726.bundle.js from UglifyJs
Unexpected token: name (AdaptiveLuminosityMaterial_AdaptiveLuminosityMaterial) [vendor.f88364d9ba59a6c23726.bundle.js:124902,6]

From what I've read, it has something to do with es6? It bulds fine as long as it doesn't run through uglify. Any help would be greatly appreciated.

Thanks!

Use TextureEffect as material

Is there any way to use a TextureEffect as material from an object?
I need to use blend mode on a texture in a plane, the texture is transparent and need to affect the color of the object behind.
I tried to look into source code and documentation but did not find anyway to do that by myself.

Edit: Works for me if i am able to use an BlendMode on a Three.MeshBasicMaterial as well.

Thanks a lot!

Blurry results on retina display.

The renderer pixelRatio property gets ignored when setting the size of the THREE.WebGLRenderTarget. This results in a write and read buffer that's 1/4 the size (pixelRatio = 2) of the canvas which means the rendered result gets upscaled and will look blurry on screens with a higher pixelRatio. You can fix this by multiplying the width and height with the pixelRatio when setting the size of the THREE.WebGLRenderTarget.

const pixelRatio = this.renderer.getPixelRatio();
new THREE.WebGLRenderTarget(size.width * pixelRatio, size.height * pixelRatio, ...

postprocessing_retina

I can send a pr when I find some time.
:)

GodRays parameters not used by the pass class

I'm running some tests with the GodRays pass. The demo (https://vanruesc.github.io/postprocessing/public/demo/#god-rays) provides a lot of parameters like density, decay, weight, etc. which are actually present in the class constructor comments.
`export class GodRaysPass extends Pass {

/**
 * Constructs a new god rays pass.
 *
 * @param {Scene} scene - The main scene.
 * @param {Camera} camera - The main camera.
 * @param {Object3D} lightSource - The main light source.
 * @param {Object} [options] - The options.
 * @param {Number} [options.density=0.96] - The density of the light rays.
 * @param {Number} [options.decay=0.93] - An illumination decay factor.
 * @param {Number} [options.weight=0.4] - A light ray weight factor.
 * @param {Number} [options.exposure=0.6] - A constant attenuation coefficient.
 * @param {Number} [options.clampMax=1.0] - An upper bound for the saturation of the overall effect.
 * @param {Number} [options.intensity=1.0] - A constant factor for additive blending.
 * @param {Number} [options.resolutionScale=0.5] - The render texture resolution scale, relative to the screen render size.
 * @param {Number} [options.kernelSize=KernelSize.LARGE] - The blur kernel size.
 * @param {Number} [options.samples=60] - The number of samples per pixel.
 * @param {Number} [options.screenMode=true] - Whether the screen blend mode should be used for combining the god rays texture with the scene colors.
 */`

But some of them have no effect, since they don't seem to be actually used by the class.
These 'ghost' parameters are:

  • density
  • decay
  • weight
  • exposure
  • clampMax
    There is also a blurriness parameter in the demo which isn't in the class.

Am I missing something?

Messing up loaded .obj geometry (hidden vertices?)

Hello,

First of all very great library, the effects are beautiful!

I'm having an issue with loaded .obj models. No matter which pass I apply (except the RenderPass), one of my model (random) will have its geometry messed up (some vertices are non visible).

I have set up an example here, where you can see that one of the cube will be almost non existant: http://mchrbn.net/test/

My JS code here: https://pastebin.com/78HQpceD (from line 64)

Tests I did:

  • It seems to happen only with loaded models, with three.js internal objects it works fine (ie: BoxGeometry, ...)
  • I do not have this problem with the postprocessing library used on the three.js website

Version of the library: 4.3.2
The issue happens on various browsers, even Internet Explorer.

Thanks!

OutlinePass no longer detects hidden edges

The hidden edge detection functionality of the OutlinePass is currently broken.

One reason for this is that the depth render target format has been changed to RGB in 4a13895 while the depth packing method is set to RGBADepthPacking. Furthermore, an incorrect refactoring was performed in 156d893 which broke depth comparison.

SSAO does nothing but other effects work perfectly

First of all thanks for the great lib, but I'm having some issues with SSAO.

Other effects work fine, I added a BLOOM and it's working perfectly, but for some reason SSAO doesn't work at all..

I tried to look at the demo but it is obfuscated (index.min.js), would be a lot easier to test stuff with a demo with raw code online.

I saw in the demo that there's a SMAA applied before the SSAO, is this required?

I can't test with SMAA because I'm not sure how to generate the SMAA images and the docs seems outdated (SMAAPassareaImageDataURL should be replaced with SMAAEffect.areaImageDataURL).

Here's my code:

                    this.composer = new EffectComposer(this.renderer);
		
		this.renderPass = new NormalPass(this.scene, this.camera, {
			resolutionScale: 1.0
		});

		this.bloomPass = new EffectPass(this.camera, new BloomEffect());
		
		this.ssaoPass = new SSAOEffect(this.camera, this.renderPass.renderTarget.texture, {
			blendFunction: BlendFunction.MULTIPLY,
			samples: 11,
			rings: 4,
			distanceThreshold: 0.6,
			distanceFalloff: 0.1,
			rangeThreshold: 0.0015,
			rangeFalloff: 0.01,
			luminanceInfluence: 0.7,
			radius: 18.25,
			scale: 1.0,
			bias: 0.5
		});

		this.ssaoPass.blendMode.opacity.value = 1.5;

		this.copyPass = new EffectPass(this.camera, this.ssaoPass);
		this.copyPass.renderToScreen = true;

		this.composer.addPass(new RenderPass(this.scene, this.camera));
		this.composer.addPass(this.bloomPass);
		this.composer.addPass(this.copyPass);

Any idea what's going on?

Thanks

Using multiple passes

Is it possible to use multiple passes in the same effect composer? When I try to add a new one, it looks like nothing is rendered. Thank you for your time :)

Version: 4.10.0
Browser: Latest Chrome - MacOS

    this.composer = new EffectComposer(this.renderer, {
      stencilBuffer: true,
      depthTexture: true
    });

    this.renderPass = new RenderPass(this.scene, this.camera);

    this.composer.addPass(this.renderPass);
    this.renderPass.renderToScreen = false;

    this.pass = new ShockWavePass(this.camera, new THREE.Vector3(0, 0, 0), {
      speed: 1.9,
      maxRadius: 7.0,
      size: 2,
      waveSize: 2,
      amplitude: 0.2
    });
    this.pass.renderToScreen = true;
    this.composer.addPass(this.pass);

    const bloomPass = new BloomPass({
      resolutionScale: 0.5,
      intensity: 2.0,
      distinction: 4.0
    });

    bloomPass.renderToScreen = true;
    this.bloomPass = bloomPass;
    this.composer.addPass(bloomPass);

uglify

It looks like it is impossible to use this plugin in a project that builds using UglifyJsPlugin, that is quite usual in production. This is my webpack config file

/* eslint-env node */
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');


module.exports = {
	target: 'web',
	devtool: 'source-map',
	entry: './src/application.js',
	output: {
		path: path.resolve(__dirname, 'www'),
		filename: 'bundle.js',
		publicPath: ''
	},
	plugins: [
		new HtmlWebpackPlugin({
			title: 'Example',
			filename: 'index.html'
		}),
        new webpack.optimize.OccurrenceOrderPlugin(),
		new webpack.DefinePlugin({
		  'process.env': {
			'NODE_ENV': JSON.stringify('production')
		  }
		}),
		new webpack.optimize.UglifyJsPlugin({
		  compressor: {
			warnings: false
		  }
		})
	],
	module: {
		rules: [
			{
				test: /\.js$/,
				include: [
					path.resolve(__dirname, 'src')
				],
				loader: 'babel-loader',
				query: {
					compact: true,
					presets: [
						['es2015', {modules: false}]
					]
				}
			}
		]
	},
	performance: {
		hints: false
	}
};

And this is the error I'm having:

ERROR in bundle.js from UglifyJs
Unexpected token: name (Pass) [bundle.js:44195,6]

ShaderPass documentation / help

Hi there,

Relatively new to Threejs and find myself trying to add in my own shader to achieve a look. I've used the standard THREE.ShaderMaterial and got that working but I can't seem to get that working with this library and the effect composer. Assuming that's the expected behaviour I then tried to create a shader object and pass it to the ShaderPass. However, I'm totally stuck on how I should construct this as most of what I can gather you simply pass in the 'shader' i.e. new ShaderPass(SomeShaderObject) but that doesn't seem right (doesn't work either as far as I can see - but I am still learning this all).

How do I set this up so as to pass in the scene, camera etc. and have my shader used as part of the effect composer pipeline?

Cheers.

OutlinePass animation problem

Hello,

first of all thank you for your hard work on this library.

When I tried to use the OutlinePass effect, I found that it works well for static meshes, but when I try to play an animation, the outline does not follow the moving mesh parts. Is there any way to resolve this?

A minimal project for reproducing the problem is here: https://github.com/erosb/outlinepass-bug
After cloning,

  • run npm install && npm run-script build
  • load it with any static HTTP server
  • from the browser dev console run eg. playAnim("attack_3")

You can find it running here: http://erosb.github.io/outlinepass-bug/

Environment:

  • Tested in Chrome and Firefox
  • ubuntu 16.04
  • NVidia GeForce GTX 960

Thank you for your time.

Unreal Bloom

Hi,
Do you have any plan to include the unreal bloom effect inside postprocessing effects ? (already included bloom seems to not achieve the same effect).
If not, do you have any hint or feedback on the feasibility to use the unreal bloom effect associated with postprocessing framework ? (wiki guidelines on custom passes may be helpful ?)

Thanks,

Outline effect pass fills entire screen after clearing selection

When creating and outline effect and starting with an empty selection everything is displayed fine without any outline.

When selecting objects with selectObject() or setSelection() everything is still fine and the outline is visible.

After clearing the selection using clearSelection() or deselectObject() the effect pass fills the whole screen with the outline color.

Absolutely incredible work on v5 - examples of chaining shaders, new comparative performance benchmarks?

I was reviewing your changes for the past couple hours, seeing where all that work went into for the v5 PR and #82 milestone. It's incredible how much time and thought you put into this.

Correct me if I'm wrong but this combines passes much more efficiently than the ThreeJS EffectPass class because you are combining shaders and running a single pass rather then multiple passes over each?

I'd love to see some examples of chaining shaders together, I can even submit a PR for that to add to your examples for FPS experimentation.

Bloom Pass: Shader couldn't compile for 'linearToRelativeLuminance'.

Hi, thanks you for this library, it's amazing.

It's the first time that i find a problem that I'm not able to solve related to your library.

OS: Windows 7 x64
Chrome Version: 61.0.3163.100

My problem is the following.

I have this error in console only when BloomPass is active.

THREE.WebGLShader: Shader couldn't compile
THREE.WebGLShader: gl.getShaderInfoLog() fragment ERROR: 0:171: 'linearToRelativeLuminance' : no matching overloaded function found
THREE.WebGLProgram: shader error:  0 gl.VALIDATE_STATUS false gl.getProgramInfoLog invalid shaders
ERROR: 0:171: 'linearToRelativeLuminance' : no matching overloaded function found
WebGL: INVALID_OPERATION: useProgram: program not valid

Complete Error Stack Trace

I'm working on Angular4 and Typescript and I've tested the application in Angular2 Too, but the error stack trace is the same.
I've tested it only on Chrome, and I don't know if error appears on other browsers.

I've also tried to take a look at the shader program, but my knowledge in OpenGL are very limited and I've not been able to find a solution.

Can you help me to understand what went wrong?

SMAAPass depends on the main clear color.

The SMAAPass breaks if the clear color of the renderer is not black.

It indirectly uses this clear color to clear the color edges buffer renderTargetColorEdges, but should use its own ClearPass instead.

Cannot read property 'blendFunction' of undefined

Expect behavior

I'd like to use ShaderPass with my custom shader.

Actual behavior

Trying to setup a ShaderPass I get this error.

Uncaught TypeError: Cannot read property 'blendFunction' of undefined

Code

  import * as POST from "processing";

  const uniforms = { 
    // my uniforms
  }
  const shaderSettings = {
    uniforms: {
      "tDiffuse": { value: null },
      ...uniforms
    },
    // get vertex and fragment from HTML script
    vertexShader: document.getElementById("vertexFilter").textContent,
    fragmentShader: document.getElementById("fragmentFilter").textContent,
  };

  const renderPass = new POST.RenderPass(scene, camera);
  const effectPass = new POST.EffectPass(camera, new POST.ShaderPass(shaderSettings));
  effectPass.renderToScreen = true;
  effectComposer = new POST.EffectComposer(renderer);
  effectComposer.addPass(renderPass);
  effectComposer.addPass(effectPass);

Version

postprocessing: ^5.0.0

Antialiasing disabled when using Godrays

I'm using the Godrays pass, which works well.
But then, the antialiasing seems to be disabled. Is it possible to have both antialiasing and a godrays pass?

I'm thinking one solution could be to use a SMAA pass, but I've no idea how it supposed to work.
After some digging, I've realized that the demo page
https://github.com/vanruesc/postprocessing/blob/master/demo/src/demos/SMAADemo.js
and the actual class
https://github.com/vanruesc/postprocessing/blob/master/src/passes/SMAAPass.js
were quiet different, which adds to my confusion :)

Clarification regarding Masking

Hi. I'm new with three js and with postprocessing.
Could you please clarify, is there some examples how to create/use mask?
Thanks in advance

Aframe or WebVR mode

Hi there,

I'm working on creating vignette effect for WebVR/Aframe to create the tunnel vision.
I'm wondering that whether the library can work in VR mode, or it can only work with 2D screens?
Looking forward to hearing back from you!

Thanks,
Tony

BloomFilter broken on Edge > 38

After some initial digging, it seems that the 'range' value of the LuminosityMaterial needs to be defined as a 2d Vector rather than null, if no range is specified.

I haven't had time to build out an example case but if this is something you want to address, I'll happily expand on this tomorrow when I have a dab more time!

Why 'type' param is passed as material parameter?

FXAA

Does the postprocessing module support an equivalent to the FXAA pass in the three.js example code?

Module should point to ES build

Hello @vanruesc ,
Thanks for your amazing work with this postprocessing library for Three.js!

However, I have some problems with making UglifyJS while building module that includes your library. And this happens because of this line(7):
image

Could you please make it something like: "module": "build/postprocessing.module.js" which is a completely ES5 (thanks, Babel) except that it has ES6 harmony module syntax in exporting (or importing external libraries)

For example, in RollupJS such option is possible if you specify format: 'es'. https://rollupjs.org/guide/en#exporting

SMAAPass on a render target

Hello. Thanks a lot for this amazing library! It's the first time i'm using it, so apologies if my question is kind of stupid.

I am creating a tool to export high resolution images for prints from Three.js, like 16K x 16K pixels. It works well: i'm rendering on a large render target and then creating a PNG from there. Only problem: I learnt that rendering on a render target disables the antialisasing.

So the only way to get it, is by using something like SMAAPass. All the other filters work perfectly and i can export the PNG with those effects. But with SMAAPass I have an error in the console: THREE.WebGLRenderer: Texture marked for update but image is incomplete Texture. This happens with low resolution exports, any size, consistently.

Here is what i'm doing:

const composer = new EffectComposer(renderer)
composer.addPass(new RenderPass(scene, camera))
const pass = new SMAAPass(window.Image)
composer.addPass(pass)
composer.render()

const rtt = this.composer.writeBuffer
renderer.readRenderTargetPixels( rtt, 0, 0, size.width, size.height, array )
// and here i convert the array to PNG

The result is a png perfectly rendered but with no antialias and the error in the console. Do you think there could be a way to solve this?

Question: What are SMAA search and area images?

In your demo with SMAA you pass both these images to the SMAAPass. What are they for? I'm a little puzzled. I have no textures in my render scene. Documentation does not explain that properly. Why are these two images needed, what are they, and how can I generate them?

(I need fast and reliable anti-aliasing since chrome-antialiasing fails on some devices)

OutlinePass

When assigning array to pass.selection nothing happens, must use pass.selectObject instead.
It can be fixed ?

Also there is no antialiasing working when enabled in WebGLRenderer, am I doing something wrong ?

Thanks.

Disabling the effect produces a black screen

Hi, I'm using the GlitchPass and i want to activate/deactivate the effect only when an event is triggered. I'm using .enabled=false to deactivate the effect, but this turns the whole screen black.

General questions about your shaders and render pipeline

I was looking through the open issues hoping someone would have congratulated you on getting all of these examples to work so well with the r92 build. Congratulations this is awesome work!

I can speculate why you went through so much effort to build this postprocessing lib separate from the Three repo - but I'm curious to hear you explain it for yourself :)

  • What was the reasoning behind creating this lib in the first place?
  • How does your render pipeline differ from Three.js and is there any performance benefits?
  • Are the shaders direct ports from Three.js ones or have you modified/optimized many of them?

GodRaysEffect skinning support

GodRaysEffect currently doesn't support masking skinned meshes. Enabling skinning on renderPassMask.overrideMaterial fixes the issue, but maybe there's a more efficient way?

Rendering Pipeline Improvements

Introduction

The purpose of the postprocessing library is to provide a package of well maintained and up-to-date filter effects for three.js. While there are already many improvements in place, the current code base of this library still roughly mirrors the postprocessing examples from three.js and operates according to the following principles:

  • The EffectComposer maintains a list of passes.
  • The user adds various kinds of passes that modify the rendered scene colors consecutively.
  • Any pass may render to screen.

This processing flow is quite simple and easy to use, but it's not very efficient.

Pipeline Problem

The postprocessing library currently operates in a wasteful manner when multiple passes are being used. The biggest issue that prevents optimal performance is that almost every pass performs at least one expensive fullscreen render operation. Using a variety of interesting filter effects comes at a price that doesn't justify the results.

For the next major release v5.0.0 I'd like to replace the current naive approach with a more sophisticated one by introducing the concept of effects to improve performance and tighten some loose ends.

Merging Passes

The goal of most passes is to modify the input pixel data in some way. Instead of expecting each pass to write its result to a frame buffer just for the next pass to read, modify and write more pixels again, all of the work could be done in one go using a single fullscreen render operation. With the aim to improve performance, some passes already consist of multiple effects. When a pass is designed that way, it only needs to perform a single render operation, but it also becomes bloated and rigid. In terms of maintainability, cramming all the existing shaders into one is not exactly an option.

Still, there should be a mechanism that merges passes to minimize the amount of render operations globally.

Of course, there's more than one way to implement this feature, but passes should be merged whenever possible. This means that the user shouldn't be able to accidentally degrade performance. With this in mind, the merge process could either be automatic or explicit. In my opinion, it should be explicit to allow for more control. The convenience of a fully automatic merge mechanism is questionable because it could easily become unpredictable and difficult to handle due to its implicit nature. It goes without saying that the merge process should be as simple as possible and crystal clear.

EffectPass

At a closer look, passes can be divided into four groups. The first group consists of passes that render normal scenes like the RenderPass and MaskPass. The second type doesn't render anything, but performs supporting operations. For example, the ClearMaskPass belongs to that group. Passes that render special textures make up the third group. GPGPU passes are a good example for this group. The fourth and most prominent group contains the fullscreen effect passes. Only this last group of passes can be merged.

To devise a clean and efficient merge strategy, be it automatic or manual, these effect passes must be treated as a special case. Such passes actually contain effects and act only as carriers that eventually render them. Merging would only focus on the effects within the passes. Hence it makes sense to separate effects from passes. To further enhance the concept of effects, there should be only one pass that can handle effects.

In other words, there should be a monolithic EffectPass that is similar to the RenderPass. While the RenderPass can render any Scene, the EffectPass would be able to render any Effect and it would take care of merging multiple effects. This not only improves performance substantially but also reduces boilerplate code and guarantees an optimal processing order. For example, cinematic noise should not be applied before antialiasing. This approach is explicit in that the user adds effects to a specialized pass and expects it to organize them efficiently. It's also automatic in that the merging process itself remains hidden.

Note that once a merge mechanism is in place, it will no longer be necessary to maintain bloated shaders. Complex passes can then safely be split into more fine-grained effects without losing the performance benefits of compound shaders.

Effects

The new Effect class will be very similar to the Pass class. An Effect must specify a fragment shader and a vertex shader according to a simple standard that will closely follow the one that Shadertoy uses. It may also declare custom defines and uniforms. Just like passes, effects may perform initialization tasks, react to render size changes and execute supporting render operations if needed but they don't have access to the output buffer and are not supposed to render to screen by themselves. Instead of a render method, they would have something like an onBeforeRender method.

Consequences

Since the shaders from the chosen effects will be baked into a single shader, enabling or disabling one effect at runtime would require a slow recompilation of the shader program. As an alternative, the user can prepare multiple EffectPass instances with the desired effect combinations and enable or disable these passes as needed. This is also a reason why a purely automatic merge system would cause trouble.

Besides the performance and coordination advantages, this new approach would allow every effect to choose its own blend mode from a list of built-in functions. An option to disable blending altogether would also be available to handle advanced compositing use cases in a very natural fashion.

Another interesting feature would be inter-effect-communication. Since effects will ultimately reside in the same shader program, they could easily declare output variables for other effects. For example, a chromatic abberation effect could optionally be influenced by a preceding bokeh effect.

One restriction that rarely becomes an issue is the limit on the amount of uniforms that can be used in a single shader program. With the monolithic EffectPass approach, this limit may be reached more quickly than usual. If that happens the EffectPass will inform you about it and you'll either have to reduce the number of effects or use multiple EffectPass instances. Most effects don't require additional varying fields so there shouldn't be an issue with that. However, some effects may use multiple varyings for UV-coordinates to optimize texel fetches. This case will be treated similarly and limitations will be reported to the user accordingly.

Conclusion

At this point, it's hard to tell whether the presented changes can live up to the expectations. I did consider other options, but none of them looked as promising as the EffectPass approach.

I'll try it out first to see if there are any hidden problems. In the meantime, feel free to share your thoughts.

✌️

RealisticBokehPass

Hi. I'm trying to use the RealisticBokehPass. I've took this sample
But for me it doesn't work. Also I was trying to use BokehPass and it works.
Here is my code:

import { Injectable } from '@angular/core';
import {Camera, Clock, DepthTexture, Scene, WebGLRenderer} from "three";
import * as THREE from 'three';



import '../EnableThreeExamples.js';
import '@root/node_modules/three/examples/js/postprocessing/EffectComposer.js';
import '@root/node_modules/three/examples/js/shaders/CopyShader.js';
import '@root/node_modules/three/examples/js/postprocessing/ShaderPass.js';

import {BokehPass} from '@root/node_modules/postprocessing/src/passes/BokehPass.js';
import {RealisticBokehPass} from '@root/node_modules/postprocessing/src/passes/RealisticBokehPass.js';


import {RenderPass} from "postprocessing";




@Injectable()
export class CameraControllerService {

  postprocessing = {};

  bokehPass;

  renderPass;
  composer;

  pass;

  clock = new Clock();

  constructor(private camera:Camera, private scene:Scene, private renderer:WebGLRenderer) {

    this.composer = new THREE.EffectComposer( renderer, new THREE.WebGLRenderTarget( 800, 600 ) );


    this.renderPass = new RenderPass(scene, camera);
    this.bokehPass = new RealisticBokehPass(camera, {
      // focus: 0.5,
      // dof: 0,
      // aperture: 0.15,
      // maxBlur: 0.1

      rings: 5,
      samples: 5,
      showFocus: false,
      manualDoF: true,
      vignette: true,
      pentagon: true,
      shaderFocus: true,
      noise: false,
      maxBlur: 2.0,
      luminanceThreshold: 0.15,
      luminanceGain: 3.5,
      bias: 0.25,
      fringe: 0.33

    });

    this.renderPass.renderToScreen = false;
    this.bokehPass.renderToScreen = true;


    this.composer.addPass(this.renderPass);
    this.composer.addPass(this.bokehPass);




  }

  updateDOF(){

    const time = this.clock.getDelta();//performance.now() * 0.001;
    this.composer.render(time);
  }

}

Thanks in advance

Not working with ie11

Hi,

It seems like the effects do not work on IE11.
I'm working with webpack and whenever I try to import and use a postprocessing class I get a weird syntax error pointing to this beauty:
capture
I eventually noticed that when I'm using IE, the demo page doesn't work either.
https://vanruesc.github.io/postprocessing/public/demo/

Is it even supposed to work on IE did you give up on it? :)

Anyway, thanks!

Outline Pass

In the THREE.js examples there's an outline pass example that I want to use. Would you accept a PR with it (If I updated it toyour current code style, etc...)?

TexturePass can't really render to screen

The TexturePass can render a texture to screen, but when it does that it also ignores the input buffer. If the pass doesn't render to screen, it uses a CopyMaterial to additively blend its texture with the input buffer.

The TexturePass should use the CombineMaterial instead to always blend the texture with the input buffer.

.shading has been removed. Use the boolean .flatShading instead.

Hi,

I encountered a problem when I tried to add a pass with the three.js rj86 version.

For example with the BloomPass :

const bloomPass = new BloomPass({
  resolutionScale: 0.5,
  intensity: 2.0,
  distinction: 4.0,
});
THREE.LuminosityMaterial: .shading has been removed. Use the boolean .flatShading instead.
THREE.ConvolutionMaterial: .shading has been removed. Use the boolean .flatShading instead.
THREE.CombineMaterial: .shading has been removed. Use the boolean .flatShading instead.

I also tried the BlurPass and I have overall the same error.

version: [email protected]

THREE.WebGLShader: Shader couldn't compile.

I use Webpack and file-loader for *.vert|frag files. And have this errors:

THREE.WebGLProgram: shader error:  0 gl.VALIDATE_STATUS false gl.getProgramInfoLog invalid shaders ERROR: 0:44: 'shader' : syntax error
 ERROR: 0:102: 'shader' : syntax error
THREE.WebGLShader: gl.getShaderInfoLog() vertex ERROR: 0:44: 'shader' : syntax error
 1: precision highp float;
2: precision highp int;
3: #define SHADER_NAME LuminosityMaterial
4: #define COLOR 1
5: #define VERTEX_TEXTURES
6: #define GAMMA_FACTOR 2
7: #define MAX_BONES 0
8: #define BONE_TEXTURE
9: #define NUM_CLIPPING_PLANES 0
10: uniform mat4 modelMatrix;
11: uniform mat4 modelViewMatrix;
12: uniform mat4 projectionMatrix;
13: uniform mat4 viewMatrix;
14: uniform mat3 normalMatrix;
15: uniform vec3 cameraPosition;
16: attribute vec3 position;
17: attribute vec3 normal;
18: attribute vec2 uv;
19: #ifdef USE_COLOR
20: 	attribute vec3 color;
21: #endif
22: #ifdef USE_MORPHTARGETS
23: 	attribute vec3 morphTarget0;
24: 	attribute vec3 morphTarget1;
25: 	attribute vec3 morphTarget2;
26: 	attribute vec3 morphTarget3;
27: 	#ifdef USE_MORPHNORMALS
28: 		attribute vec3 morphNormal0;
29: 		attribute vec3 morphNormal1;
30: 		attribute vec3 morphNormal2;
31: 		attribute vec3 morphNormal3;
32: 	#else
33: 		attribute vec3 morphTarget4;
34: 		attribute vec3 morphTarget5;
35: 		attribute vec3 morphTarget6;
36: 		attribute vec3 morphTarget7;
37: 	#endif
38: #endif
39: #ifdef USE_SKINNING
40: 	attribute vec4 skinIndex;
41: 	attribute vec4 skinWeight;
42: #endif
43: 
44: shader.vert

loader config

module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.(frag|vert)$/,
        loader: 'file-loader?name=[name].[ext]'
      }
    ]
  },

I'm new in THREE, I need your help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.