ThreeJS源码学习2WebGLRenderTarget

这篇博客介绍了three.js中的WebGLRenderTarget类,它用于离屏渲染,是获取深度图和实现后处理的核心。WebGLRenderTarget通过Object.assign实现继承,扩展了EventDispatcher基类,提供了setSize、clone、copy和dispose等方法,用于管理和操作渲染目标的属性。EventDispatcher负责监听和调度事件,确保了对象的正确交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承方法

threejs中通过 Object.assign方法向对象添加属性和方法等以实现继承。

WebGLRenderTarget

离屏渲染,是获取深度图,构建主渲染的必要方法。
也是实现后处理过程的核心方法。

function WebGLRenderTarget(width, height, options) {
		this.width = width;
		this.height = height;
		this.scissor = new Vector4(0, 0, width, height);
		this.scissorTest = false;
		this.viewport = new Vector4(0, 0, width, height);
		options = options || {};
		this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
		this.texture.image = {};
		this.texture.image.width = width;
		this.texture.image.height = height;
		this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
		this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
		this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
		this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
		this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
	}

这是方法本身,给WebGLRenderTarget添加属性,相当于一个控制器。
接下来是添加内置方法

WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
		constructor: WebGLRenderTarget,
		isWebGLRenderTarget: true,
		setSize: function setSize(width, height) {
			if (this.width !== width || this.height !== height) {
				this.width = width;
				this.height = height;
				this.texture.image.width = width;
				this.texture.image.height = height;
				this.dispose();
			}

			this.viewport.set(0, 0, width, height);
			this.scissor.set(0, 0, width, height);
		},
		clone: function clone() {
			return new this.constructor().copy(this);
		},
		copy: function copy(source) {
			this.width = source.width;
			this.height = source.height;
			this.viewport.copy(source.viewport);
			this.texture = source.texture.clone();
			this.depthBuffer = source.depthBuffer;
			this.stencilBuffer = source.stencilBuffer;
			this.depthTexture = source.depthTexture;
			return this;
		},
		dispose: function dispose() {
			this.dispatchEvent({
				type: 'dispose'
			});
		}
	});

可以看到,方法通过改变prototype的默认指向实现目的,同时第一行重新设置了constructor,因为在改变prototype指向的时候,constructor会发生一些奇怪的改变,具体可参考

EventDispatcher

着重解析一下其中的EventDispatcher。这是实现的一个类,是three.js的实体基类,主要负责监听和调度事件,具体注释可参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值