From 23573ad407013fda4561bbbf71e58700cb5421b2 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 18 Feb 2019 10:01:40 +0800 Subject: [PATCH 1/6] performance improves --- cocos/3d/framework/camera-component.ts | 2 +- cocos/assets/render-texture.ts | 61 ++---------- cocos/core/root.ts | 7 +- cocos/core/vmath/mat4.ts | 120 +++++++++++++----------- cocos/gfx/command-buffer.ts | 2 +- cocos/gfx/webgl/webgl-command-buffer.ts | 6 +- cocos/gfx/webgl/webgl-commands.ts | 10 +- cocos/gfx/webgl/webgl-device.ts | 15 +-- cocos/gfx/webgl2/webgl2-commands.ts | 10 +- cocos/pipeline/forward/forward-stage.ts | 11 ++- cocos/pipeline/render-pipeline.ts | 2 + cocos/renderer/core/effect.ts | 2 - playground/simple.html | 1 - rollup/config.js | 6 +- 14 files changed, 124 insertions(+), 131 deletions(-) diff --git a/cocos/3d/framework/camera-component.ts b/cocos/3d/framework/camera-component.ts index 7dcc8f2be1..5a2b486b9c 100644 --- a/cocos/3d/framework/camera-component.ts +++ b/cocos/3d/framework/camera-component.ts @@ -100,7 +100,7 @@ export class CameraComponent extends Component { @property protected _rect = new Rect(0, 0, 1, 1); @property - protected _targetDisplay = 0; + protected _targetDisplay = -1; protected _camera: Camera | null = null; diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts index d535942467..c5c15529ab 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/assets/render-texture.ts @@ -42,7 +42,7 @@ export class RenderTexture extends Texture2D { * @param [string] * @method initWithSize */ - public initWithSize (width?: number, height?: number, format?: DSFormat) { + public initWithSize (width: number, height: number, format: DSFormat = 'D24S8') { this.destroy(); const gfxDevice = this._getGlobalDevice(); @@ -50,29 +50,17 @@ export class RenderTexture extends Texture2D { return; } - const w = Math.floor(width || cc.visibleRect.width); - const h = Math.floor(height || cc.visibleRect.height); const image = new ImageAsset({ - width: w, - height: h, + width, + height, format: GFXFormat.RGBA8UI, - _data: new Uint8Array(w * h * 4), + _data: new Uint8Array(width * height * 4), _compressed: false, }); this.image = image; - if (!this._texture) { - return; - } - - const colorView = gfxDevice.createTextureView({ - texture: this._texture, - type: GFXTextureViewType.TV2D, - format: this._getGfxFormat(), - }); - - if (!colorView) { + if (!this._textureView) { return; } @@ -81,12 +69,9 @@ export class RenderTexture extends Texture2D { type: GFXTextureType.TEX2D, usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT, format: _formatMap[format], - width: w, - height: h, + width, + height, }); - if (!this._depthStencilTexture) { - return; - } this._depthStencilTextureView = gfxDevice.createTextureView({ texture: this._depthStencilTexture, type: GFXTextureViewType.TV2D, @@ -94,19 +79,14 @@ export class RenderTexture extends Texture2D { }); } - if (this._depthStencilTextureView === null) { - return; - } - this._framebuffer = gfxDevice.createFramebuffer({ renderPass: cc.director.root.pipeline.getRenderPass(RenderPassStage.DEFAULT), - colorViews: [ colorView ], - depthStencilView: this._depthStencilTextureView === null ? undefined : this._depthStencilTextureView, + colorViews: [ this._textureView ], + depthStencilView: this._depthStencilTextureView!, isOffscreen: true, }); this.loaded = true; - // @ts-ignore this.emit('load'); } @@ -138,31 +118,10 @@ export class RenderTexture extends Texture2D { // this._framebuffer._height = height; // } - /** - * !#en Draw a texture to the specified position - * !#zh 将指定的图片渲染到指定的位置上 - * @param texture - * @param x - * @param y - */ - public drawTextureAt (texture: Texture2D, x: number, y: number) { - if (!this._texture) { - return; - } - - const image = texture.image; - - if (!image) { - return; - } - - this._assignImage(image, 0); - } - /** * !#en * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array. - * It will return a new (width * height * 4) length Uint8Array by default。 + * It will return a new (width * height * 4) length Uint8Array by default. * You can specify a data to store the pixels to reuse the data, * you and can specify other params to specify the texture region to read. * !#zh diff --git a/cocos/core/root.ts b/cocos/core/root.ts index cfd9c400bf..85c0151065 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -10,9 +10,8 @@ import { UI } from '../renderer/ui/ui'; export let _createSceneFun; export let _createViewFun; -// tslint:disable-next-line:no-empty-interface -export interface IRootInfo { -} +// export interface IRootInfo { +// } export interface ISceneInfo { name: string; @@ -76,7 +75,7 @@ export class Root { RenderView.registerCreateFunc(this); } - public initialize (info: IRootInfo): boolean { + public initialize (/*info: IRootInfo*/): boolean { if (!this._device.mainWindow) { return false; diff --git a/cocos/core/vmath/mat4.ts b/cocos/core/vmath/mat4.ts index 3890527d26..b719e5b449 100644 --- a/cocos/core/vmath/mat4.ts +++ b/cocos/core/vmath/mat4.ts @@ -1,6 +1,8 @@ import { EPSILON } from './utils'; // tslint:disable: one-variable-per-declaration +// tslint:disable: max-line-length +// tslint:disable: class-name /** * Mathematical 4x4 matrix. @@ -29,6 +31,70 @@ import { EPSILON } from './utils'; * apparent lack of consistency between the memory layout and the documentation. */ class mat4 { + + /** + * Inverts a matrix. + * + * @param out - Matrix to store result. + * @param a - Matrix to invert. + * @return out. + */ + public static invert = (() => { + // cache temps due to the high frequency invocations of this function + let a00 = 1, a01 = 0, a02 = 0, a03 = 0; + let a10 = 0, a11 = 1, a12 = 0, a13 = 0; + let a20 = 0, a21 = 0, a22 = 1, a23 = 0; + let a30 = 0, a31 = 0, a32 = 0, a33 = 1; + let b00 = 1, b01 = 0, b02 = 0, b03 = 0; + let b04 = 0, b05 = 0, b06 = 0, b07 = 0; + let b08 = 0, b09 = 0, b10 = 0, b11 = 1; + let det = 1; + return (out, a) => { + a00 = a.m00; a01 = a.m01; a02 = a.m02; a03 = a.m03; + a10 = a.m04; a11 = a.m05; a12 = a.m06; a13 = a.m07; + a20 = a.m08; a21 = a.m09; a22 = a.m10; a23 = a.m11; + a30 = a.m12; a31 = a.m13; a32 = a.m14; a33 = a.m15; + + b00 = a00 * a11 - a01 * a10; + b01 = a00 * a12 - a02 * a10; + b02 = a00 * a13 - a03 * a10; + b03 = a01 * a12 - a02 * a11; + b04 = a01 * a13 - a03 * a11; + b05 = a02 * a13 - a03 * a12; + b06 = a20 * a31 - a21 * a30; + b07 = a20 * a32 - a22 * a30; + b08 = a20 * a33 - a23 * a30; + b09 = a21 * a32 - a22 * a31; + b10 = a21 * a33 - a23 * a31; + b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (det === 0) { return null; } + det = 1.0 / det; + + out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return out; + }; + })(); + /** * Creates a matrix, with elements specified separately. * @@ -221,60 +287,6 @@ class mat4 { return out; } - /** - * Inverts a matrix. - * - * @param out - Matrix to store result. - * @param a - Matrix to invert. - * @return out. - */ - public static invert (out, a) { - const a00 = a.m00, a01 = a.m01, a02 = a.m02, a03 = a.m03, - a10 = a.m04, a11 = a.m05, a12 = a.m06, a13 = a.m07, - a20 = a.m08, a21 = a.m09, a22 = a.m10, a23 = a.m11, - a30 = a.m12, a31 = a.m13, a32 = a.m14, a33 = a.m15; - - const b00 = a00 * a11 - a01 * a10; - const b01 = a00 * a12 - a02 * a10; - const b02 = a00 * a13 - a03 * a10; - const b03 = a01 * a12 - a02 * a11; - const b04 = a01 * a13 - a03 * a11; - const b05 = a02 * a13 - a03 * a12; - const b06 = a20 * a31 - a21 * a30; - const b07 = a20 * a32 - a22 * a30; - const b08 = a20 * a33 - a23 * a30; - const b09 = a21 * a32 - a22 * a31; - const b10 = a21 * a33 - a23 * a31; - const b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) { - return null; - } - det = 1.0 / det; - - out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; - - return out; - } - /** * Calculates the adjugate of a matrix. * diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index 8da0e7380b..9d11504b55 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -77,7 +77,7 @@ export abstract class GFXCommandBuffer extends GFXObject { public abstract setDepthBias (depthBiasConstantFacotr: number, depthBiasClamp: number, depthBiasSlopeFactor: number); public abstract setBlendConstants (blendConstants: number[]); public abstract setDepthBound (minDepthBounds: number, maxDepthBounds: number); - public abstract setStencilWirteMask (faceMask: GFXStencilFace, writeMask: number); + public abstract setStencilWriteMask (faceMask: GFXStencilFace, writeMask: number); public abstract setStencilCompareMask (face: GFXStencilFace, reference: number, compareMask: number); public abstract draw (inputAssembler: GFXInputAssembler); public abstract updateBuffer (buffer: GFXBuffer, data: ArrayBuffer, offset?: number); diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 440da5a98b..32e379926b 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -135,7 +135,9 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { const cmd = this._webGLAllocator!.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; cmd.renderArea = renderArea; - cmd.clearColors = clearColors.slice(); + for (let i = 0; i < clearColors.length; i++) { + cmd.clearColors[i] = clearColors[i]; + } cmd.clearDepth = clearDepth; cmd.clearStencil = clearStencil; this.cmdPackage.beginRenderPassCmds.push(cmd); @@ -287,7 +289,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public setStencilWirteMask (face: GFXStencilFace, writeMask: number) { + public setStencilWriteMask (face: GFXStencilFace, writeMask: number) { if (!this._curStencilWriteMask) { this._curStencilWriteMask = { face, diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 91560f4686..54ee945f48 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1226,10 +1226,14 @@ export function WebGLCmdFuncCreateInputAssember (device: WebGLGFXDevice, gpuInpu export function WebGLCmdFuncDestroyInputAssembler (device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { } +const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 +const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { const gl = device.gl; - const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 + for (let initID = 0; initID < cmdIds.length; initID++) { + cmdIds[initID] = 0; + } let gpuPipelineState: WebGLGPUPipelineState | null = null; let gpuShader: WebGLGPUShader | null = null; @@ -1281,7 +1285,9 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web const curGPURenderPass = cmd0.gpuFramebuffer.gpuRenderPass; - const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; + for (let initAtt = 0; initAtt < invalidateAttachments.length; initAtt++) { + invalidateAttachments[initAtt] = 0; + } let numInvalidAttach = 0; if (curGPURenderPass.colorAttachments.length > 0 && cmd0.clearColors.length) { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 23c8928954..5f7cff5931 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -469,12 +469,15 @@ export class WebGLGFXDevice extends GFXDevice { if (!context) { return; } const data: Uint8ClampedArray[] = []; - for (let i = 0; i < source.length; i++) { - const level = regions[i].texSubres.baseMipLevel; - this._canvas2D.width = texture.width >> level; - this._canvas2D.height = texture.height >> level; - context.drawImage(source[i], 0, 0); - data.push(context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height).data); + const faces = source.length / regions.length; + for (let j = 0; j < regions.length; j++) { + for (let i = 0; i < faces; i++) { + const level = regions[j].texSubres.baseMipLevel; + this._canvas2D.width = texture.width >> level; + this._canvas2D.height = texture.height >> level; + context.drawImage(source[j * faces + i], 0, 0); + data.push(context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height).data); + } } const buffer = new Uint8ClampedArray(data.reduce((acc, cur) => acc + cur.length, 0)); diff --git a/cocos/gfx/webgl2/webgl2-commands.ts b/cocos/gfx/webgl2/webgl2-commands.ts index 01ee9dd26d..6070fc208b 100644 --- a/cocos/gfx/webgl2/webgl2-commands.ts +++ b/cocos/gfx/webgl2/webgl2-commands.ts @@ -1345,10 +1345,14 @@ export function WebGL2CmdFuncCreateInputAssember (device: WebGL2GFXDevice, gpuIn export function WebGL2CmdFuncDestroyInputAssembler (device: WebGL2GFXDevice, gpuInputAssembler: WebGL2GPUInputAssembler) { } +const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 +const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: WebGL2CmdPackage) { const gl = device.gl; - const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 + for (let initID = 0; initID < cmdIds.length; initID++) { + cmdIds[initID] = 0; + } let gpuPipelineState: WebGL2GPUPipelineState | null = null; let gpuShader: WebGL2GPUShader | null = null; @@ -1400,7 +1404,9 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W const curGPURenderPass = cmd0.gpuFramebuffer.gpuRenderPass; - const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; + for (let initAtt = 0; initAtt < invalidateAttachments.length; initAtt++) { + invalidateAttachments[initAtt] = 0; + } let numInvalidAttach = 0; if (curGPURenderPass.colorAttachments.length > 0 && cmd0.clearColors.length) { diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 28d57a5681..1b09cd09a5 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -1,11 +1,14 @@ import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXCommandBufferType, IGFXColor } from '../../gfx/define'; import { GFXFramebuffer } from '../../gfx/framebuffer'; import { Camera } from '../../renderer/scene/camera'; import { RenderFlow } from '../render-flow'; import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; +const colors: IGFXColor[] = []; +const bufs: GFXCommandBuffer[] = []; + export class ForwardStage extends RenderStage { constructor (flow: RenderFlow) { @@ -51,16 +54,18 @@ export class ForwardStage extends RenderStage { this._renderArea.width = camera.width; this._renderArea.height = camera.height; + colors[0] = camera.clearColor; cmdBuff.begin(); cmdBuff.beginRenderPass(framebuffer, this._renderArea, - [camera.clearColor], camera.clearDepth, camera.clearStencil); + colors, camera.clearDepth, camera.clearStencil); cmdBuff.execute(queue.cmdBuffs.array, queue.cmdBuffCount); cmdBuff.endRenderPass(); cmdBuff.end(); - this._device.queue.submit([cmdBuff]); + bufs[0] = cmdBuff; + this._device.queue.submit(bufs); } } diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 369f8dad4a..707843d03a 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -14,6 +14,7 @@ import { IRenderFlowInfo, RenderFlow } from './render-flow'; import { RenderQueue } from './render-queue'; import { RenderView } from './render-view'; +// tslint:disable: max-line-length export class UBOGlobal { public static MAX_DIR_LIGHTS = 4; public static MAX_POINT_LIGHTS = 4; @@ -66,6 +67,7 @@ export class UBOGlobal { public view: Float32Array = new Float32Array(UBOGlobal.COUNT); } +// tslint:enable: max-line-length export class UBOLocal { public static MAT_WORLD_OFFSET: number = 0; diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 125ae93f1d..0e89ef1d03 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -42,5 +42,3 @@ export class Effect { return passes; } } - -cc.Effect = Effect; diff --git a/playground/simple.html b/playground/simple.html index 8e89448a42..796a55398d 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -121,7 +121,6 @@ .map((t) => [Math.random(), Math.random(), Math.random(), 0.8]) .reduce((c, a) => a.concat(c), []); modelCom.mesh = cc.utils.createMesh(shape); - modelNode.setPosition(0, 3, 100); } let buttonDown = false, pos = cc.v2(); diff --git a/rollup/config.js b/rollup/config.js index b907d75a2a..0aa5009faf 100644 --- a/rollup/config.js +++ b/rollup/config.js @@ -39,12 +39,14 @@ export default { extensions: ['.js', '.ts'], presets: [ - '@babel/preset-env', + [ + '@babel/preset-env', + // { targets: { "esmodules": true } } + ], '@babel/preset-typescript' ], plugins: [ - //'./rollup/babel-plugin-mix-ts-js', ['@babel/plugin-proposal-decorators', { legacy: true }], From e936d1a1117722d227b6b85186145e9ce7e73c61 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Mon, 18 Feb 2019 17:12:39 +0800 Subject: [PATCH 2/6] fix some particle error --- .../framework/particle/animator/gradient.ts | 25 ++++++++++++++----- .../renderer/particle-system-renderer.ts | 4 +-- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/cocos/3d/framework/particle/animator/gradient.ts b/cocos/3d/framework/particle/animator/gradient.ts index f38e34fdfd..fabca293f3 100644 --- a/cocos/3d/framework/particle/animator/gradient.ts +++ b/cocos/3d/framework/particle/animator/gradient.ts @@ -1,8 +1,10 @@ -import { repeat } from '../../../../core/vmath'; +import { repeat, lerp } from '../../../../core/vmath'; import { Enum, ValueType, Color } from '../../../../core/value-types'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +// tslint:disable: max-line-length + const Mode = Enum({ Blend: 0, Fixed: 1, @@ -77,7 +79,7 @@ export default class Gradient { const preTime = this.colorKeys[i - 1].time; const curTime = this.colorKeys[i].time; if (time >= preTime && time < curTime) { - if (this.mode === 'fixed') { + if (this.mode === Mode.Fixed) { return this.colorKeys[i].color; } const factor = (time - preTime) / (curTime - preTime); @@ -85,7 +87,13 @@ export default class Gradient { return this._color; } } - console.warn('something went wrong. can not get gradient color.'); + const lastIndex = this.colorKeys.length - 1; + if (time < this.colorKeys[0].time) { + Color.BLACK.lerp(this.colorKeys[0].color, time / this.colorKeys[0].time, this._color); + } else if (time > this.colorKeys[lastIndex].time) { + this.colorKeys[lastIndex].color.lerp(Color.BLACK, (time - this.colorKeys[lastIndex].time) / (1 - this.colorKeys[lastIndex].time), this._color); + } + // console.warn('something went wrong. can not get gradient color.'); } else if (this.colorKeys.length === 1) { this._color.set(this.colorKeys[0].color); return this._color; @@ -105,14 +113,19 @@ export default class Gradient { const preTime = this.alphaKeys[i - 1].time; const curTime = this.alphaKeys[i].time; if (time >= preTime && time < curTime) { - if (this.mode === 'fixed') { + if (this.mode === Mode.Fixed) { return this.alphaKeys[i].alpha; } const factor = (time - preTime) / (curTime - preTime); - return (this.alphaKeys[i - 1].alpha * (1 - factor) + this.alphaKeys[i].alpha * factor); + return lerp(this.alphaKeys[i - 1].alpha , this.alphaKeys[i].alpha , factor); } } - console.warn('something went wrong. can not get gradient alpha.'); + const lastIndex = this.alphaKeys.length - 1; + if (time < this.alphaKeys[0].time) { + return lerp(255, this.alphaKeys[0].alpha, time / this.alphaKeys[0].time); + } else if (time > this.alphaKeys[lastIndex].time) { + return lerp(this.alphaKeys[lastIndex].alpha, 255, (time - this.alphaKeys[lastIndex].time) / (1 - this.alphaKeys[lastIndex].time)); + } } else if (this.alphaKeys.length === 1) { return this.alphaKeys[0].alpha; } else { diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 0359bd1581..39afb9de2d 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -160,7 +160,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { } public _getFreeParticle (): Particle | null { - if (this._particles.length >= this.particleSystem._capacity) { + if (this._particles.length >= this.particleSystem.capacity) { return null; } return this._particles.add(); @@ -189,7 +189,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { continue; } - p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity. + p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed)! * 9.8 * dt; // apply gravity. if (this.particleSystem.sizeOvertimeModule.enable) { this.particleSystem.sizeOvertimeModule.animate(p); } From d3c7ca21dca0ee0177f14fefff55324b3956ebcd Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Mon, 18 Feb 2019 17:44:26 +0800 Subject: [PATCH 3/6] repair rendering unsynchronized bug --- cocos/3d/ui/components/label-component.ts | 10 +- cocos/3d/ui/components/sprite-component.ts | 205 +++++++++--------- cocos/3d/ui/components/ui-render-component.ts | 6 + 3 files changed, 116 insertions(+), 105 deletions(-) diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index a1106a59c4..9e99af1cd7 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -352,7 +352,7 @@ export class LabelComponent extends UIRenderComponent { this._renderData = null; } // this._fontAtlas = null; - this._updateAssembler(); + this._flushAssembler(); this._applyFontTexture(true); this.updateRenderData(); } @@ -386,7 +386,7 @@ export class LabelComponent extends UIRenderComponent { this._isSystemFontUsed = !!value; if (value) { this.font = null; - this._updateAssembler(); + this._flushAssembler(); this.updateRenderData(); this._checkStringEmpty(); } @@ -565,7 +565,7 @@ export class LabelComponent extends UIRenderComponent { } public updateAssembler(render: UI) { - if (!this._material) { + if (!this._material || this.string.length <= 0) { return; } super.updateAssembler(render); @@ -580,7 +580,7 @@ export class LabelComponent extends UIRenderComponent { } if (force) { - this._updateAssembler(); + this._flushAssembler(); this._applyFontTexture(force); } } @@ -603,7 +603,7 @@ export class LabelComponent extends UIRenderComponent { // this.markForRender(!!this.string); } - private _updateAssembler () { + private _flushAssembler () { const assembler = LabelComponent.Assembler!.getAssembler(this); if (this._assembler !== assembler) { diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 74536b7815..4c0f4b336d 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -32,6 +32,7 @@ import { Vec2 } from '../../../core/value-types'; import { ccenum } from '../../../core/value-types/enum'; import { UI } from '../../../renderer/ui/ui'; import { UIRenderComponent } from './ui-render-component'; +import { EventType } from '../../../scene-graph/node-event-enum'; /** * !#en Enum for sprite type. @@ -106,26 +107,28 @@ ccenum(FillType); * !#zh 精灵尺寸调整模式 * @enum Sprite.SizeMode */ -// var SizeMode = cc.Enum({ -// /** -// * !#en Use the customized node size. -// * !#zh 使用节点预设的尺寸 -// * @property {Number} CUSTOM -// */ -// CUSTOM: 0, -// /** -// * !#en Match the trimmed size of the sprite frame automatically. -// * !#zh 自动适配为精灵裁剪后的尺寸 -// * @property {Number} TRIMMED -// */ -// TRIMMED: 1, -// /** -// * !#en Match the raw size of the sprite frame automatically. -// * !#zh 自动适配为精灵原图尺寸 -// * @property {Number} RAW -// */ -// RAW: 2 -// }); +enum SizeMode { + /** + * !#en Use the customized node size. + * !#zh 使用节点预设的尺寸 + * @property {Number} CUSTOM + */ + CUSTOM = 0, + /** + * !#en Match the trimmed size of the sprite frame automatically. + * !#zh 自动适配为精灵裁剪后的尺寸 + * @property {Number} TRIMMED + */ + TRIMMED = 1, + /** + * !#en Match the raw size of the sprite frame automatically. + * !#zh 自动适配为精灵原图尺寸 + * @property {Number} RAW + */ + RAW = 2 +}; + +ccenum(SizeMode); // var State = cc.Enum({ // /** @@ -302,41 +305,45 @@ export class SpriteComponent extends UIRenderComponent { * @example * sprite.trim = true; */ + @property get trim () { - // return this._isTrimmedMode; + return this._isTrimmedMode; return false; } set trim (value: boolean) { - // if (this._isTrimmedMode !== value) { - // this._isTrimmedMode = value; - // if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) && - // this._renderData) { - // this.markForUpdateRenderData(true); - // } - // } + if (this._isTrimmedMode !== value) { + this._isTrimmedMode = value; + if ((this._type === SpriteType.SIMPLE /*|| this._type === SpriteType.MESH*/) && + this._renderData) { + this.markForUpdateRenderData(true); + } + } if (this._spriteFrame) { this.node.setContentSize(this._spriteFrame.getOriginalSize()); } } - // /** - // * !#en specify the size tracing mode. - // * !#zh 精灵尺寸调整模式 - // * @property sizeMode - // * @type {Sprite.SizeMode} - // * @example - // * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; - // */ - // get sizeMode() { - // return this._sizeMode; - // } - // set sizeMode(value) { - // // this._sizeMode = value; - // // if (value !== SizeMode.CUSTOM) { - // // this._applySpriteSize(); - // // } - // } + /** + * !#en specify the size tracing mode. + * !#zh 精灵尺寸调整模式 + * @property sizeMode + * @type {Sprite.SizeMode} + * @example + * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; + */ + @property({ + type: SizeMode + }) + get sizeMode() { + return this._sizeMode; + } + set sizeMode(value) { + this._sizeMode = value; + if (value !== SizeMode.CUSTOM) { + this._applySpriteSize(); + } + } public static FillType = FillType; public static Type = SpriteType; @@ -346,24 +353,34 @@ export class SpriteComponent extends UIRenderComponent { public _type: number = SpriteType.SIMPLE; @property public _fillType: number = FillType.HORIZONTAL; - // @property - // _sizeMode = SizeMode.TRIMMED; @property - public _fillCenter: Vec2 = cc.v2(0, 0); + public _sizeMode = SizeMode.TRIMMED; + @property + public _fillCenter: Vec2 = new Vec2(0, 0); @property public _fillStart: number = 0; @property public _fillRange: number = 0; - // @property - // _isTrimmedMode = true; + @property + _isTrimmedMode = true; // _state = 0; // TODO: @property public _atlas: atlas | null = null; public _spriteWidget = null; - // static SizeMode = SizeMode; + static SizeMode = SizeMode; // static State = State; + public __preload() { + if (super.__preload) { + super.__preload(); + } + + if (CC_EDITOR) { + this.node.on(EventType.SIZE_CHANGED, this._resized, this); + } + } + // /** // * Change the state of sprite. // * @method setState @@ -409,6 +426,9 @@ export class SpriteComponent extends UIRenderComponent { public onDestroy () { super.onDestroy(); this.destroyRenderData(); + if (CC_EDITOR) { + this.node.off(EventType.SIZE_CHANGED, this._resized, this); + } } // public onDisable () { @@ -518,19 +538,19 @@ export class SpriteComponent extends UIRenderComponent { // // } // } - // _applySpriteSize() { - // if (this._spriteFrame) { - // if (SizeMode.RAW === this._sizeMode) { - // var size = this._spriteFrame.getOriginalSize(); - // this.node.setContentSize(size); - // } else if (SizeMode.TRIMMED === this._sizeMode) { - // var rect = this._spriteFrame.getRect(); - // this.node.setContentSize(rect.width, rect.height); - // } + _applySpriteSize() { + if (this._spriteFrame) { + if (SizeMode.RAW === this._sizeMode) { + const size = this._spriteFrame.getOriginalSize(); + this.node.setContentSize(size); + } else if (SizeMode.TRIMMED === this._sizeMode) { + const rect = this._spriteFrame.getRect(); + this.node.setContentSize(rect.width, rect.height); + } - // this._activateMaterial(); - // } - // } + this._activateMaterial(); + } + } // _onTextureLoaded() { // if (!this.isValid) { @@ -573,46 +593,31 @@ export class SpriteComponent extends UIRenderComponent { } } - // _resized() { - // if (!CC_EDITOR) { - // return; - // } + _resized() { + if (!CC_EDITOR) { + return; + } - // if (this._spriteFrame) { - // var actualSize = this.node.getContentSize(); - // var expectedW = actualSize.width; - // var expectedH = actualSize.height; - // if (this._sizeMode === SizeMode.RAW) { - // var size = this._spriteFrame.getOriginalSize(); - // expectedW = size.width; - // expectedH = size.height; - // } else if (this._sizeMode === SizeMode.TRIMMED) { - // var rect = this._spriteFrame.getRect(); - // expectedW = rect.width; - // expectedH = rect.height; + if (this._spriteFrame) { + const actualSize = this.node.getContentSize(); + let expectedW = actualSize.width; + let expectedH = actualSize.height; + if (this._sizeMode === SizeMode.RAW) { + const size = this._spriteFrame.getOriginalSize(); + expectedW = size.width; + expectedH = size.height; + } else if (this._sizeMode === SizeMode.TRIMMED) { + const rect = this._spriteFrame.getRect(); + expectedW = rect.width; + expectedH = rect.height; - // } + } - // if (expectedW !== actualSize.width || expectedH !== actualSize.height) { - // this._sizeMode = SizeMode.CUSTOM; - // } - // } - // } + if (expectedW !== actualSize.width || expectedH !== actualSize.height) { + this._sizeMode = SizeMode.CUSTOM; + } + } + } } -// if (CC_EDITOR) { -// // override __preload -// Sprite.prototype.__superPreload = cc.Component.prototype.__preload; -// Sprite.prototype.__preload = function () { -// if (this.__superPreload) this.__superPreload(); -// this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); -// }; -// // override onDestroy -// Sprite.prototype.__superOnDestroy = cc.Component.prototype.onDestroy; -// Sprite.prototype.onDestroy = function () { -// if (this.__superOnDestroy) this.__superOnDestroy(); -// this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); -// }; -// } - cc.SpriteComponent = SpriteComponent; diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index 4c97c20f94..908a912b43 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -270,6 +270,12 @@ export class UIRenderComponent extends Component { if (renderData) { renderData.uvDirty = enable; renderData.vertDirty = enable; + for (const child of this.node.children) { + const renderComp = child.getComponent(UIRenderComponent); + if(renderComp){ + renderComp.markForUpdateRenderData(); + } + } } // } // else if (!enable) { From 16a74d471f1a80c81a50ee9a03b220b33cd0c812 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 18 Feb 2019 18:13:25 +0800 Subject: [PATCH 4/6] fix multi-vertex-buffers mesh bug; remove _cc, use cc.internal instead; fix wireframed() function; fix component's onDisable bug. --- cocos/3d/assets/mesh.ts | 10 ++++++---- cocos/3d/framework/animation-component.ts | 3 +++ cocos/3d/framework/physics/body.ts | 4 ++++ cocos/3d/primitive/index.ts | 2 +- cocos/3d/primitive/transform.ts | 7 +++++++ cocos/core/platform/event-manager/CCInputManager.ts | 2 +- cocos/renderer/models/skinning-model.ts | 2 +- cocos/scene-graph/component-scheduler.js | 4 +++- globals.d.ts | 2 -- predefine.js | 2 +- 10 files changed, 27 insertions(+), 11 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index a6135dc2d5..bd31231282 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -469,14 +469,19 @@ export class Mesh extends Asset { indexBuffer.update(ib); } + const vbReference = primitive.vertexBundelIndices.map( + (i) => vertexBuffers[i]); + const gfxAttributes: IGFXInputAttribute[] = []; primitive.vertexBundelIndices.forEach((iVertexBundle) => { + // const istream = iVertexBundle; + const istream = vbReference.indexOf(vertexBuffers[iVertexBundle]); const vertexBundle = this._struct.vertexBundles[iVertexBundle]; vertexBundle.attributes.forEach((attribute) => { const gfxAttribute: IGFXInputAttribute = { name: attribute.name, format: toGFXAttributeType(attribute), - stream: iVertexBundle, + stream: istream, }; if ('normalize' in attribute) { gfxAttribute.isNormalized = attribute.normalize; @@ -485,9 +490,6 @@ export class Mesh extends Asset { }); }); - const vbReference = primitive.vertexBundelIndices.map( - (i) => vertexBuffers[i]); - const geomInfo: any = primitive.geometricInfo; if (geomInfo) { geomInfo.indices = ib; diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts index 19b9578021..aa7f1dbc02 100644 --- a/cocos/3d/framework/animation-component.ts +++ b/cocos/3d/framework/animation-component.ts @@ -177,6 +177,9 @@ class AnimationCtrl { * @param duration */ public crossFade (to: AnimationState | null, duration: number) { + if (this._current === to) { + return; + } if (this._current && duration > 0.0) { this._next = to; this._blendTime = 0.0; diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts index 7b7ab856d5..6f59e46c6f 100644 --- a/cocos/3d/framework/physics/body.ts +++ b/cocos/3d/framework/physics/body.ts @@ -276,6 +276,10 @@ export class PhysicsBody { } private _onCollided (event: CANNON.ICollisionEvent) { + if (!this._node) { + return; + } + this._node.emit('collided', {}); // console.log(`Collided {${getWrap(event.body)._node.name}} and {${getWrap(event.target)._node.name}}.`); } diff --git a/cocos/3d/primitive/index.ts b/cocos/3d/primitive/index.ts index 9d77900f62..bc5c0afd03 100644 --- a/cocos/3d/primitive/index.ts +++ b/cocos/3d/primitive/index.ts @@ -8,4 +8,4 @@ export { default as sphere } from './sphere'; export { default as torus } from './torus'; export { default as capsule } from './capsule'; export { default as circle } from './circle'; -export { translate, scale } from './transform'; \ No newline at end of file +export { translate, scale, wireframed } from './transform'; diff --git a/cocos/3d/primitive/transform.ts b/cocos/3d/primitive/transform.ts index f5e536cafa..65785f28d4 100644 --- a/cocos/3d/primitive/transform.ts +++ b/cocos/3d/primitive/transform.ts @@ -1,4 +1,5 @@ import { IGeometry } from './define'; +import { GFXPrimitiveMode } from '../../gfx/define'; export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }) { const x = offset.x || 0; @@ -51,6 +52,11 @@ export function wireframed (geometry: IGeometry) { return geometry; } + // We only support triangles' wireframe. + if (geometry.primitiveMode && geometry.primitiveMode !== GFXPrimitiveMode.TRIANGLE_LIST) { + return geometry; + } + const offsets = [[0, 1], [1, 2], [2, 0]]; const lines: number[] = []; const lineIDs = {}; @@ -70,5 +76,6 @@ export function wireframed (geometry: IGeometry) { } geometry.indices = lines; + geometry.primitiveMode = GFXPrimitiveMode.LINE_LIST; return geometry; } diff --git a/cocos/core/platform/event-manager/CCInputManager.ts b/cocos/core/platform/event-manager/CCInputManager.ts index 570595c08e..ca14057bd3 100644 --- a/cocos/core/platform/event-manager/CCInputManager.ts +++ b/cocos/core/platform/event-manager/CCInputManager.ts @@ -782,4 +782,4 @@ const inputManager = new InputManager(); export default inputManager; -_cc.inputManager = inputManager; +cc.internal.inputManager = inputManager; diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index 14e7e0a9a7..17db3782cf 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -34,7 +34,7 @@ function isUniformStorage (storage: JointStorage): storage is IJointUniformsStor return !('texture' in storage); } -export const __FORCE_USE_UNIFORM_STORAGE__ = false; +export const __FORCE_USE_UNIFORM_STORAGE__ = true; export class SkinningModel extends Model { private _jointStorage: JointStorage | null = null; diff --git a/cocos/scene-graph/component-scheduler.js b/cocos/scene-graph/component-scheduler.js index 925649e49c..f218699655 100644 --- a/cocos/scene-graph/component-scheduler.js +++ b/cocos/scene-graph/component-scheduler.js @@ -27,6 +27,8 @@ import { CCObject } from '../core/data/object'; import { MutableForwardIterator } from '../core/utils/array'; import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; +import * as js from '../core/utils/js'; +const fastRemoveAt = js.array.fastRemoveAt; var IsStartCalled = CCObject.Flags.IsStartCalled; var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; @@ -333,7 +335,7 @@ class ComponentScheduler { // cancel schedule task var index = this.scheduleInNextFrame.indexOf(comp); if (index >= 0) { - array.fastRemoveAt(this.scheduleInNextFrame, index); + js.array.fastRemoveAt(this.scheduleInNextFrame, index); return; } diff --git a/globals.d.ts b/globals.d.ts index 8c476a4668..558d0b281c 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -39,8 +39,6 @@ declare const CC_SUPPORT_JIT: boolean; declare const cc: any; -declare const _cc: any; - type RecursivePartial = { [P in keyof T]?: T[P] extends Array ? Array> : diff --git a/predefine.js b/predefine.js index 3862294262..963c63ff30 100644 --- a/predefine.js +++ b/predefine.js @@ -131,7 +131,7 @@ var _global = typeof window === 'undefined' ? global : window; let cc = _global.cc = _global.cc || {}; // For internal usage -_global._cc = _global._cc || {}; +cc.internal = cc.internal || {}; function defineMacro (name, defaultValue) { From c099c576cb9c269405040fb69b3215f12491f390 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 18 Feb 2019 17:33:17 +0800 Subject: [PATCH 5/6] seperated light UBO --- cocos/3d/assets/effect-asset.ts | 4 +- cocos/3d/builtin/effects.js | 42 +++++-- cocos/pipeline/forward/forward-pipeline.ts | 126 +++++++++++++++++++-- cocos/pipeline/render-pipeline.ts | 64 +---------- cocos/renderer/core/effect.ts | 1 + cocos/renderer/core/pass.ts | 5 + cocos/renderer/core/program-lib.ts | 18 +-- cocos/renderer/models/model-uniforms.ts | 4 +- cocos/renderer/ui/ui.ts | 2 +- 9 files changed, 173 insertions(+), 93 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 3cb9b4e16d..e541198d77 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -59,8 +59,8 @@ export interface IDefineInfo { } export interface IShaderInfo { name: string; - vert: string; - frag: string; + glsl3: { vert: string, frag: string }; + glsl1: { vert: string, frag: string }; defines: IDefineInfo[]; blocks: IBlockInfo[]; samplers: ISamplerInfo[]; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 12932537a0..39718eafb6 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -6,8 +6,14 @@ export default [ "shaders": [ { "name": "builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", - "vert": "\n uniform vec2 frameTile;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n uniform float velocityScale;\n uniform float lengthScale;\n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , velocityScale\n , lengthScale\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile) * mainTiling + mainOffset;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n", - "frag": "\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n varying vec2 uv;\n varying vec4 color;\n void main () {\n \n gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n }\n", + "glsl3": { + "vert": "\nuniform Constants {\n vec2 frameTile;\n vec2 mainTiling;\n vec2 mainOffset;\n float velocityScale;\n float lengthScale;\n};\n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\nuniform CCGlobal {\n \n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n \n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos; \n \n vec4 cc_dirLightDirection[4]; \n vec4 cc_dirLightColor[4]; \n \n vec4 cc_pointLightPositionAndRange[4]; \n vec4 cc_pointLightColor[4]; \n \n vec4 cc_spotLightPositionAndRange[4]; \n vec4 cc_spotLightDirection[4]; \n vec4 cc_spotLightColor[4]; \n \n mat4 cc_matViewProjLight;\n vec4 cc_shadowParam1; \n vec4 cc_shadowParam2; \n};\nuniform CCLocal {\n mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , velocityScale\n , lengthScale\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile) * mainTiling + mainOffset;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n", + "frag": "\n uniform sampler2D mainTexture;\n uniform FragConstants {\n vec4 tintColor;\n };\n varying vec2 uv;\n varying vec4 color;\n void main () {\n \n gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n }\n" + }, + "glsl1": { + "vert": "\n uniform vec2 frameTile;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n uniform float velocityScale;\n uniform float lengthScale;\n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos.xyz\n , velocity\n , velocityScale\n , lengthScale\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile) * mainTiling + mainOffset;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n", + "frag": "\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n varying vec2 uv;\n varying vec4 color;\n void main () {\n \n gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n }\n" + }, "defines": [ {"name":"USE_BILLBOARD", "type":"boolean", "defines":[]}, {"name":"USE_STRETCHED_BILLBOARD", "type":"boolean", "defines":[]}, @@ -40,8 +46,14 @@ export default [ "shaders": [ { "name": "builtin-effect-skybox|sky-vs|sky-fs", - "vert": "\n attribute vec3 a_position;\n \n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n gl_Position = clipPos;\n gl_Position.z = clipPos.w * 0.99999;\n viewDir = a_position;\n }\n", - "frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n", + "glsl3": { + "vert": "\n attribute vec3 a_position;\n \n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\nuniform CCGlobal {\n \n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n \n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos; \n \n vec4 cc_dirLightDirection[4]; \n vec4 cc_dirLightColor[4]; \n \n vec4 cc_pointLightPositionAndRange[4]; \n vec4 cc_pointLightColor[4]; \n \n vec4 cc_spotLightPositionAndRange[4]; \n vec4 cc_spotLightDirection[4]; \n vec4 cc_spotLightColor[4]; \n \n mat4 cc_matViewProjLight;\n vec4 cc_shadowParam1; \n vec4 cc_shadowParam2; \n};\n varying vec3 viewDir;\n void main() {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n gl_Position = clipPos;\n gl_Position.z = clipPos.w * 0.99999;\n viewDir = a_position;\n }\n", + "frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n" + }, + "glsl1": { + "vert": "\n attribute vec3 a_position;\n \n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n gl_Position = clipPos;\n gl_Position.z = clipPos.w * 0.99999;\n viewDir = a_position;\n }\n", + "frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n" + }, "defines": [ {"name":"USE_RGBE_CUBEMAP", "type":"boolean", "defines":[]} ], @@ -55,12 +67,18 @@ export default [ }, { "name": "builtin-effect-sprite", - "techniques": [{"passes":[{"depthStencilState":{"depthTest":false, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendSrcAlpha":1, "blendDstAlpha":1}]}, "program":"builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", "properties":{"mainTexture":{"type":29, "value":"white"}}}]}], + "techniques": [{"passes":[{"depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", "properties":{"mainTexture":{"type":29, "value":"white"}}}]}], "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec2 uv0;\nvarying vec4 color;\n uniform mat4 cc_matViewProj;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\nuniform sampler2D mainTexture;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n", + "glsl3": { + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec2 uv0;\nvarying vec4 color;\nuniform ui {\n mat4 cc_matViewProj;\n};\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nuniform sampler2D mainTexture;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n" + }, + "glsl1": { + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec2 uv0;\nvarying vec4 color;\n uniform mat4 cc_matViewProj;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nuniform sampler2D mainTexture;\nvarying vec2 uv0;\nvarying vec4 color;\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n o *= texture2D(mainTexture, uv0);\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n" + }, "defines": [], "blocks": [ {"name": "ui", "size": 64, "defines": [], "binding": 0, "members": [ @@ -80,8 +98,14 @@ export default [ "shaders": [ { "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", - "vert": "\nattribute vec3 a_position;\n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n", + "glsl3": { + "vert": "\nattribute vec3 a_position;\n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\nuniform CCGlobal {\n \n vec4 cc_time; \n vec4 cc_screenSize; \n vec4 cc_screenScale; \n \n mat4 cc_matProj;\n mat4 cc_matProjInv;\n mat4 cc_matView;\n mat4 cc_matViewInv;\n mat4 cc_matViewProj;\n mat4 cc_matViewProjInv;\n vec4 cc_cameraPos; \n \n vec4 cc_dirLightDirection[4]; \n vec4 cc_dirLightColor[4]; \n \n vec4 cc_pointLightPositionAndRange[4]; \n vec4 cc_pointLightColor[4]; \n \n vec4 cc_spotLightPositionAndRange[4]; \n vec4 cc_spotLightDirection[4]; \n vec4 cc_spotLightColor[4]; \n \n mat4 cc_matViewProjLight;\n vec4 cc_shadowParam1; \n vec4 cc_shadowParam2; \n};\nuniform CCLocal {\n mat4 cc_matWorld;\n mat4 cc_matWorldIT;\n};\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n uniform TexCoords {\n vec2 mainTiling;\n vec2 mainOffset;\n };\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform CCSkinning {\n mat4 cc_matJoint[128];\n vec4 cc_jointsTextureSize;\n};\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform Constant {\n vec4 color;\n };\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n" + }, + "glsl1": { + "vert": "\nattribute vec3 a_position;\n#define MAX_DIR_LIGHTS 4\n#define MAX_POINT_LIGHTS 4\n#define MAX_SPOT_LIGHTS 4\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n" + }, "defines": [ {"name":"USE_TEXTURE", "type":"boolean", "defines":[]}, {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index af8351d9a4..9083eb7886 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -1,16 +1,60 @@ import { Root } from '../../core/root'; -import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXType } from '../../gfx/define'; import { GFXRenderPass } from '../../gfx/render-pass'; +import { GFXUniformBlock } from '../../gfx/shader'; import { RenderPassStage } from '../define'; -import { RenderPipeline, UBOGlobal } from '../render-pipeline'; +import { RenderPipeline } from '../render-pipeline'; +import { RenderView } from '../render-view'; import { ForwardFlow } from './forward-flow'; export enum ForwardFlowPriority { FORWARD = 0, } +// tslint:disable: max-line-length +export class UBOForwardLights { + public static MAX_DIR_LIGHTS = 4; + public static MAX_POINT_LIGHTS = 4; + public static MAX_SPOT_LIGHTS = 4; + + public static DIR_LIGHT_DIR_OFFSET: number = 0; + public static DIR_LIGHT_COLOR_OFFSET: number = UBOForwardLights.DIR_LIGHT_DIR_OFFSET + UBOForwardLights.MAX_DIR_LIGHTS * 4; + public static POINT_LIGHT_POS_RANGE_OFFSET: number = UBOForwardLights.DIR_LIGHT_COLOR_OFFSET + UBOForwardLights.MAX_DIR_LIGHTS * 4; + public static POINT_LIGHT_COLOR_OFFSET: number = UBOForwardLights.POINT_LIGHT_POS_RANGE_OFFSET + UBOForwardLights.MAX_POINT_LIGHTS * 4; + public static SPOT_LIGHT_POS_RANGE_OFFSET: number = UBOForwardLights.POINT_LIGHT_COLOR_OFFSET + UBOForwardLights.MAX_POINT_LIGHTS * 4; + public static SPOT_LIGHT_DIR_OFFSET: number = UBOForwardLights.SPOT_LIGHT_POS_RANGE_OFFSET + UBOForwardLights.MAX_SPOT_LIGHTS * 4; + public static SPOT_LIGHT_COLOR_OFFSET: number = UBOForwardLights.SPOT_LIGHT_DIR_OFFSET + UBOForwardLights.MAX_SPOT_LIGHTS * 4; + public static COUNT: number = UBOForwardLights.SPOT_LIGHT_COLOR_OFFSET + UBOForwardLights.MAX_SPOT_LIGHTS * 4; + public static SIZE: number = UBOForwardLights.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 29, name: 'CCForwardLights', members: [ + { name: 'cc_dirLightDirection', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_DIR_LIGHTS }, + { name: 'cc_dirLightColor', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_DIR_LIGHTS }, + { name: 'cc_pointLightPositionAndRange', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_POINT_LIGHTS }, + { name: 'cc_pointLightColor', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_POINT_LIGHTS }, + { name: 'cc_spotLightPositionAndRange', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLightDirection', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_SPOT_LIGHTS }, + { name: 'cc_spotLightColor', type: GFXType.FLOAT4, count: UBOForwardLights.MAX_SPOT_LIGHTS }, + ], + }; + + public view: Float32Array = new Float32Array(UBOForwardLights.COUNT); +} +// tslint:enable: max-line-length + +const _idVec4Array = Float32Array.from([0, 0, 0, 1]); + export class ForwardPipeline extends RenderPipeline { + protected _uboLights: UBOForwardLights = new UBOForwardLights(); + protected _lightsUBO: GFXBuffer | null = null; + + public get lightsUBO (): GFXBuffer { + return this._lightsUBO!; + } + constructor (root: Root) { super(root); } @@ -39,13 +83,6 @@ export class ForwardPipeline extends RenderPipeline { this.addRenderPass(RenderPassStage.DEFAULT, windowPass); - // create UBOs - this._globalUBO = this._root.device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST, - size: UBOGlobal.SIZE, - }); - // create flows this.createFlow(ForwardFlow, { name: 'ForwardFlow', @@ -62,4 +99,75 @@ export class ForwardPipeline extends RenderPipeline { this.destroyQuadInputAssembler(); } + protected createUBOs (): boolean { + super.createUBOs(); + + this._lightsUBO = this._root.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOForwardLights.SIZE, + }); + + if (!this._lightsUBO) { + return false; + } + + return true; + } + + protected destroyUBOs () { + super.destroyUBOs(); + + if (this._lightsUBO) { + this._lightsUBO.destroy(); + this._lightsUBO = null; + } + } + + protected updateUBOs (view: RenderView) { + super.updateUBOs(view); + + const scene = view.camera.scene; + const dLights = scene.directionalLights; + for (let i = 0; i < UBOForwardLights.MAX_DIR_LIGHTS; i++) { + const light = dLights[i]; + if (light && light.enabled) { + light.update(); + this._uboLights.view.set(light.directionArray, UBOForwardLights.DIR_LIGHT_DIR_OFFSET + i * 4); + this._uboLights.view.set(light.colorData, UBOForwardLights.DIR_LIGHT_COLOR_OFFSET + i * 4); + } else { + this._uboLights.view.set(_idVec4Array, UBOForwardLights.DIR_LIGHT_DIR_OFFSET + i * 4); + this._uboLights.view.set(_idVec4Array, UBOForwardLights.DIR_LIGHT_COLOR_OFFSET + i * 4); + } + } + const pLights = scene.pointLights; + for (let i = 0; i < UBOForwardLights.MAX_POINT_LIGHTS; i++) { + const light = pLights[i]; + if (light && light.enabled) { + light.update(); + this._uboLights.view.set(light.positionAndRange, UBOForwardLights.POINT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboLights.view.set(light.colorData, UBOForwardLights.POINT_LIGHT_COLOR_OFFSET + i * 4); + } else { + this._uboLights.view.set(_idVec4Array, UBOForwardLights.POINT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboLights.view.set(_idVec4Array, UBOForwardLights.POINT_LIGHT_COLOR_OFFSET + i * 4); + } + } + const sLights = scene.spotLights; + for (let i = 0; i < UBOForwardLights.MAX_SPOT_LIGHTS; i++) { + const light = sLights[i]; + if (light && light.enabled) { + light.update(); + this._uboLights.view.set(light.positionAndRange, UBOForwardLights.SPOT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboLights.view.set(light.directionArray, UBOForwardLights.SPOT_LIGHT_DIR_OFFSET + i * 4); + this._uboLights.view.set(light.colorData, UBOForwardLights.SPOT_LIGHT_COLOR_OFFSET + i * 4); + } else { + this._uboLights.view.set(_idVec4Array, UBOForwardLights.SPOT_LIGHT_POS_RANGE_OFFSET + i * 4); + this._uboLights.view.set(_idVec4Array, UBOForwardLights.SPOT_LIGHT_DIR_OFFSET + i * 4); + this._uboLights.view.set(_idVec4Array, UBOForwardLights.SPOT_LIGHT_COLOR_OFFSET + i * 4); + } + } + + // update ubos + this._lightsUBO!.update(this._uboLights.view); + } } diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 707843d03a..8da2d9849c 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -14,12 +14,7 @@ import { IRenderFlowInfo, RenderFlow } from './render-flow'; import { RenderQueue } from './render-queue'; import { RenderView } from './render-view'; -// tslint:disable: max-line-length export class UBOGlobal { - public static MAX_DIR_LIGHTS = 4; - public static MAX_POINT_LIGHTS = 4; - public static MAX_SPOT_LIGHTS = 4; - public static TIME_OFFSET: number = 0; public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; public static SCREEN_SCALE_OFFSET: number = UBOGlobal.SCREEN_SIZE_OFFSET + 4; @@ -30,14 +25,7 @@ export class UBOGlobal { public static MAT_VIEW_PROJ_OFFSET: number = UBOGlobal.MAT_PROJ_INV_OFFSET + 16; public static MAT_VIEW_PROJ_INV_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_OFFSET + 16; public static CAMERA_POS_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET + 16; - public static DIR_LIGHT_DIR_OFFSET: number = UBOGlobal.CAMERA_POS_OFFSET + 4; - public static DIR_LIGHT_COLOR_OFFSET: number = UBOGlobal.DIR_LIGHT_DIR_OFFSET + UBOGlobal.MAX_DIR_LIGHTS * 4; - public static POINT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.DIR_LIGHT_COLOR_OFFSET + UBOGlobal.MAX_DIR_LIGHTS * 4; - public static POINT_LIGHT_COLOR_OFFSET: number = UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + UBOGlobal.MAX_POINT_LIGHTS * 4; - public static SPOT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.POINT_LIGHT_COLOR_OFFSET + UBOGlobal.MAX_POINT_LIGHTS * 4; - public static SPOT_LIGHT_DIR_OFFSET: number = UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + UBOGlobal.MAX_SPOT_LIGHTS * 4; - public static SPOT_LIGHT_COLOR_OFFSET: number = UBOGlobal.SPOT_LIGHT_DIR_OFFSET + UBOGlobal.MAX_SPOT_LIGHTS * 4; - public static COUNT: number = UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + UBOGlobal.MAX_SPOT_LIGHTS * 4; + public static COUNT: number = UBOGlobal.CAMERA_POS_OFFSET + 4; public static SIZE: number = UBOGlobal.COUNT * 4; public static BLOCK: GFXUniformBlock = { @@ -54,20 +42,11 @@ export class UBOGlobal { { name: 'cc_matViewProj', type: GFXType.MAT4, count: 1 }, { name: 'cc_matViewProjInv', type: GFXType.MAT4, count: 1 }, { name: 'cc_cameraPos', type: GFXType.FLOAT4, count: 1 }, - // lights - { name: 'cc_dirLightDirection', type: GFXType.FLOAT4, count: UBOGlobal.MAX_DIR_LIGHTS }, - { name: 'cc_dirLightColor', type: GFXType.FLOAT4, count: UBOGlobal.MAX_DIR_LIGHTS }, - { name: 'cc_pointLightPositionAndRange', type: GFXType.FLOAT4, count: UBOGlobal.MAX_POINT_LIGHTS }, - { name: 'cc_pointLightColor', type: GFXType.FLOAT4, count: UBOGlobal.MAX_POINT_LIGHTS }, - { name: 'cc_spotLightPositionAndRange', type: GFXType.FLOAT4, count: UBOGlobal.MAX_SPOT_LIGHTS }, - { name: 'cc_spotLightDirection', type: GFXType.FLOAT4, count: UBOGlobal.MAX_SPOT_LIGHTS }, - { name: 'cc_spotLightColor', type: GFXType.FLOAT4, count: UBOGlobal.MAX_SPOT_LIGHTS }, ], }; public view: Float32Array = new Float32Array(UBOGlobal.COUNT); } -// tslint:enable: max-line-length export class UBOLocal { public static MAT_WORLD_OFFSET: number = 0; @@ -85,7 +64,6 @@ export class UBOLocal { public view: Float32Array = new Float32Array(UBOLocal.COUNT); } -const _idVec4Array = Float32Array.from([0, 0, 0, 1]); const _vec4Array = new Float32Array(4); const _mat4Array = new Float32Array(16); const _outMat = new Mat4(); @@ -359,46 +337,6 @@ export abstract class RenderPipeline { _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); - const scene = view.camera.scene; - const dLights = scene.directionalLights; - for (let i = 0; i < UBOGlobal.MAX_DIR_LIGHTS; i++) { - const light = dLights[i]; - if (light && light.enabled) { - light.update(); - this._uboGlobal.view.set(light.directionArray, UBOGlobal.DIR_LIGHT_DIR_OFFSET + i * 4); - this._uboGlobal.view.set(light.colorData, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + i * 4); - } else { - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_DIR_OFFSET + i * 4); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + i * 4); - } - } - const pLights = scene.pointLights; - for (let i = 0; i < UBOGlobal.MAX_POINT_LIGHTS; i++) { - const light = pLights[i]; - if (light && light.enabled) { - light.update(); - this._uboGlobal.view.set(light.positionAndRange, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + i * 4); - this._uboGlobal.view.set(light.colorData, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + i * 4); - } else { - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + i * 4); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + i * 4); - } - } - const sLights = scene.spotLights; - for (let i = 0; i < UBOGlobal.MAX_SPOT_LIGHTS; i++) { - const light = sLights[i]; - if (light && light.enabled) { - light.update(); - this._uboGlobal.view.set(light.positionAndRange, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + i * 4); - this._uboGlobal.view.set(light.directionArray, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + i * 4); - this._uboGlobal.view.set(light.colorData, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + i * 4); - } else { - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + i * 4); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + i * 4); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + i * 4); - } - } - // update ubos this._globalUBO!.update(this._uboGlobal.view); } diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 0e89ef1d03..b7092dd981 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -31,6 +31,7 @@ export class Effect { passInfo.blocks = prog.blocks; passInfo.samplers = prog.samplers; passInfo.globals = cc.director.root.pipeline.globalUBO; + passInfo.lights = cc.director.root.pipeline.lightsUBO; if (shader) { passInfo.shader = shader; } else { console.warn(`create shader ${passInfo.program} failed`); } if (renderPass) { passInfo.renderPass = renderPass; } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 24b89048de..747697cc3a 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -17,6 +17,7 @@ import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; import { RenderPassStage, RenderPriority } from '../../pipeline/define'; +import { UBOForwardLights } from '../../pipeline/forward/forward-pipeline'; import { UBOGlobal } from '../../pipeline/render-pipeline'; export interface IPassInfoFull extends IPassInfo { @@ -26,6 +27,7 @@ export interface IPassInfoFull extends IPassInfo { shader: GFXShader; renderPass: GFXRenderPass; globals: GFXBuffer; + lights: GFXBuffer; } export type PassOverrides = RecursivePartial; @@ -122,6 +124,7 @@ export class Pass { protected _shader: GFXShader | null = null; protected _renderPass: GFXRenderPass | null = null; protected _globalUBO: GFXBuffer | null = null; + protected _lightsUBO: GFXBuffer | null = null; public constructor (device: GFXDevice) { this._device = device; @@ -139,6 +142,7 @@ export class Pass { this._shader = info.shader; this._renderPass = info.renderPass; this._globalUBO = info.globals; + this._lightsUBO = info.lights; this._fillinPipelineInfo(info); for (const u of info.blocks) { @@ -292,6 +296,7 @@ export class Pass { bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]); } bindingLayout.bindBuffer(UBOGlobal.BLOCK.binding, this._globalUBO!); + bindingLayout.bindBuffer(UBOForwardLights.BLOCK.binding, this._lightsUBO!); const pipelineLayout = this._device.createPipelineLayout({ layouts: [bindingLayout] }); const pipelineState = this._device.createPipelineState({ bs: this._bs, diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 6bfa9afe00..53566f8272 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -2,11 +2,12 @@ import { IBlockInfo, IBlockMember, IDefineInfo, ISamplerInfo, IShaderInfo } from '../../3d/assets/effect-asset'; import { GFXGetTypeSize, GFXShaderType } from '../../gfx/define'; -import { GFXDevice } from '../../gfx/device'; +import { GFXAPI, GFXDevice } from '../../gfx/device'; import { GFXShader, GFXUniform, GFXUniformBlock, GFXUniformSampler } from '../../gfx/shader'; import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; import { SkinningUBO } from '../models/model-uniforms'; import { IDefineMap } from './effect'; +import { UBOForwardLights } from '../../pipeline/forward/forward-pipeline'; function _generateDefines ( device: GFXDevice, @@ -69,9 +70,7 @@ class ProgramLib { */ public define (prog: IShaderInfo) { const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; - tmpl.vert = this._precision + prog.vert; - tmpl.frag = this._precision + prog.frag; - tmpl.blocks = tmpl.blocks.concat(globals, locals); + tmpl.blocks = tmpl.blocks.concat(globals, locals, lights); // calculate option mask offset let offset = 0; @@ -130,8 +129,12 @@ class ProgramLib { // get template const tmpl = this._templates[name]; const customDef = _generateDefines(device, defines, tmpl.defines, tmpl.dependencies) + '\n'; - const vert = customDef + tmpl.vert; - const frag = customDef + tmpl.frag; + + const source = tmpl.glsl1; // temporary measure + // const source = (device.gfxAPI === GFXAPI.WEBGL2 ? tmpl.glsl3 : tmpl.glsl1); + + const vert = customDef + this._precision + source.vert; + const frag = customDef + this._precision + source.frag; const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name); program = device.createShader({ @@ -150,6 +153,7 @@ class ProgramLib { const globals = convertToBlockInfo(UBOGlobal.BLOCK); const locals = convertToBlockInfo(UBOLocal.BLOCK); +const lights = convertToBlockInfo(UBOForwardLights.BLOCK); const skinning = convertToBlockInfo(SkinningUBO.BLOCK); const jointsTexture = convertToSamplerInfo(SkinningUBO.JOINT_TEXTURE); @@ -184,7 +188,7 @@ function convertToSamplerInfo (sampler: GFXUniformSampler): ISamplerInfo { binding: sampler.binding, defines: [], type: sampler.type, - count: sampler.count + count: sampler.count, }; } diff --git a/cocos/renderer/models/model-uniforms.ts b/cocos/renderer/models/model-uniforms.ts index dc7fc83596..0c24d96ff1 100644 --- a/cocos/renderer/models/model-uniforms.ts +++ b/cocos/renderer/models/model-uniforms.ts @@ -8,13 +8,13 @@ export class SkinningUBO { public static SIZE: number = SkinningUBO.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 29, name: 'CCSkinning', members: [ + binding: 28, name: 'CCSkinning', members: [ { name: 'cc_matJoint', type: GFXType.MAT4, count: 128 }, { name: 'cc_jointsTextureSize', type: GFXType.FLOAT4, count: 1 }, ], }; public static JOINT_TEXTURE: GFXUniformSampler = { - binding: 28, name: 'cc_jointsTexture', type: GFXType.SAMPLER2D, count: 1, + binding: 27, name: 'cc_jointsTexture', type: GFXType.SAMPLER2D, count: 1, }; } diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 8e1e8e49e3..2e78a59801 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -39,7 +39,7 @@ export class UBOUI { public static SIZE: number = UBOUI.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 30, name: 'CCUI', members: [ + binding: 26, name: 'CCUI', members: [ { name: 'cc_matViewProj', type: GFXType.MAT4, count: 1 }, ], }; From ba491ae9d51fa871bf4c1fe7d71dc388bec5153d Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Mon, 18 Feb 2019 20:54:50 +0800 Subject: [PATCH 6/6] resolve UI material issue --- cocos/3d/memop/pool.js | 45 --------- cocos/3d/memop/pool.ts | 60 ++++++++++++ cocos/3d/memop/recycle-pool.ts | 12 --- cocos/3d/ui/assembler/sprite/simple.ts | 2 +- cocos/3d/ui/components/sprite-component.ts | 6 +- cocos/renderer/scene/model.ts | 10 +- cocos/renderer/ui/ui-material.ts | 18 ++++ cocos/renderer/ui/ui.ts | 105 +++++++++++---------- 8 files changed, 143 insertions(+), 115 deletions(-) delete mode 100644 cocos/3d/memop/pool.js create mode 100644 cocos/3d/memop/pool.ts diff --git a/cocos/3d/memop/pool.js b/cocos/3d/memop/pool.js deleted file mode 100644 index 4db7e02a64..0000000000 --- a/cocos/3d/memop/pool.js +++ /dev/null @@ -1,45 +0,0 @@ -export default class Pool { - constructor(fn, size) { - this._fn = fn; - this._idx = size - 1; - this._frees = new Array(size); - - for (let i = 0; i < size; ++i) { - this._frees[i] = fn(); - } - } - - _expand(size) { - let old = this._frees; - this._frees = new Array(size); - - let len = size - old.length; - for (let i = 0; i < len; ++i) { - this._frees[i] = this._fn(); - } - - for (let i = len, j = 0; i < size; ++i, ++j) { - this._frees[i] = old[j]; - } - - this._idx += len; - } - - alloc() { - // create some more space (expand by 20%, minimum 1) - if (this._idx < 0) { - this._expand(Math.round(this._frees.length * 1.2) + 1); - } - - let ret = this._frees[this._idx]; - this._frees[this._idx] = null; - --this._idx; - - return ret; - } - - free(obj) { - ++this._idx; - this._frees[this._idx] = obj; - } -} \ No newline at end of file diff --git a/cocos/3d/memop/pool.ts b/cocos/3d/memop/pool.ts new file mode 100644 index 0000000000..f3813bbfa6 --- /dev/null +++ b/cocos/3d/memop/pool.ts @@ -0,0 +1,60 @@ +export default class Pool { + + private _fn: () => T; + private _idx: number; + private _frees: T[]; + + constructor (fn: () => T, size: number) { + this._fn = fn; + this._idx = size - 1; + this._frees = new Array(size); + + for (let i = 0; i < size; ++i) { + this._frees[i] = fn(); + } + } + + private _expand (size: number) { + const old = this._frees; + this._frees = new Array(size); + + const len = size - old.length; + for (let i = 0; i < len; ++i) { + this._frees[i] = this._fn(); + } + + for (let i = len, j = 0; i < size; ++i, ++j) { + this._frees[i] = old[j]; + } + + this._idx += len; + } + + public alloc (): T { + // create some more space (expand by 20%, minimum 1) + if (this._idx < 0) { + this._expand(Math.round(this._frees.length * 1.2) + 1); + } + + const ret = this._frees[this._idx]; + this._frees[this._idx] = null; + --this._idx; + + return ret; + } + + public free (obj: T) { + ++this._idx; + this._frees[this._idx] = obj; + } + + public clear (fn: (obj: T) => void) { + for (let i = 0; i <= this._idx; i++) { + if (fn) { + fn(this._frees[i]); + } + } + this._frees.splice(0); + this._idx = -1; + } +} diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/3d/memop/recycle-pool.ts index 67f8b5a89f..c74a3d3970 100644 --- a/cocos/3d/memop/recycle-pool.ts +++ b/cocos/3d/memop/recycle-pool.ts @@ -4,16 +4,13 @@ export default class RecyclePool { private _fn: () => T; private _count = 0; private _data: T[]; - private _objIdx: Map; constructor (fn: () => T, size: number) { this._fn = fn; this._data = new Array(size); - this._objIdx = new Map(); for (let i = 0; i < size; ++i) { this._data[i] = fn(); - this._objIdx.set(this._data[i], i); } } @@ -33,7 +30,6 @@ export default class RecyclePool { if (size > this._data.length) { for (let i = this._data.length; i < size; ++i) { this._data[i] = this._fn(); - this._objIdx.set(this._data[i], i); } } } @@ -55,17 +51,9 @@ export default class RecyclePool { const tmp = this._data[idx]; this._data[idx] = this._data[last]; this._data[last] = tmp; - this._objIdx.set(this._data[idx], idx); - this._objIdx.set(this._data[last], last); this._count -= 1; } - public remove (obj: T) { - if (this._objIdx.has(obj)) { - this.removeAt(this._objIdx.get(obj)!); - } - } - public sort (compare: (a: T, b: T) => number) { return sort(this._data, 0, this._count, compare); } diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts index 283db1754c..3fc4d4f507 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -142,7 +142,7 @@ export const simple: IAssembler = { ibuf![indiceOffset++] = vertexId + 2; commitBuffer.meshBuffer = buffer; - commitBuffer.material = sprite.material!; + commitBuffer.material = sprite.sharedMaterial!; commitBuffer.texture = sprite.spriteFrame!; commitBuffer.priority = sprite.priority; renderer.addToQueue(commitBuffer); diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 74536b7815..1ef6bf703d 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -400,7 +400,7 @@ export class SpriteComponent extends UIRenderComponent { } public updateAssembler (render: UI) { - if (!this._spriteFrame || !this._material) { + if (!this._spriteFrame || !this.sharedMaterial) { return; } super.updateAssembler(render); @@ -432,7 +432,7 @@ export class SpriteComponent extends UIRenderComponent { if (!this._renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); - this._renderData.material = this._material; + this._renderData.material = this.sharedMaterial; this.markForUpdateRenderData(); } } @@ -440,7 +440,7 @@ export class SpriteComponent extends UIRenderComponent { private _activateMaterial () { const spriteFrame = this._spriteFrame; - const material = this._material; + const material = this.sharedMaterial; // WebGL if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { // if (!material) { diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 481def9e1c..96ea742157 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -2,7 +2,7 @@ import { Material } from '../../3d/assets/material'; import { IRenderingSubmesh } from '../../3d/assets/mesh'; import { aabb } from '../../3d/geom-utils'; -import { RecyclePool } from '../../3d/memop'; +import Pool from '../../3d/memop/pool'; import { Vec3 } from '../../core/value-types'; import { mat4 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; @@ -17,7 +17,7 @@ import { SubModel } from './submodel'; const _temp_floatx16 = new Float32Array(16); const _temp_mat4 = mat4.create(); -const _subMeshPool = new RecyclePool(() => { +const _subMeshPool = new Pool(() => { return new SubModel(); }, 32); @@ -61,7 +61,7 @@ export class Model { public destroy () { for (const subModel of this._subModels) { subModel.destroy(); - _subMeshPool.remove(subModel); + _subMeshPool.free(subModel); } if (this._localUBO) { this._localUBO.destroy(); @@ -178,7 +178,7 @@ export class Model { public initSubModel (idx: number, subMeshData: IRenderingSubmesh, mat: Material) { if (this._subModels[idx] == null) { - this._subModels[idx] = _subMeshPool.add(); + this._subModels[idx] = _subMeshPool.alloc(); } else { const oldMat = this._subModels[idx].material; this._subModels[idx].destroy(); @@ -190,7 +190,7 @@ export class Model { public setSubModelMesh (idx: number, subMeshData: IRenderingSubmesh) { if (this._subModels[idx] == null) { - this._subModels[idx] = _subMeshPool.add(); + this._subModels[idx] = _subMeshPool.alloc(); } this._subModels[idx].subMeshData = subMeshData; } diff --git a/cocos/renderer/ui/ui-material.ts b/cocos/renderer/ui/ui-material.ts index 60cfbd776e..50ad083f9c 100644 --- a/cocos/renderer/ui/ui-material.ts +++ b/cocos/renderer/ui/ui-material.ts @@ -2,6 +2,7 @@ import { Material } from '../../3d/assets/material'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Pass } from '../core/pass'; +import Pool from '../../3d/memop/pool'; export interface IUIMaterialInfo { material: Material; @@ -19,8 +20,10 @@ export class UIMaterial { protected _material: Material | null = null; protected _pass: Pass | null = null; + private _psos: Pool | null; constructor () { + this._psos = null; } public initialize (info: IUIMaterialInfo): boolean { @@ -33,10 +36,25 @@ export class UIMaterial { this._pass = this._material.passes[0]; + this._psos = new Pool(() => this._pass!.createPipelineState()!, 1); + return true; } + public getPipelineState (): GFXPipelineState { + return this._psos!.alloc(); + } + + public revertPipelineState (pso: GFXPipelineState) { + this._psos!.free(pso); + } + public destroy () { this._material = null; + if (this._psos) { + this._psos.clear((obj: GFXPipelineState) => { + this._pass!.destroyPipelineState(obj); + }); + } } } diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 8e1e8e49e3..bc0046079e 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -32,6 +32,7 @@ import { Node } from '../../scene-graph/node'; import { Camera, CameraProjection } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; import { IUIMaterialInfo, UIMaterial } from './ui-material'; +import Pool from '../../3d/memop/pool'; export class UBOUI { public static MAT_VIEW_PROJ_OFFSET: number = 0; @@ -71,19 +72,22 @@ export class UIDrawBatch { public pipelineState: GFXPipelineState | null = null; public bindingLayout: GFXBindingLayout | null = null; - public destroy () { + public destroy (ui: UI) { if (this.pipelineState) { - this.pipelineState.destroy(); + ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState); this.pipelineState = null; } if (this.bindingLayout) { - this.bindingLayout.destroy(); this.bindingLayout = null; } } - public clear () { + public clear (ui: UI) { + if (this.pipelineState) { + ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState); + this.pipelineState = null; + } this.camera = null; this.bufferBatch = null; this.material = null; @@ -116,7 +120,7 @@ export class UI { private _bufferBatchPool: RecyclePool = new RecyclePool(() => { return new UIBufferBatch(); }, 128); - private _drawBatchPool: RecyclePool = new RecyclePool(() => { + private _drawBatchPool: Pool = new Pool(() => { return new UIDrawBatch(); }, 128); private _device: GFXDevice; @@ -130,14 +134,14 @@ export class UI { private _vertF32Count = 0; private _bufferBatches: UIBufferBatch[] = []; private _uiMaterial: UIMaterial | null = null; - private _uiMaterials: UIMaterial[] = []; + private _uiMaterials: Map = new Map(); private _uboUI: UBOUI = new UBOUI(); private _uiUBO: GFXBuffer | null = null; private _batches: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; private _commitUICanvas: IUICanvas[] = []; - private _sortChildList: RecyclePool = new RecyclePool(() => { + private _sortChildList: Pool = new Pool(() => { return []; }, 128); @@ -194,7 +198,7 @@ export class UI { type: GFXCommandBufferType.PRIMARY, }); - this._uiMaterial = this.createUIMaterial({ material: builtinResMgr.get('sprite-material')}); + // this._uiMaterial = this.createUIMaterial({ material: builtinResMgr.get('sprite-material') }); this._uiUBO = this._device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, @@ -206,7 +210,7 @@ export class UI { } public destroy () { - this.destroyUIMaterials(); + this._destroyUIMaterials(); if (this._uiUBO) { this._uiUBO.destroy(); @@ -214,7 +218,7 @@ export class UI { } for (const batch of this._batches.array) { - batch.destroy(); + batch.destroy(this); } for (const buffBatch of this._bufferBatches) { @@ -224,6 +228,10 @@ export class UI { } this._bufferBatches.splice(0); + for (const uiMat of this._uiMaterials.values()) { + uiMat.destroy(); + } + if (this._cmdBuff) { this._cmdBuff.destroy(); this._cmdBuff = null; @@ -241,31 +249,29 @@ export class UI { // this._camera.update(); // } - public createUIMaterial (info: IUIMaterialInfo): UIMaterial | null { - const uiMtrl = new UIMaterial(); - if (uiMtrl.initialize(info)) { - this._uiMaterials.push(uiMtrl); - return uiMtrl; + public _getUIMaterial (mat: Material): UIMaterial { + if (this._uiMaterials.has(mat.hash)) { + return this._uiMaterials.get(mat.hash)!; } else { - return null; + const uiMat = new UIMaterial(); + uiMat.initialize({ material: mat }); + this._uiMaterials.set(mat.hash, uiMat); + return uiMat; } } - public destroyUIMaterial (uiMaterial: UIMaterial) { - for (let i = 0; i < this._uiMaterials.length; ++i) { - if (this._uiMaterials[i] === uiMaterial) { - uiMaterial.destroy(); - this._uiMaterials.splice(i); - return; - } + private _deleteUIMaterial (mat: Material) { + if (this._uiMaterials.has(mat.hash)) { + this._uiMaterials.get(mat.hash)!.destroy(); + this._uiMaterials.delete(mat.hash); } } - public destroyUIMaterials () { - for (const uiMaterial of this._uiMaterials) { - uiMaterial.destroy(); + private _destroyUIMaterials () { + for (const uiMat of this._uiMaterials.values()) { + uiMat.destroy(); } - this._uiMaterials = []; + this._uiMaterials.clear(); } public addScreen (comp) { @@ -311,8 +317,8 @@ export class UI { for (let i = 0; i < this._batches.length; ++i) { const batch = this._batches.array[i]; - batch.clear(); - this._drawBatchPool.remove(batch); + batch.clear(this); + this._drawBatchPool.free(batch); } this._batches.clear(); this._commitUICanvas = []; @@ -340,7 +346,6 @@ export class UI { public render () { - const material = this._uiMaterial!; if (this._batches.length) { const framebuffer = this._root.curWindow!.framebuffer; @@ -366,6 +371,7 @@ export class UI { // TODO: add screen adapter // update ubo + camera.matViewProj.m14 /= 1000; // hack:to be resolved later mat4.array(_mat4Array, camera.matViewProj); this._uboUI.view.set(_mat4Array, UBOUI.MAT_VIEW_PROJ_OFFSET); @@ -398,13 +404,13 @@ export class UI { } } - private _walk (node: Node, fn1, fn2, level = 0, isRenderComp = false) { + private _walk (node: Node, fn1, fn2, level = 0, isRenderComp = false) { let resortNodeList; const len = node.childrenCount; fn1(node); - if (len > 0){ + if (len > 0) { resortNodeList = this._defineNodeOrder(node); for (const comp of resortNodeList) { this._walk(comp, fn1, fn2, level); @@ -414,7 +420,7 @@ export class UI { // this._walk(child, fn1, fn2, level); // } - this._sortChildList.remove(resortNodeList); + this._sortChildList.free(resortNodeList); } fn2(node); @@ -422,13 +428,15 @@ export class UI { } private _defineNodeOrder (node: Node) { - let sortList: any[] = this._sortChildList.add(); + let sortList: any[] = this._sortChildList.alloc(); sortList = node.children.slice(); sortList.sort((a, b) => { const ca = a.getComponent(UIRenderComponent); const cb = b.getComponent(UIRenderComponent); - if (ca && cb) { return ca.priority - cb.priority; } + if (ca && cb) { + return ca.priority - cb.priority; + } else if (!ca) { return -Number.MAX_SAFE_INTEGER; } else { @@ -489,6 +497,7 @@ export class UI { private mergeBatches () { let curTexView: GFXTextureView | null = null; + let curMaterialHash: number = 0; let bufferBatchIdx = 0; let curBufferBatch: UIBufferBatch = this._bufferBatches[bufferBatchIdx++]; let firstIdx = 0; @@ -561,9 +570,10 @@ export class UI { curBufferBatch.vui16![idxCount + n] = vui16[n] + vertCount; } - if (curTexView !== uiRenderData.texture.getGFXTextureView()) { - if (curTexView){ - curDrawBatch = this._drawBatchPool.add(); + if (curMaterialHash !== uiRenderData.material.hash || + curTexView !== uiRenderData.texture.getGFXTextureView()) { + if (curTexView) { + curDrawBatch = this._drawBatchPool.alloc(); curDrawBatch.camera = uiCanvas.camera; curDrawBatch.bufferBatch = curBufferBatch; curDrawBatch.material = uiRenderData.material; @@ -572,15 +582,14 @@ export class UI { curDrawBatch.idxCount = idxCount - firstIdx; firstIdx = idxCount; - if (!curDrawBatch.pipelineState) { - curDrawBatch.pipelineState = this._uiMaterial!.pass.createPipelineState(); - curDrawBatch.bindingLayout = curDrawBatch.pipelineState!.pipelineLayout.layouts[0]; - } + curDrawBatch.pipelineState = this._getUIMaterial(uiRenderData.material).getPipelineState(); + curDrawBatch.bindingLayout = curDrawBatch.pipelineState!.pipelineLayout.layouts[0]; this._batches.push(curDrawBatch); } curTexView = uiRenderData.texture.getGFXTextureView(); + curMaterialHash = uiRenderData.material.hash; // firstIdx = idxCount; // idxCount = 0; @@ -589,10 +598,10 @@ export class UI { idxCount += vui16.length; vertCount += vCount; - isEnding = index === len; + isEnding = index === len; // get the last data - if (isEnding){ - curDrawBatch = this._drawBatchPool.add(); + if (isEnding) { + curDrawBatch = this._drawBatchPool.alloc(); curDrawBatch.camera = uiCanvas.camera; curDrawBatch.bufferBatch = curBufferBatch; curDrawBatch.material = uiRenderData.material; @@ -601,10 +610,8 @@ export class UI { curDrawBatch.idxCount = idxCount - firstIdx; firstIdx = idxCount; - if (!curDrawBatch.pipelineState) { - curDrawBatch.pipelineState = this._uiMaterial!.pass.createPipelineState(); - curDrawBatch.bindingLayout = curDrawBatch.pipelineState!.pipelineLayout.layouts[0]; - } + curDrawBatch.pipelineState = this._getUIMaterial(uiRenderData.material).getPipelineState(); + curDrawBatch.bindingLayout = curDrawBatch.pipelineState!.pipelineLayout.layouts[0]; this._batches.push(curDrawBatch); }