diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index a6f2d9797c..b015831c8f 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -27,15 +27,10 @@ import { ccclass, property } from '../../core/data/class-decorator'; import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; import { GFXBindingType } from '../../gfx/define'; import { Effect } from '../../renderer/core/effect'; -import { IPassOverrides, Pass } from '../../renderer/core/pass'; +import { Pass, PassOverrides } from '../../renderer/core/pass'; +import { RenderableComponent } from '../framework/renderable-component'; import { EffectAsset } from './effect-asset'; -export interface IMaterialInfo { - technique?: number; - effectName?: string; - defines?: Record; -} - @ccclass('cc.Material') export class Material extends Asset { public static getInstantiatedMaterial (mat: Material, rndCom: any) { @@ -60,18 +55,9 @@ export class Material extends Asset { protected _props: Array> = []; protected _passes: Pass[] = []; - protected _owner: any = null; + protected _owner: RenderableComponent | null = null; protected _hash = 0; - constructor (opts?: IMaterialInfo) { - super(); - if (opts) { - if (opts.technique) { this._techIdx = opts.technique; } - if (opts.defines) { this._defines = opts.defines; } - if (opts.effectName) { this.effectName = opts.effectName; } - } - } - @property set effectAsset (val: EffectAsset | null) { if (!val || this.effectName !== val.name) { this.update(val, false); } @@ -157,17 +143,11 @@ export class Material extends Asset { this.update(); } - public rebuildWithOverrides (overrides: IPassOverrides, idx?: number) { + public overridePipelineStates (overrides: PassOverrides, passIdx: number = 0) { if (!this._passes || !this._effectAsset) { return; } const passInfos = Effect.getPassInfos(this._effectAsset, this._techIdx); - if (idx === undefined) { - for (let i = 0; i < this._passes.length; i++) { - this._passes[i].rebuildWithOverrides(passInfos[i], overrides); - } - } else { - this._passes[idx].rebuildWithOverrides(passInfos[idx], overrides); - } - this.prepareHash(); + this._passes[passIdx].overridePipelineStates(passInfos[passIdx], overrides); + this.onPassChange(); } public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { @@ -202,7 +182,7 @@ export class Material extends Asset { } else { this._props.fill({}); } - this.prepareHash(); + this.onPassChange(); } protected _uploadProperty (pass: Pass, name: string, val: any) { @@ -219,12 +199,17 @@ export class Material extends Asset { return true; } - protected prepareHash () { + protected onPassChange () { let str = ''; for (const pass of this._passes) { str += pass.serializePipelineStates(); } this._hash = murmurhash2_32_gc(str, 666); + if (this._owner) { + const comp = this._owner; + const index = comp.sharedMaterials.findIndex((m) => m === this); + if (index >= 0) { comp._onMaterialModified(index, this); } + } } } diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index fd14d277d9..717941c52f 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -6,9 +6,11 @@ import { GFXCommandBufferType, GFXObject, GFXObjectType, + GFXStencilFace, GFXTextureLayout, IGFXColor, IGFXRect, + IGFXViewport, } from './define'; import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; @@ -47,6 +49,14 @@ export abstract class GFXCommandBuffer extends GFXObject { public abstract bindPipelineState (pipelineState: GFXPipelineState); public abstract bindBindingLayout (bindingLayout: GFXBindingLayout); public abstract bindInputAssembler (inputAssembler: GFXInputAssembler); + public abstract setViewport (viewport: IGFXViewport); + public abstract setScissor (scissor: IGFXRect); + public abstract setLineWidth (lineWidth: number); + 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 setStencilCompareMask (face: GFXStencilFace, reference: number, compareMask: number); public abstract draw (inputAssembler: GFXInputAssembler); public abstract updateBuffer (buffer: GFXBuffer, data: ArrayBuffer, offset?: number); public abstract copyBufferToTexture (srcBuff: GFXBuffer, dstTex: GFXTexture, dstLayout: GFXTextureLayout, regions: GFXBufferTextureCopy[]); diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 3b3c54671f..03a8dd02d0 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -472,6 +472,23 @@ export enum GFXPipelineBindPoint { RAY_TRACING, } +export enum GFXDynamicState { + VIEWPORT, + SCISSOR, + LINE_WIDTH, + DEPTH_BIAS, + BLEND_CONSTANTS, + DEPTH_BOUNDS, + STENCIL_WRITE_MASK, + STENCIL_COMPARE_MASK, +} + +export enum GFXStencilFace { + FRONT, + BACK, + ALL, +} + export enum GFXQueueType { GRAPHICS, COMPUTE, diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index 524524cbbe..9fb9e94c66 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -4,6 +4,7 @@ import { GFXColorMask, GFXComparisonFunc, GFXCullMode, + GFXDynamicState, GFXObject, GFXObjectType, GFXPolygonMode, @@ -23,11 +24,12 @@ export class GFXRasterizerState { public shadeModel: GFXShadeModel = GFXShadeModel.GOURAND; public cullMode: GFXCullMode = GFXCullMode.BACK; public isFrontFaceCCW: boolean = true; - public depthBias: number = 0.0; - public depthBiasFactor: number = 0.0; + public depthBias: number = 0; + public depthBiasClamp: number = 0.0; + public depthBiasSlop: number = 0.0; public isDepthClip: boolean = true; public isMultisample: boolean = false; - // lineWidth: number = 1.0; + public lineWidth: number = 1.0; public compare (state: GFXRasterizerState): boolean { return (this.isDiscard === state.isDiscard) && @@ -36,9 +38,10 @@ export class GFXRasterizerState { (this.cullMode === state.cullMode) && (this.isFrontFaceCCW === state.isFrontFaceCCW) && (this.depthBias === state.depthBias) && - (this.depthBiasFactor === state.depthBiasFactor) && + (this.depthBiasClamp === state.depthBiasClamp) && + (this.depthBiasSlop === state.depthBiasSlop) && (this.isDepthClip === state.isDepthClip) && - // (this.lineWidth === state.lineWidth) && + (this.lineWidth === state.lineWidth) && (this.isMultisample === state.isMultisample); } } @@ -127,6 +130,7 @@ export interface IGFXPipelineStateInfo { rs: GFXRasterizerState; dss: GFXDepthStencilState; bs: GFXBlendState; + dynamicStates?: GFXDynamicState[]; layout: GFXPipelineLayout; renderPass: GFXRenderPass; } @@ -153,12 +157,16 @@ export abstract class GFXPipelineState extends GFXObject { return this._bs as GFXBlendState; } + public get dynamicStates (): GFXDynamicState[] { + return this._dynamicStates; + } + public get pipelineLayout (): GFXPipelineLayout { - return this._layout as GFXPipelineLayout; + return this._layout as GFXPipelineLayout; } public get renderPass (): GFXRenderPass { - return this._renderPass as GFXRenderPass; + return this._renderPass as GFXRenderPass; } protected _device: GFXDevice; @@ -168,6 +176,7 @@ export abstract class GFXPipelineState extends GFXObject { protected _rs: GFXRasterizerState | null = null; protected _dss: GFXDepthStencilState | null = null; protected _bs: GFXBlendState | null = null; + protected _dynamicStates: GFXDynamicState[] = []; protected _layout: GFXPipelineLayout | null = null; protected _renderPass: GFXRenderPass | null = null; diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 8806d9c3f4..245e7b2fbc 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -6,9 +6,11 @@ import { GFXBufferUsageBit, GFXCommandBufferType, GFXStatus, + GFXStencilFace, GFXTextureLayout, IGFXColor, IGFXRect, + IGFXViewport, } from '../define'; import { GFXDevice } from '../device'; import { GFXFramebuffer } from '../framebuffer'; @@ -34,6 +36,28 @@ import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { WebGLGFXPipelineState } from './webgl-pipeline-state'; import { WebGLGFXTexture } from './webgl-texture'; +export interface IGFXDepthBias { + constantFactor: number; + clamp: number; + slopeFactor: number; +} + +export interface IGFXDepthBounds { + minBounds: number; + maxBounds: number; +} + +export interface IGFXStencilWriteMask { + face: GFXStencilFace; + writeMask: number; +} + +export interface IGFXStencilCompareMask { + face: GFXStencilFace; + reference: number; + compareMask: number; +} + export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); @@ -41,6 +65,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { private _curGPUPipelineState: WebGLGPUPipelineState | null = null; private _curGPUBindingLayout: WebGLGPUBindingLayout | null = null; private _curGPUInputAssembler: WebGLGPUInputAssembler | null = null; + private _curViewport: IGFXViewport | null = null; + private _curScissor: IGFXRect | null = null; + private _curLineWidth: number | null = null; + private _curDepthBias: IGFXDepthBias | null = null; + private _curBlendConstants: number[] = []; + private _curDepthBounds: IGFXDepthBounds | null = null; + private _curStencilWriteMask: IGFXStencilWriteMask | null = null; + private _curStencilCompareMask: IGFXStencilCompareMask | null = null; private _isStateInvalied: boolean = false; constructor (device: GFXDevice) { @@ -131,6 +163,165 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } + public setViewport (viewport: IGFXViewport) { + if (!this._curViewport) { + this._curViewport = { + left: viewport.left, + top: viewport.top, + width: viewport.width, + height: viewport.height, + minDepth: viewport.minDepth, + maxDepth: viewport.maxDepth, + }; + } else { + if (this._curViewport.left !== viewport.left || + this._curViewport.top !== viewport.top || + this._curViewport.width !== viewport.width || + this._curViewport.height !== viewport.height || + this._curViewport.minDepth !== viewport.minDepth || + this._curViewport.maxDepth !== viewport.maxDepth) { + + this._curViewport.left = viewport.left; + this._curViewport.top = viewport.top; + this._curViewport.width = viewport.width; + this._curViewport.height = viewport.height; + this._curViewport.minDepth = viewport.minDepth; + this._curViewport.maxDepth = viewport.maxDepth; + this._isStateInvalied = true; + } + } + + if (this._curViewport !== viewport) { + this._curViewport = viewport; + this._isStateInvalied = true; + } + } + + public setScissor (scissor: IGFXRect) { + if (!this._curScissor) { + this._curScissor = { + x: scissor.x, + y: scissor.y, + width: scissor.width, + height: scissor.height, + }; + } else { + if (this._curScissor.x !== scissor.x || + this._curScissor.y !== scissor.y || + this._curScissor.width !== scissor.width || + this._curScissor.height !== scissor.height) { + this._curScissor.x = scissor.x; + this._curScissor.y = scissor.y; + this._curScissor.width = scissor.width; + this._curScissor.height = scissor.height; + this._isStateInvalied = true; + } + } + } + + public setLineWidth (lineWidth: number) { + if (this._curLineWidth !== lineWidth) { + this._curLineWidth = lineWidth; + this._isStateInvalied = true; + } + } + + public setDepthBias (depthBiasConstantFacotr: number, depthBiasClamp: number, depthBiasSlopeFactor: number) { + if (!this._curDepthBias) { + this._curDepthBias = { + constantFactor: depthBiasConstantFacotr, + clamp: depthBiasClamp, + slopeFactor: depthBiasSlopeFactor, + }; + this._isStateInvalied = true; + } else { + if (this._curDepthBias.constantFactor !== depthBiasConstantFacotr || + this._curDepthBias.clamp !== depthBiasClamp || + this._curDepthBias.slopeFactor !== depthBiasSlopeFactor) { + + this._curDepthBias.constantFactor = depthBiasConstantFacotr; + this._curDepthBias.clamp = depthBiasClamp; + this._curDepthBias.slopeFactor = depthBiasSlopeFactor; + this._isStateInvalied = true; + } + } + } + + public setBlendConstants (blendConstants: number[]) { + if (!this._curBlendConstants && + blendConstants.length === 4) { + this._curBlendConstants = [blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]]; + this._isStateInvalied = true; + } else { + if (blendConstants.length === 4 && ( + this._curBlendConstants[0] !== blendConstants[0] || + this._curBlendConstants[1] !== blendConstants[1] || + this._curBlendConstants[2] !== blendConstants[2] || + this._curBlendConstants[3] !== blendConstants[3])) { + this._curBlendConstants = [blendConstants[0], blendConstants[1], blendConstants[2], blendConstants[3]]; + this._isStateInvalied = true; + } + } + } + + public setDepthBound (minDepthBounds: number, maxDepthBounds: number) { + if (!this._curDepthBounds) { + this._curDepthBounds = { + minBounds: minDepthBounds, + maxBounds: maxDepthBounds, + }; + this._isStateInvalied = true; + } else { + if (this._curDepthBounds.minBounds !== minDepthBounds || + this._curDepthBounds.maxBounds !== maxDepthBounds) { + this._curDepthBounds = { + minBounds: minDepthBounds, + maxBounds: maxDepthBounds, + }; + this._isStateInvalied = true; + } + } + } + + public setStencilWirteMask (face: GFXStencilFace, writeMask: number) { + if (!this._curStencilWriteMask) { + this._curStencilWriteMask = { + face, + writeMask, + }; + this._isStateInvalied = true; + } else { + if (this._curStencilWriteMask.face !== face || + this._curStencilWriteMask.writeMask !== writeMask) { + + this._curStencilWriteMask.face = face; + this._curStencilWriteMask.writeMask = writeMask; + this._isStateInvalied = true; + } + } + } + + public setStencilCompareMask (face: GFXStencilFace, reference: number, compareMask: number) { + if (!this._curStencilCompareMask) { + this._curStencilCompareMask = { + face, + reference, + compareMask, + }; + this._isStateInvalied = true; + } else { + if (this._curStencilCompareMask.face !== face || + this._curStencilCompareMask.reference !== reference || + this._curStencilCompareMask.compareMask !== compareMask) { + + this._curStencilCompareMask.face = face; + this._curStencilCompareMask.reference = reference; + this._curStencilCompareMask.compareMask = compareMask; + this._isStateInvalied = true; + } + } + } + public draw (inputAssembler: GFXInputAssembler) { if (this._type === GFXCommandBufferType.PRIMARY && this._isInRenderPass || this._type === GFXCommandBufferType.SECONDARY) { @@ -240,6 +431,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { bindStatesCmd.gpuPipelineState = this._curGPUPipelineState; bindStatesCmd.gpuBindingLayout = this._curGPUBindingLayout; bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler; + bindStatesCmd.viewport = this._curViewport; + bindStatesCmd.scissor = this._curScissor; + bindStatesCmd.lineWidth = this._curLineWidth; + bindStatesCmd.depthBias = this._curDepthBias; + bindStatesCmd.blendConstants = this._curBlendConstants; + bindStatesCmd.depthBounds = this._curDepthBounds; + bindStatesCmd.stencilWriteMask = this._curStencilWriteMask; + bindStatesCmd.stencilCompareMask = this._curStencilCompareMask; this.cmdPackage.bindStatesCmds.push(bindStatesCmd); this.cmdPackage.cmds.push(WebGLCmd.BIND_STATES); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 797afea5a4..75223bab2c 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,10 +1,11 @@ import { CachedArray } from '../../core/memop/cached-array'; import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, - GFXCullMode, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, GFXMemoryUsageBit, - GFXShaderType, GFXTextureFlagBit, GFXTextureLayout, GFXTextureViewType, - GFXType, IGFXColor, IGFXRect, WebGLEXT } from '../define'; + GFXCullMode, GFXDynamicState, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, + GFXMemoryUsageBit, GFXShaderType, GFXStencilFace, GFXTextureFlagBit, + GFXTextureLayout, GFXTextureViewType, GFXType, IGFXColor, IGFXRect, IGFXViewport, WebGLEXT } from '../define'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { IGFXDepthBias, IGFXDepthBounds, IGFXStencilCompareMask, IGFXStencilWriteMask } from './webgl-command-buffer'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer, WebGLGPUInput, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUShader, @@ -376,7 +377,14 @@ export class WebGLCmdBindStates extends WebGLCmdObject { public gpuPipelineState: WebGLGPUPipelineState | null = null; public gpuBindingLayout: WebGLGPUBindingLayout | null = null; public gpuInputAssembler: WebGLGPUInputAssembler | null = null; - + public viewport: IGFXViewport | null = null; + public scissor: IGFXRect | null = null; + public lineWidth: number | null = null; + public depthBias: IGFXDepthBias | null = null; + public blendConstants: number[] | null = null; + public depthBounds: IGFXDepthBounds | null = null; + public stencilWriteMask: IGFXStencilWriteMask | null = null; + public stencilCompareMask: IGFXStencilCompareMask | null = null; constructor () { super(WebGLCmd.BIND_STATES); } @@ -1080,6 +1088,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web const gl = device.gl; const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 + let gpuPipelineState: WebGLGPUPipelineState | null = null; let gpuShader: WebGLGPUShader | null = null; let gpuInputAssembler: WebGLGPUInputAssembler | null = null; let glPrimitive = WebGLRenderingContext.TRIANGLES; @@ -1264,7 +1273,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; if (cmd2.gpuPipelineState) { - + gpuPipelineState = cmd2.gpuPipelineState; glPrimitive = cmd2.gpuPipelineState.glPrimitive; if (cmd2.gpuPipelineState.gpuShader) { @@ -1310,18 +1319,16 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } if ((device.stateCache.rs.depthBias !== rs.depthBias) || - (device.stateCache.rs.depthBiasFactor !== rs.depthBiasFactor)) { - gl.polygonOffset(rs.depthBiasFactor, rs.depthBias); + (device.stateCache.rs.depthBiasSlop !== rs.depthBiasSlop)) { + gl.polygonOffset(rs.depthBias, rs.depthBiasSlop); device.stateCache.rs.depthBias = rs.depthBias; - device.stateCache.rs.depthBiasFactor = rs.depthBiasFactor; + device.stateCache.rs.depthBiasSlop = rs.depthBiasSlop; } - /* no browser actually supports this if (device.stateCache.rs.lineWidth !== rs.lineWidth) { gl.lineWidth(rs.lineWidth); device.stateCache.rs.lineWidth = rs.lineWidth; } - */ } // rasterizater state @@ -1879,6 +1886,164 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } + if (gpuPipelineState) { + for (const dynamicState of gpuPipelineState.dynamicStates) { + switch (dynamicState) { + case GFXDynamicState.VIEWPORT: { + if (cmd2.viewport) { + if (device.stateCache.viewport.left !== cmd2.viewport.left || + device.stateCache.viewport.top !== cmd2.viewport.top || + device.stateCache.viewport.width !== cmd2.viewport.width || + device.stateCache.viewport.height !== cmd2.viewport.height) { + + gl.viewport(cmd2.viewport.left, cmd2.viewport.top, cmd2.viewport.width, cmd2.viewport.height); + + device.stateCache.viewport.left = cmd2.viewport.left; + device.stateCache.viewport.top = cmd2.viewport.top; + device.stateCache.viewport.width = cmd2.viewport.width; + device.stateCache.viewport.height = cmd2.viewport.height; + } + } + break; + } + case GFXDynamicState.SCISSOR: { + if (cmd2.scissor) { + if (device.stateCache.scissorRect.x !== cmd2.scissor.x || + device.stateCache.scissorRect.y !== cmd2.scissor.y || + device.stateCache.scissorRect.width !== cmd2.scissor.width || + device.stateCache.scissorRect.height !== cmd2.scissor.height) { + + gl.scissor(cmd2.scissor.x, cmd2.scissor.y, cmd2.scissor.width, cmd2.scissor.height); + + device.stateCache.scissorRect.x = cmd2.scissor.x; + device.stateCache.scissorRect.y = cmd2.scissor.y; + device.stateCache.scissorRect.width = cmd2.scissor.width; + device.stateCache.scissorRect.height = cmd2.scissor.height; + } + } + break; + } + case GFXDynamicState.LINE_WIDTH: { + if (cmd2.lineWidth) { + if (device.stateCache.rs.lineWidth !== cmd2.lineWidth) { + gl.lineWidth(cmd2.lineWidth); + device.stateCache.rs.lineWidth = cmd2.lineWidth; + } + } + break; + } + case GFXDynamicState.DEPTH_BIAS: { + if (cmd2.depthBias) { + + if ((device.stateCache.rs.depthBias !== cmd2.depthBias.constantFactor) || + (device.stateCache.rs.depthBiasSlop !== cmd2.depthBias.slopeFactor)) { + gl.polygonOffset(cmd2.depthBias.constantFactor, cmd2.depthBias.slopeFactor); + device.stateCache.rs.depthBias = cmd2.depthBias.constantFactor; + device.stateCache.rs.depthBiasSlop = cmd2.depthBias.slopeFactor; + } + } + break; + } + case GFXDynamicState.BLEND_CONSTANTS: { + if (cmd2.blendConstants) { + if ((device.stateCache.bs.blendColor[0] !== cmd2.blendConstants[0]) || + (device.stateCache.bs.blendColor[1] !== cmd2.blendConstants[1]) || + (device.stateCache.bs.blendColor[2] !== cmd2.blendConstants[2]) || + (device.stateCache.bs.blendColor[3] !== cmd2.blendConstants[3])) { + + gl.blendColor(cmd2.blendConstants[0], cmd2.blendConstants[1], cmd2.blendConstants[2], cmd2.blendConstants[3]); + + device.stateCache.bs.blendColor[0] = cmd2.blendConstants[0]; + device.stateCache.bs.blendColor[1] = cmd2.blendConstants[1]; + device.stateCache.bs.blendColor[2] = cmd2.blendConstants[2]; + device.stateCache.bs.blendColor[3] = cmd2.blendConstants[3]; + } + } + break; + } + case GFXDynamicState.STENCIL_WRITE_MASK: { + if (cmd2.stencilWriteMask) { + switch (cmd2.stencilWriteMask.face) { + case GFXStencilFace.FRONT: { + if (device.stateCache.dss.stencilWriteMaskFront !== cmd2.stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, cmd2.stencilWriteMask.writeMask); + device.stateCache.dss.stencilWriteMaskFront = cmd2.stencilWriteMask.writeMask; + } + break; + } + case GFXStencilFace.BACK: { + if (device.stateCache.dss.stencilWriteMaskBack !== cmd2.stencilWriteMask.writeMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, cmd2.stencilWriteMask.writeMask); + device.stateCache.dss.stencilWriteMaskBack = cmd2.stencilWriteMask.writeMask; + } + break; + } + case GFXStencilFace.ALL: { + if (device.stateCache.dss.stencilWriteMaskFront !== cmd2.stencilWriteMask.writeMask || + device.stateCache.dss.stencilWriteMaskBack !== cmd2.stencilWriteMask.writeMask) { + gl.stencilMask(cmd2.stencilWriteMask.writeMask); + device.stateCache.dss.stencilWriteMaskFront = cmd2.stencilWriteMask.writeMask; + device.stateCache.dss.stencilWriteMaskBack = cmd2.stencilWriteMask.writeMask; + } + break; + } + } + } + break; + } + case GFXDynamicState.STENCIL_COMPARE_MASK: { + if (cmd2.stencilCompareMask) { + switch (cmd2.stencilCompareMask.face) { + case GFXStencilFace.FRONT: { + if (device.stateCache.dss.stencilRefFront !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskFront !== cmd2.stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + WebGLRenderingContext.FRONT, + WebGLCmpFuncs[device.stateCache.dss.stencilFuncFront], + cmd2.stencilCompareMask.reference, + cmd2.stencilCompareMask.compareMask); + device.stateCache.dss.stencilRefFront = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskFront = cmd2.stencilCompareMask.compareMask; + } + break; + } + case GFXStencilFace.BACK: { + if (device.stateCache.dss.stencilRefBack !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskBack !== cmd2.stencilCompareMask.compareMask) { + gl.stencilFuncSeparate( + WebGLRenderingContext.BACK, + WebGLCmpFuncs[device.stateCache.dss.stencilFuncBack], + cmd2.stencilCompareMask.reference, + cmd2.stencilCompareMask.compareMask); + device.stateCache.dss.stencilRefBack = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskBack = cmd2.stencilCompareMask.compareMask; + } + break; + } + case GFXStencilFace.ALL: { + if (device.stateCache.dss.stencilRefFront !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskFront !== cmd2.stencilCompareMask.compareMask || + device.stateCache.dss.stencilRefBack !== cmd2.stencilCompareMask.reference || + device.stateCache.dss.stencilReadMaskBack !== cmd2.stencilCompareMask.compareMask) { + gl.stencilFunc( + WebGLCmpFuncs[device.stateCache.dss.stencilFuncBack], + cmd2.stencilCompareMask.reference, + cmd2.stencilCompareMask.compareMask); + device.stateCache.dss.stencilRefFront = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskFront = cmd2.stencilCompareMask.compareMask; + device.stateCache.dss.stencilRefBack = cmd2.stencilCompareMask.reference; + device.stateCache.dss.stencilReadMaskBack = cmd2.stencilCompareMask.compareMask; + } + break; + } + } + } + break; + } + } // switch + } // for + } // if + break; } case WebGLCmd.DRAW: { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index e834db69a1..ca1e1c9978 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -882,6 +882,7 @@ export class WebGLGFXDevice extends GFXDevice { rs: info.rs, dss: info.dss, bs: info.bs, + dynamicStates: (info.dynamicStates !== undefined ? info.dynamicStates : []), gpuLayout, gpuRenderPass, }; diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index ddd993a09c..e66513ba80 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -3,6 +3,7 @@ import { GFXBindingType, GFXBufferUsage, GFXBufferUsageBit, + GFXDynamicState, GFXFormat, GFXMemoryUsage, GFXMemoryUsageBit, @@ -217,6 +218,7 @@ export class WebGLGPUPipelineState extends WebGLGPUObject { public rs: GFXRasterizerState = new GFXRasterizerState(); public dss: GFXDepthStencilState = new GFXDepthStencilState(); public bs: GFXBlendState = new GFXBlendState(); + public dynamicStates: GFXDynamicState[] = []; public gpuLayout: WebGLGPUPipelineLayout | null = null; public gpuRenderPass: WebGLGPURenderPass | null = null; diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts index fa40398838..a6cddf6b54 100644 --- a/cocos/gfx/webgl/webgl-pipeline-state.ts +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -28,6 +28,11 @@ export class WebGLGFXPipelineState extends GFXPipelineState { this._rs = info.rs; this._dss = info.dss; this._bs = info.bs; + + if (info.dynamicStates !== undefined) { + this._dynamicStates = info.dynamicStates; + } + this._layout = info.layout; this._renderPass = info.renderPass; diff --git a/cocos/pipeline/testcase/test-material-stage.ts b/cocos/pipeline/testcase/test-material-stage.ts deleted file mode 100644 index f9b67028d2..0000000000 --- a/cocos/pipeline/testcase/test-material-stage.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { Material } from '../../3d/assets/material'; -import ImageAsset from '../../assets/image-asset'; -import Texture2D from '../../assets/texture-2d'; -import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; -import { GFXFramebuffer } from '../../gfx/framebuffer'; -import { GFXInputAssembler } from '../../gfx/input-assembler'; -import { Camera } from '../../renderer/scene/camera'; -import { RenderFlow } from '../render-flow'; -import { IRenderStageInfo, RenderStage } from '../render-stage'; -import { RenderView } from '../render-view'; - -export class TestMaterialStage extends RenderStage { - - private _textureAsset: Texture2D | null = null; - private _material: Material = new Material('testMtrl'); - - constructor (flow: RenderFlow) { - super(flow); - } - - public initialize (info: IRenderStageInfo): boolean { - - if (info.name !== undefined) { - this._name = info.name; - } - - this._priority = info.priority; - this._framebuffer = info.framebuffer; - if (!this._framebuffer) { - return false; - } - - this._cmdBuff = this._device.createCommandBuffer({ - allocator: this._device.commandAllocator, - type: GFXCommandBufferType.PRIMARY, - }); - - // load texture - const imgElms = this._device.canvas.getElementsByTagName('img'); - if (imgElms.length) { - if (!this.loadTexture(imgElms[0] as HTMLImageElement)) { - console.error('Load texture failed.'); - return false; - } - } else { - console.error('Not found image, load texture failed.'); - } - - return true; - } - - public destroy () { - if (this._textureAsset) { - this._textureAsset.destroy(); - this._textureAsset = null; - } - if (this._cmdBuff) { - this._cmdBuff.destroy(); - this._cmdBuff = null; - } - } - - public render (view: RenderView) { - const mtl = this._material; - // @ts-ignore - if (!mtl.inited) { - // material - mtl.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js - const pass = mtl.passes[0]; - - /* efficient pass API * - const texBinding = pass.getBinding('u_sampler'); - const texView = this._textureAsset && this._textureAsset.getGFXTextureView(); - if (texView) { pass.bindTextureView(texBinding, texView); } - const colorHandle = pass.getHandle('u_color'); - pass.setUniform(colorHandle, cc.color('#ffffff')); - /* convenient material API */ - mtl.setProperty('u_sampler', this._textureAsset); - mtl.setProperty('u_color', cc.color('#ff0000')); - /**/ - - pass.update(); - // @ts-ignore - mtl.inited = true; - } - - const camera = view.camera as Camera; - - const cmdBuff = this._cmdBuff as GFXCommandBuffer; - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; - - cmdBuff.begin(); - cmdBuff.beginRenderPass( this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, - this._clearDepth, this._clearStencil); - - cmdBuff.bindPipelineState(this._material.passes[0].pipelineState); - cmdBuff.bindBindingLayout(this._material.passes[0].bindingLayout); - - cmdBuff.bindInputAssembler( this._pipeline.quadIA as GFXInputAssembler); - cmdBuff.draw( this._pipeline.quadIA as GFXInputAssembler); - cmdBuff.endRenderPass(); - cmdBuff.end(); - - this._device.queue.submit([cmdBuff]); - } - - private loadTexture (image: HTMLImageElement): boolean { - const textureAsset = this._textureAsset = new Texture2D(); - textureAsset.image = new ImageAsset(image); - - const texture = textureAsset.getGFXTexture(); - if (!texture) { return false; } - const texView = textureAsset.getGFXTextureView(); - if (!texView) { return false; } - - return true; - } -} diff --git a/cocos/pipeline/testcase/test-model-stage.ts b/cocos/pipeline/testcase/test-model-stage.ts deleted file mode 100644 index 979f9fd2ac..0000000000 --- a/cocos/pipeline/testcase/test-model-stage.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { Material } from '../../3d/assets/material'; -import ImageAsset from '../../assets/image-asset'; -import Texture2D from '../../assets/texture-2d'; -import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; -import { GFXFramebuffer } from '../../gfx/framebuffer'; -import { Camera } from '../../renderer/scene/camera'; -import { Model } from '../../renderer/scene/model'; -import { Scene } from '../../scene-graph'; -import { RenderFlow } from '../render-flow'; -import { IRenderStageInfo, RenderStage } from '../render-stage'; -import { RenderView } from '../render-view'; - -export class TestModelStage extends RenderStage { - - private _material: Material = new Material("testMtrl"); - private _model: Model; - private _scene: Scene; - private _init: boolean = false; - private _textureAsset: Texture2D | null = null; - - constructor(flow: RenderFlow) { - super(flow); - } - - public initialize (info: IRenderStageInfo): boolean { - - if (info.name !== undefined) { - this._name = info.name; - } - - this._priority = info.priority; - this._framebuffer = info.framebuffer; - if (!this._framebuffer) { - return false; - } - - this._cmdBuff = this._device.createCommandBuffer({ - allocator: this._device.commandAllocator, - type: GFXCommandBufferType.PRIMARY, - }); - - // load texture - const imgElms = this._device.canvas.getElementsByTagName('img'); - if (imgElms.length) { - if (!this.loadTexture(imgElms[0] as HTMLImageElement)) { - console.error('Load texture failed.'); - return false; - } - } else { - console.error('Not found image, load texture failed.'); - } - - return true; - } - - public destroy () { - - if (this._texView) { - this._texView.destroy(); - this._texView = null; - } - - if (this._texture) { - this._texture.destroy(); - this._texture = null; - } - - if (this._cmdBuff) { - this._cmdBuff.destroy(); - this._cmdBuff = null; - } - } - - public render (view: RenderView) { - - if (!this._init) { - - this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js - this._material.setProperty('u_sampler', this._textureAsset); - this._material.setProperty('u_color', cc.color('#ff1234')); - this._material.passes[0].update(); - - this._scene = new Scene(); - this._scene._scene = this._scene; - const modelCom = this._scene.addComponent('cc.ModelComponent'); - modelCom.material = this._material; - modelCom.mesh = cc.utils.createMesh(cc.game._gfxDevice, cc.primitives.box({ length: 1, width: 1, height: 1 })); - this._model = modelCom._models[0]; - this._scene.setRotationFromEuler(45, 45, 45); - this._scene._rot = this._scene._lrot; - this._init = true; - } - - const camera = view.camera as Camera; - - const cmdBuff = this._cmdBuff as GFXCommandBuffer; - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; - this._model._updateTransform(); - this._model.updateUBOs(); - cmdBuff.begin(); - cmdBuff.beginRenderPass(this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, - this._clearDepth, this._clearStencil); - - cmdBuff.execute(this._model.commandBuffers, this._model.commandBuffers.length); - cmdBuff.endRenderPass(); - cmdBuff.end(); - - this._device.queue.submit([cmdBuff]); - } - - private loadTexture (image: HTMLImageElement): boolean { - const textureAsset = this._textureAsset = new Texture2D(); - textureAsset.image = new ImageAsset(image); - - const texture = textureAsset.getGFXTexture(); - if (!texture) { return false; } - const texView = textureAsset.getGFXTextureView(); - if (!texView) { return false; } - - return true; - } -} diff --git a/cocos/pipeline/testcase/test-stage.ts b/cocos/pipeline/testcase/test-stage.ts deleted file mode 100644 index 1a28677ccc..0000000000 --- a/cocos/pipeline/testcase/test-stage.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { GFXBindingLayout } from '../../gfx/binding-layout'; -import { GFXBuffer } from '../../gfx/buffer'; -import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXAddress, GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXCommandBufferType, GFXCullMode, GFXFilter, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode, GFXShaderType, GFXTextureFlagBit, GFXTextureLayout, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType, GFXType } from '../../gfx/define'; -import { GFXFramebuffer } from '../../gfx/framebuffer'; -import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; -import { GFXBlendState, GFXDepthStencilState, GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; -import { GFXRenderPass } from '../../gfx/render-pass'; -import { GFXSampler } from '../../gfx/sampler'; -import { GFXShader } from '../../gfx/shader'; -import { GFXTexture } from '../../gfx/texture'; -import { GFXTextureView } from '../../gfx/texture-view'; -import { Camera } from '../../renderer/scene/camera'; -import { RenderFlow } from '../render-flow'; -import { UBOGlobal } from '../render-pipeline'; -import { IRenderStageInfo, RenderStage } from '../render-stage'; -import { RenderView } from '../render-view'; - -/* -declare module '*.png' { - const value: any; - export = value; - } -*/ -// declare function require(string): string; -// const image = require('../../../playground/cocos2d-x.png'); - -const _shader_vs = `#version 100 -attribute vec2 a_position; -attribute vec2 a_texCoord; - -uniform mat4 u_matViewProj; - -varying vec2 v_texCoord; - -void main() { - //gl_Position = vec4(a_position, 0.0, 1.0); - gl_Position = u_matViewProj * vec4(a_position, 0.0, 1.0); - v_texCoord = a_texCoord; -}`; - -const _shader_fs = `#version 100 -precision highp float; -varying vec2 v_texCoord; - -uniform vec4 u_color; - -uniform sampler2D u_sampler; - -void main() { - //gl_FragColor = vec4(0.6, 0.3, 0.3, 1.0); - gl_FragColor = texture2D(u_sampler, v_texCoord); - gl_FragColor.r = u_color.r; -}`; - -export class TestStage extends RenderStage { - - private _shader: GFXShader | null = null; - private _bindingLayout: GFXBindingLayout | null = null; - private _pipelineLayout: GFXPipelineLayout | null = null; - private _pipelineState: GFXPipelineState | null = null; - private _rs: GFXRasterizerState = new GFXRasterizerState(); - private _dss: GFXDepthStencilState = new GFXDepthStencilState(); - private _bs: GFXBlendState = new GFXBlendState(); - - private _ubo: GFXBuffer | null = null; - - private _texture: GFXTexture | null = null; - private _texView: GFXTextureView | null = null; - private _sampler: GFXSampler | null = null; - - constructor (flow: RenderFlow) { - super(flow); - } - - public initialize (info: IRenderStageInfo): boolean { - - if (info.name !== undefined) { - this._name = info.name; - } - - this._priority = info.priority; - this._framebuffer = info.framebuffer; - if (!this._framebuffer) { - return false; - } - - this._cmdBuff = this._device.createCommandBuffer({ - allocator: this._device.commandAllocator, - type: GFXCommandBufferType.PRIMARY, - }); - - // create shader - const vsStage = { - type: GFXShaderType.VERTEX, - source: _shader_vs, - }; - - const fsStage = { - type: GFXShaderType.FRAGMENT, - source: _shader_fs, - }; - - this._shader = this._device.createShader({ - name: 'test', - stages: [vsStage, fsStage], - blocks: [UBOGlobal.BLOCK, { - binding: 5, name: 'UBO', members: [ - { name: 'u_color', type: GFXType.FLOAT4, count: 1 }, - ], - }], - samplers: [ - { binding: 10, name: 'u_sampler', type: GFXType.SAMPLER2D, count: 1 }, - ], - }); - if (!this._shader) { - return false; - } - - this._bindingLayout = this._device.createBindingLayout({ - bindings: [ - { binding: 0, type: GFXBindingType.UNIFORM_BUFFER, name: UBOGlobal.BLOCK.name }, - { binding: 5, type: GFXBindingType.UNIFORM_BUFFER, name: 'UBO' }, - { binding: 10, type: GFXBindingType.SAMPLER, name: 'u_sampler' }, - ], - }); - if (!this._bindingLayout) { - return false; - } - - this._pipelineLayout = this._device.createPipelineLayout({ - layouts: [this._bindingLayout], - }); - if (!this._pipelineLayout) { - return false; - } - - if (!this._pipeline.quadIA) { - return false; - } - - const is: GFXInputState = { attributes: this._pipeline.quadIA.attributes }; - - this._rs.cullMode = GFXCullMode.BACK; - - this._pipelineState = this._device.createPipelineState({ - primitive: GFXPrimitiveMode.TRIANGLE_LIST, - shader: this._shader, - is, - rs: this._rs, - dss: this._dss, - bs: this._bs, - layout: this._pipelineLayout, - renderPass: this._framebuffer.renderPass as GFXRenderPass, - }); - - // create ubo - const color = [1.0, 0.3, 0.3, 1.0]; - const uboStride = color.length * 4; - this._ubo = this._device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST, - size: uboStride, - stride: uboStride, - }); - - if (!this._ubo) { - return false; - } - - const uboView = new Float32Array(4); - uboView[0] = 1.0; - uboView[1] = 0.3; - uboView[2] = 0.3; - uboView[3] = 1.0; - this._ubo.update(uboView); - - // load texture - const imgElms = this._device.canvas.getElementsByTagName('img'); - if (imgElms.length) { - if (!this.loadTexture( imgElms[0] as HTMLImageElement)) { - console.error('Load texture failed.'); - return false; - } - - this.bindBindings(); - } else { - console.error('Not found image, load texture failed.'); - } - - return true; - } - - public destroy () { - - if (this._shader) { - this._shader.destroy(); - this._shader = null; - } - - if (this._ubo) { - this._ubo.destroy(); - this._ubo = null; - } - - if (this._texView) { - this._texView.destroy(); - this._texView = null; - } - - if (this._texture) { - this._texture.destroy(); - this._texture = null; - } - - if (this._bindingLayout) { - this._bindingLayout.destroy(); - this._bindingLayout = null; - } - - if (this._pipelineLayout) { - this._pipelineLayout.destroy(); - this._pipelineLayout = null; - } - - if (this._pipelineState) { - this._pipelineState.destroy(); - this._pipelineState = null; - } - - if (this._cmdBuff) { - this._cmdBuff.destroy(); - this._cmdBuff = null; - } - } - - public render (view: RenderView) { - const cmdBuff = this._cmdBuff as GFXCommandBuffer; - - const camera = view.camera as Camera; - - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; - - cmdBuff.begin(); - cmdBuff.beginRenderPass( this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); - cmdBuff.bindPipelineState( this._pipelineState as GFXPipelineState); - cmdBuff.bindBindingLayout( this._bindingLayout as GFXBindingLayout); - cmdBuff.bindInputAssembler(this._pipeline.quadIA); - cmdBuff.draw(this._pipeline.quadIA); - cmdBuff.endRenderPass(); - cmdBuff.end(); - - this._device.queue.submit([cmdBuff]); - } - - private loadTexture (image: HTMLImageElement): boolean { - // let canvas2d = this._device.canvas.getContext("2d"); - /* - let canvas = document.createElement('canvas'); - let context = canvas.getContext('2d'); - if (!context) { - return false; - } - - canvas.width = image.width; - canvas.height = image.height; - context.drawImage(image, 0, 0); - - let imgData = context.getImageData(0, 0, image.width, image.height); - let imgBuffer: ArrayBuffer = imgData.data; - */ - - this._texture = this._device.createTexture({ - type: GFXTextureType.TEX2D, - usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, - format: GFXFormat.RGBA8, - width: image.width, - height: image.height, - flags: GFXTextureFlagBit.NONE, - }); - - if (!this._texture) { - return false; - } - - this._texView = this._device.createTextureView({ - texture: this._texture, - type: GFXTextureViewType.TV2D, - format: GFXFormat.RGBA8, - }); - - if (!this._texView) { - return false; - } - - const region: GFXBufferTextureCopy = { - buffOffset: 0, - buffStride: 0, - buffTexHeight: 0, - texOffset: { x: 0, y: 0, z: 0 }, - texExtent: { width: image.width, height: image.height, depth: 1 }, - texSubres: { baseMipLevel: 0, levelCount: 1, baseArrayLayer: 0, layerCount: 1 }, - }; - - this._device.copyImageSourceToTexture(image, this._texture, [region]); - // this._device.copyBufferToTexture(imgBuffer, this._texture, [region]); - - this._sampler = this._device.createSampler({ - minFilter: GFXFilter.LINEAR, - magFilter: GFXFilter.LINEAR, - mipFilter: GFXFilter.NONE, - addressU: GFXAddress.WRAP, - addressV: GFXAddress.WRAP, - }); - - return true; - } - - private bindBindings (): boolean { - - if (!this._bindingLayout) { - return false; - } - - this._bindingLayout.bindBuffer(0, this.pipeline.globalUBO); - this._bindingLayout.bindBuffer(5, this._ubo as GFXBuffer); - this._bindingLayout.bindTextureView(10, this._texView as GFXTextureView); - this._bindingLayout.bindSampler(10, this._sampler as GFXSampler); - this._bindingLayout.update(); - - return true; - } -} diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 6960145e94..a747292daa 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -8,7 +8,7 @@ import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXPrimitiveMode, import { GFXDevice } from '../../gfx/device'; import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, - GFXInputState, GFXPipelineState, GFXRasterizerState, IGFXPipelineStateInfo } from '../../gfx/pipeline-state'; + GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; @@ -22,15 +22,14 @@ export interface IPassInfoFull extends IPassInfo { samplers: ISamplerInfo[]; shader: GFXShader; renderPass: GFXRenderPass; - globals: GFXBuffer; } -export interface IPassOverrides { - bs: GFXBlendState; - dss: GFXDepthStencilState; - rs: GFXRasterizerState; - primitive: GFXPrimitiveMode; -} +type RecursivePartial = { + [P in keyof T]?: + T[P] extends Array ? Array> : + T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; +}; +export type PassOverrides = RecursivePartial; const _type2fn = { [GFXType.INT]: (a: Float32Array, v: any) => a[0] = v, @@ -81,27 +80,32 @@ interface IBlock { dirty: boolean; } +interface IPassResources { + bindingLayout: GFXBindingLayout; + pipelineLayout: GFXPipelineLayout; + pipelineState: GFXPipelineState; +} + export class Pass { public static getBindingTypeFromHandle = getBindingTypeFromHandle; public static getTypeFromHandle = getTypeFromHandle; public static getBindingFromHandle = getBindingFromHandle; public static getIndexFromHandle = getIndexFromHandle; // internal resources - protected _pipelineState: GFXPipelineState | null = null; - protected _pipelineLayout: GFXPipelineLayout | null = null; - protected _bindingLayout: GFXBindingLayout | null = null; - protected _buffers: GFXBuffer[] = []; - protected _samplers: GFXSampler[] = []; + protected _buffers: Record = {}; + protected _samplers: Record = {}; + protected _textureViews: Record = {}; + protected _resources: IPassResources[] = []; // internal data protected _programName: string = ''; protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; protected _stage: RenderPassStage = RenderPassStage.DEFAULT; - protected _handleMap: Record = {}; - protected _blocks: IBlock[] = []; protected _bindings: IGFXBinding[] = []; protected _bs: GFXBlendState = new GFXBlendState(); protected _dss: GFXDepthStencilState = new GFXDepthStencilState(); protected _rs: GFXRasterizerState = new GFXRasterizerState(); + protected _handleMap: Record = {}; + protected _blocks: IBlock[] = []; // external references protected _device: GFXDevice; protected _shader: GFXShader | null = null; @@ -115,18 +119,14 @@ export class Pass { this._programName = info.program; // pipeline state const device = this._device; - const bindings = this._bindings = info.blocks.map((u) => + this._bindings = info.blocks.map((u) => ({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER }), ).concat(info.samplers.map((u) => ({ name: u.name, binding: u.binding, type: GFXBindingType.SAMPLER }), )); - this._bindingLayout = device.createBindingLayout({ bindings }); - if (!this._bindingLayout) { console.error('create binding layout failed'); return; } - this._pipelineLayout = device.createPipelineLayout({ layouts: [this._bindingLayout] }); - if (!this._pipelineLayout) { console.error('create pipeline layout failed'); return; } this._shader = info.shader; this._renderPass = info.renderPass; - this._createPipelineState(info); + this._fillinPipelineInfo(info); for (const u of info.blocks) { if (builtinRE.test(u.name)) { @@ -140,7 +140,6 @@ export class Pass { usage: GFXBufferUsageBit.UNIFORM, }); if (buffer) { - this._bindingLayout.bindBuffer(u.binding, buffer); this._buffers[u.binding] = buffer; } else { console.error('create buffer failed.'); @@ -148,7 +147,7 @@ export class Pass { } // buffer data processing system const block: IBlock = this._blocks[u.binding] = { - buffer: new ArrayBuffer(u.size), + buffer: buffer.buffer as ArrayBuffer, dirty: false, views: [], }; @@ -167,8 +166,6 @@ export class Pass { }, 0); // === u.size buffer.update(block.buffer); } - // also bind builtin globals - this._bindingLayout.bindBuffer(UBOGlobal.BLOCK.binding, info.globals); for (const u of info.samplers) { this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); @@ -177,13 +174,11 @@ export class Pass { // TODO: specify filter modes in effect }); if (sampler) { - this._bindingLayout.bindSampler(u.binding, sampler); - this._samplers.push(sampler); + this._samplers[u.binding] = sampler; } else { console.error('create sampler failed.'); } } - this._bindingLayout.update(); } public getHandle (name: string) { @@ -204,38 +199,25 @@ export class Pass { } public bindTextureView (binding: number, value: GFXTextureView) { - (this._bindingLayout as GFXBindingLayout).bindTextureView(binding, value); + this._textureViews[binding] = value; + for (const res of this._resources) { + res.bindingLayout.bindTextureView(binding, value); + } } public bindSampler (binding: number, value: GFXSampler) { - (this._bindingLayout as GFXBindingLayout).bindSampler(binding, value); + this._samplers[binding] = value; + for (const res of this._resources) { + res.bindingLayout.bindSampler(binding, value); + } } - public rebuildWithOverrides (info: Partial, overrides: IPassOverrides) { - if (this._pipelineState) { this._pipelineState.destroy(); } - const ors = Object.assign({}, overrides); - this._createPipelineState(info, (states) => { - if (overrides.primitive !== undefined) { this._primitive = states.primitive = overrides.primitive; } - Object.assign(states.rs, ors.rs); - Object.assign(states.dss, ors.dss); - if (ors.bs) { - if (ors.bs.targets) { - for (let i = 0; i < ors.bs.targets.length; i++) { - Object.assign(states.bs.targets[i], ors.bs.targets[i]); - } - delete ors.bs.targets; - } - Object.assign(states.bs, ors.bs); - } - }); - } - - public destroy () { - if (this._buffers) { this._buffers.forEach((b) => b.destroy()); this._buffers.length = 0; } - if (this._samplers) { this._samplers.forEach((b) => b.destroy()); this._samplers.length = 0; } - if (this._bindingLayout) { this._bindingLayout.destroy(); this._bindingLayout = null; } - if (this._pipelineLayout) { this._pipelineLayout.destroy(); this._pipelineLayout = null; } - if (this._pipelineState) { this._pipelineState.destroy(); this._pipelineState = null; } + public overridePipelineStates (original: IPassInfo, overrides: PassOverrides) { + this._bs = new GFXBlendState(); + this._dss = new GFXDepthStencilState(); + this._rs = new GFXRasterizerState(); + this._fillinPipelineInfo(original); + this._fillinPipelineInfo(overrides); } public update () { @@ -247,27 +229,72 @@ export class Pass { block.dirty = false; } } - (this._bindingLayout as GFXBindingLayout).update(); + } + + public destroy () { + if (this._buffers) { + for (const b of Object.values(this._buffers)) { + b.destroy(); + } + this._buffers = {}; + } + if (this._samplers) { + for (const s of Object.values(this._samplers)) { + s.destroy(); + } + this._samplers = {}; + } + } + + public createPipelineState () { + if (!this._renderPass || !this._shader) { return null; } + const bindingLayout = this._device.createBindingLayout({ bindings: this._bindings }); + for (const b of Object.keys(this._buffers)) { + bindingLayout.bindBuffer(parseInt(b), this._buffers[b]); + } + for (const s of Object.keys(this._samplers)) { + bindingLayout.bindSampler(parseInt(s), this._samplers[s]); + } + for (const t of Object.keys(this._textureViews)) { + bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]); + } + const pipelineLayout = this._device.createPipelineLayout({ layouts: [bindingLayout] }); + const pipelineState = this._device.createPipelineState({ + bs: this._bs, + dss: this._dss, + is: new GFXInputState(), + layout: pipelineLayout, + primitive: this._primitive, + renderPass: this._renderPass, + rs: this._rs, + shader: this._shader, + }); + this._resources.push({ bindingLayout, pipelineLayout, pipelineState }); + return pipelineState; + } + + public destroyPipelineState (pipelineStates: GFXPipelineState) { + const idx = this._resources.findIndex((res) => res.pipelineState === pipelineStates); + if (idx >= 0) { + const { bindingLayout: bl, pipelineLayout: pl, pipelineState: ps } = this._resources[idx]; + bl.destroy(); pl.destroy(); ps.destroy(); + this._resources.splice(idx, 1); + } } public serializePipelineStates () { - const ps = this._pipelineState as GFXPipelineState; - let res = `${ps.shader.name},${this._stage},${ps.primitive}`; - res += serializeBlendState(ps.blendState); - res += serializeDepthStencilState(ps.depthStencilState); - res += serializeRasterizerState(ps.rasterizerState); + let res = `${this._shader && this._shader.name},${this._stage},${this._primitive}`; + res += serializeBlendState(this._bs); + res += serializeDepthStencilState(this._dss); + res += serializeRasterizerState(this._rs); return res; } - protected _createPipelineState (info: Partial, override?: (states: IGFXPipelineStateInfo) => any) { - if (info.primitive) { this._primitive = info.primitive; } - if (info.stage) { this._stage = info.stage; } + protected _fillinPipelineInfo (info: Partial) { + if (info.primitive !== undefined) { this._primitive = info.primitive; } + if (info.stage !== undefined) { this._stage = info.stage; } - if (!this._shader || !this._renderPass || !this._pipelineLayout) { - console.error('gfx resouces incomplete, create pipeline state failed.'); - return null; - } - const bs = new GFXBlendState(); + const bs = this._bs; if (info.blendState) { const bsInfo = Object.assign({}, info.blendState); if (bsInfo.targets) { @@ -277,34 +304,19 @@ export class Pass { delete bsInfo.targets; Object.assign(bs, bsInfo); } - const stateInfo = { - bs: this._bs = bs, - dss: this._dss = Object.assign(new GFXDepthStencilState(), info.depthStencilState), - is: new GFXInputState(), - layout: this._pipelineLayout, - primitive: info.primitive || this._primitive, - renderPass: this._renderPass, - rs: this._rs = Object.assign(new GFXRasterizerState(), info.rasterizerState), - shader: this._shader, - }; - if (override) { override(stateInfo); } - if (this._pipelineState) { - this._pipelineState.initialize(stateInfo); - } else { - this._pipelineState = this._device.createPipelineState(stateInfo); - } + Object.assign(this._rs, info.rasterizerState); + Object.assign(this._dss, info.depthStencilState); } get programName () { return this._programName; } - get shader (): GFXShader { return this._shader!; } - get pipelineState () { return this._pipelineState as GFXPipelineState; } - get bindingLayout () { return this._bindingLayout as GFXBindingLayout; } - get primitive () { return this._primitive; } - get bindings () { return this._bindings; } + get primitive (): GFXPrimitiveMode { return this._primitive; } + get stage (): RenderPassStage { return this._stage; } + get bindings (): IGFXBinding[] { return this._bindings; } get blendState (): GFXBlendState { return this._bs; } get depthStencilState (): GFXDepthStencilState { return this._dss; } get rasterizerState (): GFXRasterizerState { return this._rs; } - get renderPass (): GFXRenderPass { return this._renderPass!; } + get shader (): GFXShader | null { return this._shader; } + get renderPass (): GFXRenderPass | null { return this._renderPass; } } function serializeBlendState (bs: GFXBlendState) { diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index b893f95aa0..aece160ebe 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -1,14 +1,12 @@ -import { IRenderingSubmesh } from "../../3d/assets/mesh"; -import { GFXDevice } from "../../gfx/device"; -import { Material } from "../../3d/assets/material"; -import { GFXCommandBuffer } from "../../gfx/command-buffer"; -import { aabb } from "../../3d/geom-utils"; -import { Vec3 } from "../../core/value-types"; -import { GFXCommandBufferType } from "../../gfx/define"; -import { GFXBuffer } from "../../gfx/buffer"; -import { UBOLocal } from "../../pipeline/render-pipeline"; -import { Pass } from "../core/pass"; -import { GFXInputAssembler, IGFXInputAssemblerInfo } from "../../gfx/input-assembler"; +import { Material } from '../../3d/assets/material'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../../gfx/input-assembler'; +import { UBOLocal } from '../../pipeline/render-pipeline'; +import { Pass } from '../core/pass'; export class SubModel { protected _subMeshObject: IRenderingSubmesh | null; diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index 557076c376..f3e4d2e613 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -295,10 +295,10 @@ export class BaseNode extends CCObject { } @property - private _parent: BaseNode | null = null; + protected _parent: this | null = null; @property - private _children: BaseNode[] = []; + protected _children: this[] = []; @property private _active = true; @@ -372,7 +372,7 @@ export class BaseNode extends CCObject { * @example * node.setParent(newNode); */ - public setParent (value: BaseNode | null) { + public setParent (value: this | null) { if (this._parent === value) { return; } @@ -485,7 +485,7 @@ export class BaseNode extends CCObject { */ public getChildByPath (path: string) { const segments = path.split('/'); - let lastNode: BaseNode = this; + let lastNode: this = this; for (const segment of segments) { const next = lastNode.children.find((childNode) => childNode.name === segment); if (!next) { @@ -498,7 +498,7 @@ export class BaseNode extends CCObject { // composition: ADD - public addChild (child: BaseNode): void { + public addChild (child: this): void { if (CC_DEV && !(child instanceof cc._BaseNode)) { return cc.errorID(1634, cc.js.getClassName(child)); @@ -521,7 +521,7 @@ export class BaseNode extends CCObject { * @example * node.insertChild(child, 2); */ - public insertChild (child: BaseNode, siblingIndex: number) { + public insertChild (child: this, siblingIndex: number) { child.parent = this; child.setSiblingIndex(siblingIndex); } @@ -591,11 +591,11 @@ export class BaseNode extends CCObject { * console.log('Walked through node ' + target.name + ' after walked all children in its sub tree'); * }); */ - public walk (prefunc: (target: BaseNode) => void, postfunc?: (target: BaseNode) => void) { + public walk (prefunc: (target: this) => void, postfunc?: (target: this) => void) { // const BaseNode = cc._BaseNode; let index = 1; - let children: BaseNode[] | null = null; - let curr: BaseNode | null = null; + let children: this[] | null = null; + let curr: this | null = null; let i = 0; let stack = BaseNode._stacks[BaseNode._stackId]; if (!stack) { @@ -606,11 +606,11 @@ export class BaseNode extends CCObject { stack.length = 0; stack[0] = this; - let parent: BaseNode | null = null; + let parent: this | null = null; let afterChildren = false; while (index) { index--; - curr = stack[index]; + curr = stack[index] as (this | null); if (!curr) { continue; } @@ -718,7 +718,7 @@ export class BaseNode extends CCObject { * node.removeChild(newNode); * node.removeChild(newNode, false); */ - public removeChild (child: BaseNode, cleanup?: boolean) { + public removeChild (child: this, cleanup?: boolean) { if (this._children.indexOf(child) > -1) { // If you don't do cleanup, the child's actions will not get removed and the if (cleanup || cleanup === undefined) { @@ -770,8 +770,8 @@ export class BaseNode extends CCObject { * @example * node.isChildOf(newNode); */ - public isChildOf (parent: BaseNode) { - let child: BaseNode | null = this; + public isChildOf (parent: this) { + let child: this | null = this; do { if (child === parent) { return true; @@ -1061,7 +1061,7 @@ export class BaseNode extends CCObject { public emit? (type: string, ...args: any[]): void; - protected _onSetParent (oldParent: BaseNode | null) { + protected _onSetParent (oldParent: this | null) { if ((oldParent == null || oldParent._scene !== this._parent!._scene) && this._parent!._scene != null) { this.walk((node) => { BaseNode._setScene(node); @@ -1133,7 +1133,7 @@ export class BaseNode extends CCObject { return destroyByParent; } - protected _onHierarchyChanged (oldParent: BaseNode | null) { + protected _onHierarchyChanged (oldParent: this | null) { const newParent = this._parent; if (this._persistNode && !(newParent instanceof cc.Scene)) { cc.game.removePersistRootNode(this); @@ -1186,7 +1186,7 @@ export class BaseNode extends CCObject { } } - protected _onHierarchyChangedBase (oldParent: BaseNode) { + protected _onHierarchyChangedBase (oldParent: this) { return this._onHierarchyChanged(oldParent); } diff --git a/globals.d.ts b/globals.d.ts index dc9638e18b..52edcb9b28 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -38,3 +38,5 @@ declare const CC_RUNTIME: boolean; declare const CC_SUPPORT_JIT: boolean; declare const cc: any; + +declare const _cc: any; diff --git a/tslint.json b/tslint.json index 8087fac659..fcac35efac 100644 --- a/tslint.json +++ b/tslint.json @@ -16,7 +16,8 @@ "object-literal-sort-keys": false, "ban-types": false, "no-bitwise": false, - "no-empty": false + "no-empty": false, + "radix": false }, "rulesDirectory": [] }