From 1eec1fd9c85961297f7904a7aefad06d32654564 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 13 Dec 2018 09:18:46 +0800 Subject: [PATCH 001/267] add ts build & test files --- cocos/renderer/gfx/gfx-buffer.ts | 29 +++++++++++ cocos/renderer/gfx/gfx-device.ts | 12 +++++ cocos/renderer/gfx/index.js | 2 + cocos/renderer/gfx/webgl/webgl-buffer.ts | 13 +++++ cocos/renderer/gfx/webgl/webgl-device.ts | 47 ++++++++++++++++++ playground/sample.html | 38 +++++++++++++++ tsconfig.json | 62 ++++++++++++++++++++++++ 7 files changed, 203 insertions(+) create mode 100644 cocos/renderer/gfx/gfx-buffer.ts create mode 100644 cocos/renderer/gfx/gfx-device.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-buffer.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-device.ts create mode 100644 playground/sample.html create mode 100644 tsconfig.json diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/renderer/gfx/gfx-buffer.ts new file mode 100644 index 0000000000..8ffb003e32 --- /dev/null +++ b/cocos/renderer/gfx/gfx-buffer.ts @@ -0,0 +1,29 @@ +import { GFXDevice } from './gfx-device'; + +export const enum BufferUsageBit { + NONE = 0, + MAP_READ = 0x1, + MAP_WRITE = 0x2, + TRANSFER_SRC = 0x4, + TRANSFER_DST = 0x8, + INDEX = 0x10, + VERTEX = 0x20, + UNIFORM = 0x40, + STORAGE = 0x80, +}; + +export class GFXBufferInfo { + usage : BufferUsageBit = BufferUsageBit.NONE; + size : number = 0; +}; + +export abstract class GFXBuffer { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(desc : GFXBufferInfo) : boolean; + + protected _device : GFXDevice; +}; diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts new file mode 100644 index 0000000000..684302a999 --- /dev/null +++ b/cocos/renderer/gfx/gfx-device.ts @@ -0,0 +1,12 @@ +import { GFXBuffer } from './gfx-buffer'; + +export class GFXDeviceInfo { +}; + +export abstract class GFXDevice { + + public abstract initialize(info : GFXDeviceInfo) : boolean; + public abstract destroy() : void; + public abstract createBuffer() : GFXBuffer; + public abstract getDeviceName() : string; +}; diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js index 7687de6774..9948665e35 100644 --- a/cocos/renderer/gfx/index.js +++ b/cocos/renderer/gfx/index.js @@ -15,6 +15,7 @@ import TextureCube from './texture-cube'; import RenderBuffer from './render-buffer'; import FrameBuffer from './frame-buffer'; import Device from './device'; +import { WebGLDevice } from '../../../dist/webgl/webgl-device'; let gfx = { // classes @@ -28,6 +29,7 @@ let gfx = { RenderBuffer, FrameBuffer, Device, + WebGLDevice, // functions attrTypeBytes, diff --git a/cocos/renderer/gfx/webgl/webgl-buffer.ts b/cocos/renderer/gfx/webgl/webgl-buffer.ts new file mode 100644 index 0000000000..27f2bd15a3 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-buffer.ts @@ -0,0 +1,13 @@ +import { GFXBufferInfo, GFXBuffer } from '../gfx-buffer'; +import { GFXDevice } from '../gfx-device'; + +export class WebGLBuffer extends GFXBuffer { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(desc : GFXBufferInfo) : boolean{ + return true; + } +}; diff --git a/cocos/renderer/gfx/webgl/webgl-device.ts b/cocos/renderer/gfx/webgl/webgl-device.ts new file mode 100644 index 0000000000..574f1094d7 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-device.ts @@ -0,0 +1,47 @@ +import { GFXDeviceInfo, GFXDevice } from '../gfx-device'; +import { GFXBuffer } from '../gfx-buffer'; +import { WebGLBuffer } from './webgl-buffer'; + +export class WebGLDevice extends GFXDevice { + + constructor(canvasEL : HTMLElement) { + + super(); + + try { + this._webGLRC = (canvasEL).getContext('webgl'); + } catch (err) { + console.error(err); + return; + } + + // No errors are thrown using try catch + // Tested through ios baidu browser 4.14.1 + if (!this._webGLRC) { + console.error('This device does not support WebGL.'); + } + } + + public initialize(info : GFXDeviceInfo) : boolean { + + return true; + } + + public destroy() : void { + + } + + public createBuffer() : GFXBuffer { + return new WebGLBuffer(this); + } + + public getDeviceName() : string { + return "WebGLDevice"; + } + + public get gl(): WebGLRenderingContext | null { + return this._webGLRC; + } + + private _webGLRC : WebGLRenderingContext | null = null; +}; diff --git a/playground/sample.html b/playground/sample.html new file mode 100644 index 0000000000..fc65c8b8a4 --- /dev/null +++ b/playground/sample.html @@ -0,0 +1,38 @@ + + + + + sample + + + + + + + + + + + + + diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000..6e5dea8439 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,62 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + "allowJs": false, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./dist", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + } + //"include" : ["./source"] + //"exclude" : ["js"] +} \ No newline at end of file From 647c2720918d9b13318e8ac011ec14d1d6b2cc58 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 19 Dec 2018 17:36:36 +0800 Subject: [PATCH 002/267] add gfx code --- cocos/renderer/gfx/gfx-binding-set-layout.ts | 44 ++ cocos/renderer/gfx/gfx-buffer.ts | 53 +- cocos/renderer/gfx/gfx-command-allocator.ts | 13 + cocos/renderer/gfx/gfx-command-buffer.ts | 29 + cocos/renderer/gfx/gfx-define.ts | 402 ++++++++++ cocos/renderer/gfx/gfx-device.ts | 13 + cocos/renderer/gfx/gfx-framebuffer.ts | 26 + cocos/renderer/gfx/gfx-input-state.ts | 26 + cocos/renderer/gfx/gfx-pipeline-layout.ts | 28 + cocos/renderer/gfx/gfx-pipeline-state.ts | 223 ++++++ cocos/renderer/gfx/gfx-queue.ts | 28 + cocos/renderer/gfx/gfx-render-pass.ts | 92 +++ cocos/renderer/gfx/gfx-sampler.ts | 72 ++ cocos/renderer/gfx/gfx-shader.ts | 83 +++ cocos/renderer/gfx/gfx-texture-view.ts | 69 ++ cocos/renderer/gfx/gfx-texture.ts | 109 +++ cocos/renderer/gfx/index.js | 4 +- cocos/renderer/gfx/webgl/webgl-buffer.ts | 13 - cocos/renderer/gfx/webgl/webgl-commands.ts | 687 ++++++++++++++++++ cocos/renderer/gfx/webgl/webgl-device.ts | 47 -- cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts | 62 ++ .../gfx/webgl/webgl-gfx-command-allocator.ts | 27 + cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 261 +++++++ .../gfx/webgl/webgl-gfx-framebuffer.ts | 37 + .../gfx/webgl/webgl-gfx-input-state.ts | 22 + cocos/renderer/gfx/webgl/webgl-gfx-queue.ts | 30 + .../gfx/webgl/webgl-gfx-render-pass.ts | 34 + cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts | 30 + cocos/renderer/gfx/webgl/webgl-gfx-shader.ts | 39 + .../gfx/webgl/webgl-gfx-texture-view.ts | 42 ++ cocos/renderer/gfx/webgl/webgl-gfx-texture.ts | 52 ++ cocos/renderer/gfx/webgl/webgl-gpu-objects.ts | 181 +++++ cocos/renderer/gfx/webgl/webgl-state-cache.ts | 20 + playground/sample.html | 2 +- 34 files changed, 2834 insertions(+), 66 deletions(-) create mode 100644 cocos/renderer/gfx/gfx-binding-set-layout.ts create mode 100644 cocos/renderer/gfx/gfx-command-allocator.ts create mode 100644 cocos/renderer/gfx/gfx-command-buffer.ts create mode 100644 cocos/renderer/gfx/gfx-define.ts create mode 100644 cocos/renderer/gfx/gfx-framebuffer.ts create mode 100644 cocos/renderer/gfx/gfx-input-state.ts create mode 100644 cocos/renderer/gfx/gfx-pipeline-layout.ts create mode 100644 cocos/renderer/gfx/gfx-pipeline-state.ts create mode 100644 cocos/renderer/gfx/gfx-queue.ts create mode 100644 cocos/renderer/gfx/gfx-render-pass.ts create mode 100644 cocos/renderer/gfx/gfx-sampler.ts create mode 100644 cocos/renderer/gfx/gfx-shader.ts create mode 100644 cocos/renderer/gfx/gfx-texture-view.ts create mode 100644 cocos/renderer/gfx/gfx-texture.ts delete mode 100644 cocos/renderer/gfx/webgl/webgl-buffer.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-commands.ts delete mode 100644 cocos/renderer/gfx/webgl/webgl-device.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-device.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-queue.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-shader.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-texture.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gpu-objects.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-state-cache.ts diff --git a/cocos/renderer/gfx/gfx-binding-set-layout.ts b/cocos/renderer/gfx/gfx-binding-set-layout.ts new file mode 100644 index 0000000000..03b4d2512d --- /dev/null +++ b/cocos/renderer/gfx/gfx-binding-set-layout.ts @@ -0,0 +1,44 @@ +import { GFXDevice } from './gfx-device'; +import { GFXBuffer } from './gfx-buffer'; +import { GFXTextureView } from './gfx-texture-view'; +import { GFXSampler } from './gfx-sampler'; + +export const enum GFXBindingType { + UNKNOWN, + UNIFORM_BUFFER, + SAMPLER, + TEXTURE_VIEW, + STORAGE_BUFFER, +}; + +export class GFXBinding { + binding : number = 0; + type : GFXBindingType = GFXBindingType.UNKNOWN; + name : string = ""; +}; + +export class GFXBindingSetLayoutInfo { + bindings : GFXBinding[] = []; +}; + +export class GFXBindingUnit { + binding : number = 0; + type : GFXBindingType = GFXBindingType.UNKNOWN; + name : string = ""; + buffer : GFXBuffer | null = null; + texView : GFXTextureView | null = null; + sampler : GFXSampler | null = null; +}; + +export abstract class GFXBindingSetLayout { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXBindingSetLayoutInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _bindingUnits : GFXBindingUnit[] = []; +}; diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/renderer/gfx/gfx-buffer.ts index 8ffb003e32..9f3e2e87da 100644 --- a/cocos/renderer/gfx/gfx-buffer.ts +++ b/cocos/renderer/gfx/gfx-buffer.ts @@ -1,6 +1,6 @@ import { GFXDevice } from './gfx-device'; -export const enum BufferUsageBit { +export const enum GFXBufferUsageBit { NONE = 0, MAP_READ = 0x1, MAP_WRITE = 0x2, @@ -12,9 +12,29 @@ export const enum BufferUsageBit { STORAGE = 0x80, }; +export type GFXBufferUsage = GFXBufferUsageBit; + +export const enum GFXMemoryUsageBit { + NONE = 0, + DEVICE = 0x1, + HOST = 0x2, +}; + +export type GFXMemoryUsage = GFXMemoryUsageBit; + +export const enum GFXBufferAccessBit { + NONE = 0, + READ = 0x1, + WRITE = 0x2, +}; + +export type GFXBufferAccess = GFXBufferAccessBit; + export class GFXBufferInfo { - usage : BufferUsageBit = BufferUsageBit.NONE; + usage : GFXBufferUsage = GFXBufferUsageBit.NONE; + memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; size : number = 0; + stride : number = 1; }; export abstract class GFXBuffer { @@ -23,7 +43,34 @@ export abstract class GFXBuffer { this._device = device; } - public abstract initialize(desc : GFXBufferInfo) : boolean; + public abstract initialize(info : GFXBufferInfo) : boolean; + public abstract destroy() : void; + public abstract update(buffer : ArrayBuffer, offset : number); + + public get usage(): GFXBufferUsage { + return this._usage; + } + + public get memUsage(): GFXMemoryUsage { + return this._memUsage; + } + + public get size(): number { + return this._size; + } + + public get stride(): number { + return this._stride; + } + + public get buffer(): ArrayBuffer | null { + return this._buffer; + } protected _device : GFXDevice; + protected _usage : GFXBufferUsage = GFXBufferUsageBit.NONE; + protected _memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; + protected _size : number = 0; + protected _stride : number = 1; + protected _buffer : ArrayBuffer | null = null; }; diff --git a/cocos/renderer/gfx/gfx-command-allocator.ts b/cocos/renderer/gfx/gfx-command-allocator.ts new file mode 100644 index 0000000000..12a515ead8 --- /dev/null +++ b/cocos/renderer/gfx/gfx-command-allocator.ts @@ -0,0 +1,13 @@ +import { GFXDevice } from './gfx-device'; + +export abstract class GFXCommandAllocator { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize() : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; +} \ No newline at end of file diff --git a/cocos/renderer/gfx/gfx-command-buffer.ts b/cocos/renderer/gfx/gfx-command-buffer.ts new file mode 100644 index 0000000000..db15385888 --- /dev/null +++ b/cocos/renderer/gfx/gfx-command-buffer.ts @@ -0,0 +1,29 @@ +import { GFXDevice } from './gfx-device'; +import { GFXCommandAllocator } from './gfx-command-allocator'; + +export const enum GFXCommandBufferType { + PRIMARY, + SECONDARY, +}; + +export class GFXCommandBufferInfo { + allocator : GFXCommandAllocator | null = null; + type : GFXCommandBufferType = GFXCommandBufferType.PRIMARY; +}; + +export abstract class GFXCommandBuffer { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXCommandBufferInfo) : boolean; + public abstract destroy() : void; + + public get type(): number { + return this._type; + } + + protected _device : GFXDevice; + protected _type : GFXCommandBufferType = GFXCommandBufferType.PRIMARY; +}; diff --git a/cocos/renderer/gfx/gfx-define.ts b/cocos/renderer/gfx/gfx-define.ts new file mode 100644 index 0000000000..76d20ab9f5 --- /dev/null +++ b/cocos/renderer/gfx/gfx-define.ts @@ -0,0 +1,402 @@ +// Extensions +export const enum WebGLEXT { + COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, + COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1, + COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2, + COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3, + + COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C, + COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D, + COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E, + COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F, + + COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00, + COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01, + COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02, + COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03, + + COMPRESSED_RGB_ETC1_WEBGL = 0x8D64, +}; + +export const GFX_MAX_VERTEX_ATTRIBUTES : number = 8; +export const GFX_MAX_TEXTURE_UNITS : number = 16; +export const GFX_MAX_ATTACHMENTS : number = 4; + +export enum GFXType { + UNKNOWN, + BOOL, + BOOL2, + BOOL3, + BOOL4, + INT, + INT2, + INT3, + INT4, + UINT, + UINT2, + UINT3, + UINT4, + FLOAT, + FLOAT2, + FLOAT3, + FLOAT4, + MAT2, + MAT2X3, + MAT2X4, + MAT3X2, + MAT3, + MAT3X4, + MAT4X2, + MAT4X3, + MAT4, + SAMPLER1D, + SAMPLER1D_ARRAY, + SAMPLER2D, + SAMPLER2D_ARRAY, + SAMPLER3D, + SAMPLER_CUBE, + COUNT, +}; + +export const enum GFXFormat { + + UNKNOWN, + + A8, + L8, + LA8, + + R8, + R8SN, + R8UI, + R8I, + R16F, + R16UI, + R16I, + R32F, + R32UI, + R32I, + + RG8, + RG8SN, + RG8UI, + RG8I, + RG16F, + RG16UI, + RG16I, + RG32F, + RG32UI, + RG32I, + + RGB8, + SRGB8, + RGB8SN, + RGB8UI, + RGB8I, + RGB16F, + RGB16UI, + RGB16I, + RGB32F, + RGB32UI, + RGB32I, + + RGBA8, + SRGB8_A8, + RGBA8SN, + RGBA8UI, + RGBA8I, + RGBA16F, + RGBA16UI, + RGBA16I, + RGBA32F, + RGBA32UI, + RGBA32I, + + // Special Format + R5G6B5, + R11G11B10F, + RGB5A1, + RGBA4, + RGB10A2, + RGB10A2UI, + RGB9E5, + + // Depth-Stencil Format + D16, + D24, + D24S8, + D32F, + D32F_S8, + + // Compressed Format + + // Block Compression Format, DDS (DirectDraw Surface) + // DXT1: 3 channels (5:6:5), 1/8 origianl size, with 0 or 1 bit of alpha + BC1, + BC1_ALPHA, + BC1_SRGB, + BC1_SRGB_ALPHA, + // DXT3: 4 channels (5:6:5), 1/4 origianl size, with 4 bits of alpha + BC2, + BC2_SRGB, + // DXT5: 4 channels (5:6:5), 1/4 origianl size, with 8 bits of alpha + BC3, + BC3_SRGB, + // 1 channel (8), 1/4 origianl size + BC4, + BC4_SNORM, + // 2 channels (8:8), 1/2 origianl size + BC5, + BC5_SNORM, + // 3 channels (16:16:16), half-floating point, 1/6 origianl size + // UF16: unsigned float, 5 exponent bits + 11 mantissa bits + // SF16: signed float, 1 signed bit + 5 exponent bits + 10 mantissa bits + BC6H_UF16, + BC6H_SF16, + // 4 channels (4~7 bits per channel) with 0 to 8 bits of alpha, 1/3 original size + BC7, + BC7_SRGB, + + // Ericsson Texture Compression Format + ETC_RGB8, + ETC2_RGB8, + ETC2_SRGB8, + ETC2_RGB8_A1, + ETC2_SRGB8_A1, + ETC2_RGBA8, + ETC2_SRGB8_A8, + EAC_R11, + EAC_R11SN, + EAC_RG11, + EAC_RG11SN, + + // PVRTC (PowerVR) + PVRTC_RGB2, + PVRTC_RGBA2, + PVRTC_RGB4, + PVRTC_RGBA4, + PVRTC2_2BPP, + PVRTC2_4BPP, +}; + +export class GFXFormatInfo { + readonly name : string = "UNKNOWN"; + readonly size : number = 0; + readonly isFloating : boolean = false; + readonly hasAlpha : boolean = false; + readonly hasDepth : boolean = false; + readonly hasStencil : boolean = false; + readonly isCompressed : boolean = false; +}; + +export const GFXFormatInfos : GFXFormatInfo[] = [ + + { name : "UNKNOWN", size : 0, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "A8", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "L8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "LA8", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "R8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8SN", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8UI", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8I", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R16F", size : 2, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R16UI", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R16I", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R32F", size : 4, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R32UI", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R32I", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "RG8", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8SN", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8UI", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8I", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG16F", size : 4, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG16UI", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG16I", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG32F", size : 8, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG32UI", size : 8, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG32I", size : 8, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "RGB8", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "SRGB8", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8SN", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8UI", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8I", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB16F", size : 6, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB16UI", size : 6, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB16I", size : 6, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB32F", size : 12, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB32UI", size : 12, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB32I", size : 12, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "RGBA8", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "SRGB8_A8", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8SN", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8UI", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8I", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA16F", size : 8, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA16UI", size : 8, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA16I", size : 8, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA32F", size : 16, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA32UI", size : 16, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA32I", size : 16, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "R5G6B5", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R11G11B10F", size : 4, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB5A1", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA4", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB10A2", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB10A2UI", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB9E5", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + + { name : "D16", size : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D24", size : 3, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D24S8", size : 4, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, + { name : "D32F", size : 4, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D32FS8", size : 5, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, + + { name : "BC1", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1_ALPHA", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1_SRGB", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1_SRGB_ALPHA", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC2", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC2_SRGB", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC3", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC3_SRGB", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC4", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC4_SNORM", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC5", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC5_SNORM", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC6H_UF16", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC6H_SF16", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC7", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC7_SRGB", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + + { name : "ETC_RGB8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_RGB8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_SRGB8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_RGB8_A1", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_SRGB8_A1", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_RGBA8", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_SRGB8_A8", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_R11", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_R11SN", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_RG11", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_RG11SN", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + + { name : "PVRTC_RGB2", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGBA2", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGB4", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGBA4", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC2_2BPP", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC2_4BPP", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, +]; + +export function GFXFormatSize(format : GFXFormat, width : number, height : number, depth : number) : number { + + if(!GFXFormatInfos[format].isCompressed) { + return (width * height * depth * GFXFormatInfos[format].size); + } else { + switch(format) { + case GFXFormat.BC1: + case GFXFormat.BC1_ALPHA: + case GFXFormat.BC1_SRGB: + case GFXFormat.BC1_SRGB_ALPHA: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.BC2: + case GFXFormat.BC2_SRGB: + case GFXFormat.BC3: + case GFXFormat.BC3_SRGB: + case GFXFormat.BC4: + case GFXFormat.BC4_SNORM: + case GFXFormat.BC6H_SF16: + case GFXFormat.BC6H_UF16: + case GFXFormat.BC7: + case GFXFormat.BC7_SRGB: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case GFXFormat.BC5: + case GFXFormat.BC5_SNORM: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; + + case GFXFormat.ETC_RGB8: + case GFXFormat.ETC2_RGB8: + case GFXFormat.ETC2_SRGB8: + case GFXFormat.ETC2_RGB8_A1: + case GFXFormat.ETC2_SRGB8_A1: + case GFXFormat.EAC_R11: + case GFXFormat.EAC_R11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.EAC_RG11: + case GFXFormat.EAC_RG11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + + case GFXFormat.PVRTC_RGB2: + case GFXFormat.PVRTC_RGBA2: + case GFXFormat.PVRTC2_2BPP: + return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 4) * depth; + case GFXFormat.PVRTC_RGB4: + case GFXFormat.PVRTC_RGBA4: + case GFXFormat.PVRTC2_4BPP: + return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 2) * depth; + + default: { + return 0; + } + } + } +} + +export function GFXFormatSurfaceSize(format : GFXFormat, width : number, height : number, depth : number, mips : number) : number { + + let size = 0; + + for(let i = 0; i < mips; ++i) { + size += GFXFormatSize(format, width, height, depth); + width = Math.max(width >> 1, 1); + height = Math.max(height >> 1, 1); + depth = Math.max(depth >> 1, 1); + } + + return size; +} + +export function GFXGetTypeSize(type : GFXType) : number { + switch(type) { + case GFXType.BOOL: + case GFXType.INT: + case GFXType.UINT: + case GFXType.FLOAT: return 4; + case GFXType.BOOL2: + case GFXType.INT2: + case GFXType.UINT2: + case GFXType.FLOAT2: return 8; + case GFXType.BOOL3: + case GFXType.INT3: + case GFXType.UINT3: + case GFXType.FLOAT3: return 12; + case GFXType.BOOL4: + case GFXType.INT4: + case GFXType.UINT4: + case GFXType.FLOAT4: + case GFXType.MAT2: return 16; + case GFXType.MAT2X3: return 24; + case GFXType.MAT2X4: return 32; + case GFXType.MAT3X2: return 24; + case GFXType.MAT3: return 36; + case GFXType.MAT3X4: return 48; + case GFXType.MAT4X2: return 32; + case GFXType.MAT4X2: return 32; + case GFXType.MAT4: return 64; + case GFXType.SAMPLER1D: + case GFXType.SAMPLER1D_ARRAY: + case GFXType.SAMPLER2D: + case GFXType.SAMPLER2D_ARRAY: + case GFXType.SAMPLER3D: + case GFXType.SAMPLER_CUBE: return 4; + default: { + return 0; + } + } +} diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index 684302a999..97761026c2 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -1,4 +1,5 @@ import { GFXBuffer } from './gfx-buffer'; +import { GFXQueue } from './gfx-queue'; export class GFXDeviceInfo { }; @@ -9,4 +10,16 @@ export abstract class GFXDevice { public abstract destroy() : void; public abstract createBuffer() : GFXBuffer; public abstract getDeviceName() : string; + + public get queue(): GFXQueue { + return this._queue; + } + + public get maxVertexAttributes(): number { + return this._maxVertexAttributes; + } + + protected _queue : GFXQueue | null = null; + + protected _maxVertexAttributes : number = 0; }; diff --git a/cocos/renderer/gfx/gfx-framebuffer.ts b/cocos/renderer/gfx/gfx-framebuffer.ts new file mode 100644 index 0000000000..71bee525e8 --- /dev/null +++ b/cocos/renderer/gfx/gfx-framebuffer.ts @@ -0,0 +1,26 @@ +import { GFXDevice } from './gfx-device'; +import { GFXTextureView } from './gfx-texture-view'; +import { GFXRenderPass } from './gfx-render-pass'; + +export class GFXFramebufferInfo +{ + renderPass : GFXRenderPass | null = null; + colorViews : GFXTextureView[] = []; + depthStencilView : GFXTextureView | null = null; + isOffscreen : boolean = false; +}; + +export abstract class GFXFramebuffer { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXFramebufferInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _colorViews : GFXTextureView[] = []; + protected _depthStencilView : GFXTextureView | null = null; + protected _isOffscreen : boolean = false; +}; diff --git a/cocos/renderer/gfx/gfx-input-state.ts b/cocos/renderer/gfx/gfx-input-state.ts new file mode 100644 index 0000000000..2a682f6f75 --- /dev/null +++ b/cocos/renderer/gfx/gfx-input-state.ts @@ -0,0 +1,26 @@ +import { GFXDevice } from './gfx-device'; +import { GFX_MAX_VERTEX_ATTRIBUTES, GFXFormat } from './gfx-define'; + +export class GFXInputAttribute { + name : string = ""; + format : GFXFormat = GFXFormat.UNKNOWN; + //offset : number = 0; + isInstanced : boolean = false; +}; + +export class GFXInputStateInfo { + attributes: GFXInputAttribute[] = []; +}; + +export abstract class GFXInputState { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXInputStateInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _attributes: GFXInputAttribute[] = []; +}; diff --git a/cocos/renderer/gfx/gfx-pipeline-layout.ts b/cocos/renderer/gfx/gfx-pipeline-layout.ts new file mode 100644 index 0000000000..0f3cbb944a --- /dev/null +++ b/cocos/renderer/gfx/gfx-pipeline-layout.ts @@ -0,0 +1,28 @@ +import { GFXDevice } from './gfx-device'; +import { GFXRenderPass } from './gfx-render-pass'; +import { GFXBindingSetLayout } from './gfx-binding-set-layout'; +import { GFXShaderType } from './gfx-shader'; + +export class GFXPushConstantRange { + shaderType : GFXShaderType = GFXShaderType.VERTEX; + offset : number = 0; + count : number = 0; +}; + +export class GFXPipelineLayoutInfo { + pushConstantsRanges : GFXPushConstantRange[] = []; + layouts : GFXBindingSetLayout[] = []; +}; + +export abstract class GFXPipelineLayout { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXPipelineLayoutInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _renderPass: GFXRenderPass | null = null; +}; diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/renderer/gfx/gfx-pipeline-state.ts new file mode 100644 index 0000000000..c02ddc9f99 --- /dev/null +++ b/cocos/renderer/gfx/gfx-pipeline-state.ts @@ -0,0 +1,223 @@ +import { GFXDevice } from './gfx-device'; +import { GFX_MAX_VERTEX_ATTRIBUTES, GFXFormat } from './gfx-define'; +import { GFXShader } from './gfx-shader'; +import { GFXRenderPass } from './gfx-render-pass'; + +export const enum GFXPrimitiveMode { + POINT_LIST, + LINE_LIST, + LINE_STRIP, + LINE_LOOP, + TRIANGLE_LIST, + TRIANGLE_STRIP, + TRIANGLE_FAN, + LINE_LIST_ADJACENCY, + LINE_STRIP_ADJACENCY, + TRIANGLE_LIST_ADJACENCY, + TRIANGLE_STRIP_ADJACENCY, + TRIANGLE_PATCH_ADJACENCY, + QUAD_PATCH_LIST, + ISO_LINE_LIST, +}; + +export const enum GFXPolygonMode { + FILL, + LINE, + POINT, +}; + +export const enum GFXShadeModel { + GOURAND, + FLAT, +}; + +export const enum GFXCullMode { + NONE, + FRONT, + BACK, +}; + +export const enum GFXComparisonFunc { + NEVER, + LESS, + EQUAL, + LESS_EQUAL, + GREATER, + NOT_EQUAL, + GREATER_EQUAL, + ALWAYS, +}; + +export const enum GFXStencilOp { + KEEP, + ZERO, + REPLACE, + INCR, + DECR, + INVERT, + INCR_WRAP, + DECR_WRAP, +}; + +export const enum GFXBlendOp { + ADD, + SUB, + REV_SUB, + MIN, + MAX, +}; + +export const enum GFXBlendFactor { + ZERO, + ONE, + SRC_ALPHA, + DST_ALPHA, + ONE_MINUS_SRC_ALPHA, + ONE_MINUS_DST_ALPHA, + SRC_COLOR, + DST_COLOR, + ONE_MINUS_SRC_COLOR, + ONE_MINUS_DST_COLOR, + SRC_ALPHA_SATURATE, + CONSTANT_COLOR, + ONE_MINUS_CONSTANT_COLOR, + CONSTANT_ALPHA, + ONE_MINUS_CONSTANT_ALPHA, +}; + +export const enum GFXColorMask { + NONE = 0x0, + R = 0x1, + G = 0x2, + B = 0x4, + A = 0x8, + ALL = R | G | B | A, +}; + +export class GFXRasterizerState { + name : string = ""; + isDiscard : boolean = false; + polygonMode : GFXPolygonMode = GFXPolygonMode.FILL; + shadeModel : GFXShadeModel = GFXShadeModel.GOURAND; + cullMode : GFXCullMode = GFXCullMode.BACK; + isFrontFaceCCW : boolean = true; + depthBias : number = 0.0; + depthBiasFactor : number = 0.0; + isDepthClip : boolean = true; + isMultisample : boolean = false; + lineWidth : number = 1.0; + + public compare(state : GFXRasterizerState) : boolean { + return (this.isDiscard === state.isDiscard) && + (this.polygonMode === state.polygonMode) && + (this.shadeModel === state.shadeModel) && + (this.cullMode === state.cullMode) && + (this.isFrontFaceCCW === state.isFrontFaceCCW) && + (this.depthBias === state.depthBias) && + (this.depthBiasFactor === state.depthBiasFactor) && + (this.isDepthClip === state.isDepthClip) && + (this.isMultisample === state.isMultisample) && + (this.lineWidth === state.lineWidth); + } +}; + +export class GFXDepthStencilState { + name : string = ""; + isDepthTest : boolean = true; + isWriteDepth : boolean = true; + depthFunc : GFXComparisonFunc = GFXComparisonFunc.LESS; + isFrontStencilTest : boolean = false; + frontStencilFunc : GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + frontStencilReadMask : number = 0xffffffff; + frontStencilWriteMask : number = 0xffffffff; + frontStencilFailOp : GFXStencilOp = GFXStencilOp.KEEP; + frontStencilDepthFailOp : GFXStencilOp = GFXStencilOp.KEEP; + frontStencilPassFailOp : GFXStencilOp = GFXStencilOp.KEEP; + frontStencilRef : number = 1; + isBackStencilTest : boolean = false; + backStencilFunc : GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + backStencilReadMask : number = 0xffffffff; + backStencilWriteMask : number = 0xffffffff; + backStencilFailOp : GFXStencilOp = GFXStencilOp.KEEP; + backStencilDepthFailOp : GFXStencilOp = GFXStencilOp.KEEP; + backStencilPassFailOp : GFXStencilOp = GFXStencilOp.KEEP; + backStencilRef : number = 1; + + public compare(state : GFXDepthStencilState) : boolean { + return (this.isDepthTest === state.isDepthTest) && + (this.isWriteDepth === state.isWriteDepth) && + (this.depthFunc === state.depthFunc) && + (this.isFrontStencilTest === state.isFrontStencilTest) && + (this.frontStencilFunc === state.frontStencilFunc) && + (this.frontStencilReadMask === state.frontStencilReadMask) && + (this.frontStencilWriteMask === state.frontStencilWriteMask) && + (this.frontStencilFailOp === state.frontStencilFailOp) && + (this.frontStencilDepthFailOp === state.frontStencilDepthFailOp) && + (this.frontStencilPassFailOp === state.frontStencilPassFailOp) && + (this.frontStencilRef === state.frontStencilRef) && + (this.isBackStencilTest === state.isBackStencilTest) && + (this.backStencilFunc === state.backStencilFunc) && + (this.backStencilReadMask === state.backStencilReadMask) && + (this.backStencilWriteMask === state.backStencilWriteMask) && + (this.backStencilFailOp === state.backStencilFailOp) && + (this.backStencilDepthFailOp === state.backStencilDepthFailOp) && + (this.backStencilPassFailOp === state.backStencilPassFailOp) && + (this.backStencilRef === state.backStencilRef); + } +}; + +export class GFXBlendTarget { + isBlend : boolean = false; + srcBlend : GFXBlendFactor = GFXBlendFactor.ONE; + dstBlend : GFXBlendFactor = GFXBlendFactor.ZERO; + blendOp : GFXBlendOp = GFXBlendOp.ADD; + srcAlphaBlend : GFXBlendFactor = GFXBlendFactor.ONE; + dstAlphaBlend : GFXBlendFactor = GFXBlendFactor.ZERO; + alphBlendOp : GFXBlendOp = GFXBlendOp.ADD; + colorWriteMask : GFXColorMask = GFXColorMask.ALL; + + public compare(state : GFXBlendTarget) : boolean { + return (this.isBlend === state.isBlend) && + (this.srcBlend === state.srcBlend) && + (this.dstBlend === state.dstBlend) && + (this.blendOp === state.blendOp) && + (this.srcAlphaBlend === state.srcAlphaBlend) && + (this.dstAlphaBlend === state.dstAlphaBlend) && + (this.alphBlendOp === state.alphBlendOp) && + (this.colorWriteMask === state.colorWriteMask); + } +}; + +export class GFXBlendState { + name : string = ""; + isA2C : boolean = false; + isIndepend : boolean = false; + factor : number[] = [0, 0, 0, 0]; + targets : GFXBlendTarget[] = [new GFXBlendTarget]; +} + +export class GFXPipelineStateInfo { + primitiveMode : GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + shader : GFXShader | null = null; + rs : GFXRasterizerState | null = null; + dss : GFXDepthStencilState | null = null; + bs : GFXBlendState = new GFXBlendState; + renderPass : GFXRenderPass | null = null; +}; + +export abstract class GFXPipelineState { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXPipelineStateInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _shader : GFXShader | null = null; + protected _rs : GFXRasterizerState | null = null; + protected _dss : GFXDepthStencilState | null = null; + protected _bs : GFXBlendState | null = null; + protected _renderPass: GFXRenderPass | null = null; +}; diff --git a/cocos/renderer/gfx/gfx-queue.ts b/cocos/renderer/gfx/gfx-queue.ts new file mode 100644 index 0000000000..597767b5ca --- /dev/null +++ b/cocos/renderer/gfx/gfx-queue.ts @@ -0,0 +1,28 @@ +import { GFXDevice } from './gfx-device'; + +export const enum GFXQueueType { + GRAPHICS, + COMPUTE, + TRANSFER, +}; + +export class GFXQueueInfo { + type : GFXQueueType = GFXQueueType.GRAPHICS; +}; + +export abstract class GFXQueue { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXQueueInfo) : boolean; + public abstract destroy(); + + public get type(): number { + return this._type; + } + + protected _device : GFXDevice; + protected _type : GFXQueueType = GFXQueueType.GRAPHICS; +}; diff --git a/cocos/renderer/gfx/gfx-render-pass.ts b/cocos/renderer/gfx/gfx-render-pass.ts new file mode 100644 index 0000000000..03634718e0 --- /dev/null +++ b/cocos/renderer/gfx/gfx-render-pass.ts @@ -0,0 +1,92 @@ +import { GFXFormat, GFXFormatInfo } from './gfx-define'; +import { GFXDevice } from './gfx-device'; + +// Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. +export const enum GFXLoadOp +{ + LOAD, // Load the contents from the fbo from previous + CLEAR, // Clear the fbo + DISCARD, // Ignore writing to the fbo and keep old data +}; + +// Enumerates all possible values of operations to be performed when Storing to a Framebuffer Object. +export const enum GFXStoreOp +{ + STORE, // Write the source to the destination + DISCARD, // Don't write the source to the destination +}; + +export const enum GFXTextureLayout +{ + UNDEFINED, + GENERAL, + COLOR_ATTACHMENT_OPTIMAL, + DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + DEPTH_STENCIL_READONLY_OPTIMAL, + SHADER_READONLY_OPTIMAL, + TRANSFER_SRC_OPTIMAL, + TRANSFER_DST_OPTIMAL, + PREINITIALIZED, + PRESENT_SRC, +}; + +export class ColorAttachmentInfo +{ + format : GFXFormat = GFXFormat.UNKNOWN; + loadOp : GFXLoadOp = GFXLoadOp.CLEAR; + storeOp : GFXStoreOp = GFXStoreOp.STORE; + sampleCount : number = 1; + beginLayout : GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; + endLayout : GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; +}; + +export class DepthStencilAttachmentInfo +{ + format : GFXFormat = GFXFormat.UNKNOWN; + loadOp : GFXLoadOp = GFXLoadOp.CLEAR; + storeOp : GFXStoreOp = GFXStoreOp.STORE; + stencilLoadOp : GFXLoadOp = GFXLoadOp.CLEAR; + stencilStoreOp : GFXStoreOp = GFXStoreOp.STORE; + sampleCount : number = 1; + beginLayout : GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + endLayout : GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; +}; + +export const enum GFXPipelineBindPoint +{ + GRAPHICS, + COMPUTE, + RAY_TRACING, +}; + +export class GFXSubPassInfo +{ + bindPoint : GFXPipelineBindPoint = GFXPipelineBindPoint.GRAPHICS; + inputs : number[] = []; + colors : number[] = []; + resolves : number[] = []; + depthStencil : number = -1; + preserves : number[] = []; +}; + +export class GFXRenderPassInfo +{ + colorInfos : ColorAttachmentInfo[] = []; + depthStencilInfo : DepthStencilAttachmentInfo | null = null; + subPasses : GFXSubPassInfo[] = []; +}; + +export abstract class GFXRenderPass { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXRenderPassInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _colorInfos : ColorAttachmentInfo[] = []; + protected _depthStencilInfo : DepthStencilAttachmentInfo | null = null; + protected _subPasses : GFXSubPassInfo[] = []; +}; diff --git a/cocos/renderer/gfx/gfx-sampler.ts b/cocos/renderer/gfx/gfx-sampler.ts new file mode 100644 index 0000000000..5b44c35ad0 --- /dev/null +++ b/cocos/renderer/gfx/gfx-sampler.ts @@ -0,0 +1,72 @@ +import { GFXDevice } from './gfx-device'; +import { GFXComparisonFunc } from './gfx-pipeline-state'; + +export const enum GFXFilterOp { + NONE, + POINT, + LINEAR, + ANISOTROPIC, +}; + +export const enum GFXAddressMode { + WRAP, + MIRROR, + CLAMP, + BORDER, +}; + +export class GFXSamplerInfo { + name : string = ""; + minFilter : GFXFilterOp = GFXFilterOp.LINEAR; + magFilter : GFXFilterOp = GFXFilterOp.LINEAR; + mipFilter : GFXFilterOp = GFXFilterOp.LINEAR; + addressU : GFXAddressMode = GFXAddressMode.WRAP; + addressV : GFXAddressMode = GFXAddressMode.WRAP; + addressW : GFXAddressMode = GFXAddressMode.WRAP; + maxAnisotropy : number = 16; + cmpFunc : GFXComparisonFunc = GFXComparisonFunc.NEVER; + borderColor : number[] = [0.0, 0.0, 0.0, 0.0]; + minLOD : number = 0; + maxLOD : number = 1000; + mipLODBias : number = 0.0; + + public compare(state : GFXSamplerInfo) : boolean { + return (this.minFilter === state.minFilter) && + (this.magFilter === state.magFilter) && + (this.mipFilter === state.mipFilter) && + (this.addressU === state.addressU) && + (this.addressV === state.addressV) && + (this.addressW === state.addressW) && + (this.maxAnisotropy === state.maxAnisotropy) && + (this.cmpFunc === state.cmpFunc) && + (this.borderColor === state.borderColor) && + (this.minLOD === state.minLOD) && + (this.maxLOD === state.maxLOD) && + (this.mipLODBias === state.mipLODBias); + } +}; + +export abstract class GFXSampler { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXSamplerInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _name : string = ""; + protected _minFilter : GFXFilterOp = GFXFilterOp.LINEAR; + protected _magFilter : GFXFilterOp = GFXFilterOp.LINEAR; + protected _mipFilter : GFXFilterOp = GFXFilterOp.LINEAR; + protected _addressU : GFXAddressMode = GFXAddressMode.WRAP; + protected _addressV : GFXAddressMode = GFXAddressMode.WRAP; + protected _addressW : GFXAddressMode = GFXAddressMode.WRAP; + protected _maxAnisotropy : number = 16; + protected _cmpFunc : GFXComparisonFunc = GFXComparisonFunc.NEVER; + protected _borderColor : number[] = [0.0, 0.0, 0.0, 0.0]; + protected _minLOD : number = 0; + protected _maxLOD : number = 1000; + protected _mipLODBias : number = 0.0; +}; diff --git a/cocos/renderer/gfx/gfx-shader.ts b/cocos/renderer/gfx/gfx-shader.ts new file mode 100644 index 0000000000..8c400e3c8c --- /dev/null +++ b/cocos/renderer/gfx/gfx-shader.ts @@ -0,0 +1,83 @@ +import { GFXDevice } from './gfx-device'; +import { GFXBinding } from './gfx-binding-set-layout'; +import { GFXType } from './gfx-define'; + +export const enum GFXShaderType { + VERTEX, + HULL, + DOMAIN, + GEOMETRY, + FRAGMENT, + COMPUTE, + COUNT, +}; + +export class GFXShaderMacro { + macro : string = ""; + value : string = ""; + + constructor(macro : string, value : string = "") { + this.macro = macro; + this.value = value; + } +}; + +export class GFXShaderVar { + binding : number = -1; + name : string = ""; + type : GFXType = GFXType.UNKNOWN; + stride : number = 0; + count : number = 0; + size : number = 0; + offset : number = 0; +}; + +export class GFXShaderBlock { + binding : number = -1; + name : string = ""; + size : number = 0; + uniforms : GFXShaderVar[] = []; +}; + +export class GFXShaderSampler { + binding : number = -1; + name : string = ""; + type : GFXType = GFXType.UNKNOWN; + units : number[] = []; +}; + +export class GFXShaderStage { + type : GFXShaderType = GFXShaderType.VERTEX; + source : string = ""; + macros : GFXShaderMacro[] = []; + + public define(macro : string, value : string = "") : void { + this.macros.push({ macro, value }); + } +}; + +export class GFXShaderInfo { + name : string = ""; + stages : GFXShaderStage[] = []; + bindings : GFXBinding[] = []; +}; + +export abstract class GFXShader { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXShaderInfo) : boolean; + public abstract destroy() : void; + + protected _device : GFXDevice; + protected _name : string = ""; + protected _stages : GFXShaderStage[] = []; + protected _bindings : GFXBinding[] = []; + + protected _inputs : GFXShaderVar[] = []; + protected _uniforms : GFXShaderVar[] = []; + protected _blocks : GFXShaderBlock[] = []; + protected _samplers : GFXShaderSampler[] = []; +}; diff --git a/cocos/renderer/gfx/gfx-texture-view.ts b/cocos/renderer/gfx/gfx-texture-view.ts new file mode 100644 index 0000000000..5698b30149 --- /dev/null +++ b/cocos/renderer/gfx/gfx-texture-view.ts @@ -0,0 +1,69 @@ +import { GFXFormat, GFXFormatInfo } from './gfx-define'; +import { GFXDevice } from './gfx-device'; +import { GFXTexture } from './gfx-texture'; + +export const enum GFXTextureViewType { + TV1D, + TV2D, + TV3D, + CUBE, + TV1D_ARRAY, + TV2D_ARRAY, +}; + +export class GFXTextureViewInfo { + texture : GFXTexture | null = null; + type : GFXTextureViewType = GFXTextureViewType.TV2D; + format : GFXFormat = GFXFormat.UNKNOWN; + baseLevel : number = 0; + levelCount : number = 1; + baseLayer : number = 0; + layerCount : number = 1; +}; + +export abstract class GFXTextureView { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXTextureViewInfo) : boolean; + public abstract destroy() : void; + + public get texture(): GFXTexture { + return this._texture; + } + + public get type(): GFXTextureViewType { + return this._type; + } + + public get format(): GFXFormat { + return this._format; + } + + public get baseLevel(): number { + return this._baseLevel; + } + + public get levelCount(): number { + return this._levelCount; + } + + public get baseLayer(): number { + return this._baseLayer; + } + + public get layerCount(): number { + return this._layerCount; + } + + protected _device : GFXDevice; + protected _texture : GFXTexture | null = null; + protected _type : GFXTextureViewType = GFXTextureViewType.TV2D; + protected _format : GFXFormat = GFXFormat.UNKNOWN; + protected _baseLevel : number = 0; + protected _levelCount : number = 1; + protected _baseLayer : number = 0; + protected _layerCount : number = 1; +}; diff --git a/cocos/renderer/gfx/gfx-texture.ts b/cocos/renderer/gfx/gfx-texture.ts new file mode 100644 index 0000000000..fc9f0f3795 --- /dev/null +++ b/cocos/renderer/gfx/gfx-texture.ts @@ -0,0 +1,109 @@ +import { GFXFormat, GFXFormatInfo } from './gfx-define'; +import { GFXDevice } from './gfx-device'; + +export const enum GFXTextureType { + TEX1D, + TEX2D, + TEX3D, +}; + +export const enum GFXTextureUsageBit { + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + SAMPLED = 0x4, + STORAGE = 0x8, + INPUT_ATTACHMENT = 0x10, + OUTPUT_ATTACHMENT = 0x20, + PRESENT = 0x30, +}; + +export type GFXTextureUsage = GFXTextureUsageBit; + +export const enum GFXTextureFlagBit { + NONE = 0, + GEN_MIPMAP = 0x1, + CUBEMAP = 0x2, + BAKUP_BUFFER = 0x4, +}; + +export type GFXTextureFlags = GFXTextureFlagBit; + +export class GFXTextureInfo { + type : GFXTextureType = GFXTextureType.TEX2D; + usage : GFXTextureUsage = GFXTextureUsageBit.NONE; + format : GFXFormat = GFXFormat.UNKNOWN; + width : number = 0; + height : number = 0; + depth : number = 1; + arrayLayer : number = 1; + mipLevel : number = 1; + flags : GFXTextureFlags = GFXTextureFlagBit.NONE; +}; + +export abstract class GFXTexture { + + constructor(device : GFXDevice) { + this._device = device; + } + + public abstract initialize(info : GFXTextureInfo) : boolean; + public abstract destroy() : void; + + public get type(): GFXTextureType { + return this._type; + } + + public get usage(): GFXTextureUsage { + return this._usage; + } + + public get format(): GFXFormat { + return this._format; + } + + public get width(): number { + return this._width; + } + + public get height(): number { + return this._height; + } + + public get depth(): number { + return this._depth; + } + + public get arrayLayer(): number { + return this._arrayLayer; + } + + public get mipLevel(): number { + return this._mipLevel; + } + + public get flags(): GFXTextureFlags { + return this._flags; + } + + public get size(): number { + return this._size; + } + + public get buffer(): ArrayBuffer | null { + return this._buffer; + } + + protected _device : GFXDevice; + protected _type : GFXTextureType = GFXTextureType.TEX2D; + protected _usage : GFXTextureUsage = GFXTextureUsageBit.NONE; + protected _format : GFXFormat = GFXFormat.UNKNOWN; + protected _width : number = 0; + protected _height : number = 0; + protected _depth : number = 1; + protected _arrayLayer : number = 1; + protected _mipLevel : number = 1; + protected _flags : GFXTextureFlags = GFXTextureFlagBit.NONE; + protected _size : number = 0; + protected _buffer : ArrayBuffer | null = null; +}; diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js index 9948665e35..61fcaa8754 100644 --- a/cocos/renderer/gfx/index.js +++ b/cocos/renderer/gfx/index.js @@ -15,7 +15,7 @@ import TextureCube from './texture-cube'; import RenderBuffer from './render-buffer'; import FrameBuffer from './frame-buffer'; import Device from './device'; -import { WebGLDevice } from '../../../dist/webgl/webgl-device'; +import { WebGLGFXDevice } from '../../../dist/webgl/webgl-gfx-device'; let gfx = { // classes @@ -29,7 +29,7 @@ let gfx = { RenderBuffer, FrameBuffer, Device, - WebGLDevice, + WebGLGFXDevice, // functions attrTypeBytes, diff --git a/cocos/renderer/gfx/webgl/webgl-buffer.ts b/cocos/renderer/gfx/webgl/webgl-buffer.ts deleted file mode 100644 index 27f2bd15a3..0000000000 --- a/cocos/renderer/gfx/webgl/webgl-buffer.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { GFXBufferInfo, GFXBuffer } from '../gfx-buffer'; -import { GFXDevice } from '../gfx-device'; - -export class WebGLBuffer extends GFXBuffer { - - constructor(device : GFXDevice) { - super(device); - } - - public initialize(desc : GFXBufferInfo) : boolean{ - return true; - } -}; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts new file mode 100644 index 0000000000..e68ac7ea18 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -0,0 +1,687 @@ +import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputState, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLGPUUniform } from "./webgl-gpu-objects"; +import { WebGLGFXDevice } from "./webgl-gfx-device"; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../gfx-buffer"; +import { GFXTextureViewType } from "../gfx-texture-view"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType } from "../gfx-define"; +import { GFXShaderType } from "../gfx-shader"; + +function GFXFormatToWebGLType(format : GFXFormat) : GLenum { + switch(format) { + case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.R8UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.R8I: return WebGLRenderingContext.INT; + case GFXFormat.R16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.R16UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.R16I: return WebGLRenderingContext.INT; + case GFXFormat.R32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.R32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.R32I: return WebGLRenderingContext.INT; + + case GFXFormat.RG8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RG8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.RG8UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RG8I: return WebGLRenderingContext.INT; + case GFXFormat.RG16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RG16UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RG16I: return WebGLRenderingContext.INT; + case GFXFormat.RG32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RG32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RG32I: return WebGLRenderingContext.INT; + + case GFXFormat.RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGB8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.RGB8UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGB8I: return WebGLRenderingContext.INT; + case GFXFormat.RGB16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGB16UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGB16I: return WebGLRenderingContext.INT; + case GFXFormat.RGB32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGB32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGB32I: return WebGLRenderingContext.INT; + + case GFXFormat.RGBA8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.SRGB8_A8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGBA8SN: return WebGLRenderingContext.BYTE; + case GFXFormat.RGBA8UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGBA8I: return WebGLRenderingContext.INT; + case GFXFormat.RGBA16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGBA16UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGBA16I: return WebGLRenderingContext.INT; + case GFXFormat.RGBA32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGBA32UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGBA32I: return WebGLRenderingContext.INT; + + case GFXFormat.R5G6B5: return WebGLRenderingContext.UNSIGNED_SHORT_5_6_5; + case GFXFormat.R11G11B10F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGB5A1: return WebGLRenderingContext.UNSIGNED_SHORT_5_5_5_1; + case GFXFormat.RGBA4: return WebGLRenderingContext.UNSIGNED_SHORT_4_4_4_4; + case GFXFormat.RGB10A2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGB10A2UI: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.RGB9E5: return WebGLRenderingContext.UNSIGNED_BYTE; + + case GFXFormat.D16: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.D24: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.D24S8: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.D32F: return WebGLRenderingContext.FLOAT; + case GFXFormat.D32F_S8: return WebGLRenderingContext.FLOAT; + + case GFXFormat.BC1: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC1_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC2_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC3: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC3_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC4: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC4_SNORM: return WebGLRenderingContext.BYTE; + case GFXFormat.BC5: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC5_SNORM: return WebGLRenderingContext.BYTE; + case GFXFormat.BC6H_SF16: return WebGLRenderingContext.FLOAT; + case GFXFormat.BC6H_UF16: return WebGLRenderingContext.FLOAT; + case GFXFormat.BC7: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.BC7_SRGB: return WebGLRenderingContext.UNSIGNED_BYTE; + + case GFXFormat.ETC_RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_RGB8_A1: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_SRGB8_A1: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.ETC2_SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.EAC_R11: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.EAC_R11SN: return WebGLRenderingContext.BYTE; + case GFXFormat.EAC_RG11: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.EAC_RG11SN: return WebGLRenderingContext.BYTE; + + case GFXFormat.PVRTC_RGB2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC_RGBA2: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC_RGB4: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC_RGBA4: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC2_2BPP: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.PVRTC2_4BPP: return WebGLRenderingContext.UNSIGNED_BYTE; + + default: { + return WebGLRenderingContext.UNSIGNED_BYTE; + } + } +} + +function GFXFormatToWebGLInternalFormat(format : GFXFormat) : GLenum { + switch(format) { + case GFXFormat.A8: return WebGLRenderingContext.ALPHA; + case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; + case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; + case GFXFormat.RGB8: return WebGLRenderingContext.RGB; + case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB565; + case GFXFormat.RGB5A1: return WebGLRenderingContext.RGB5_A1; + case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA4; + case GFXFormat.D16: return WebGLRenderingContext.DEPTH_COMPONENT16; + case GFXFormat.D24: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; + case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D32F_S8: return WebGLRenderingContext.DEPTH_STENCIL; + + case GFXFormat.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case GFXFormat.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case GFXFormat.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case GFXFormat.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + + case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case GFXFormat.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + + default: { + console.error("Unsupported GFXFormat, convert to WebGL internal format failed."); + return WebGLRenderingContext.RGBA; + } + } +} + +function GFXFormatToWebGLFormat(format : GFXFormat) : GLenum { + switch(format) { + case GFXFormat.A8: return WebGLRenderingContext.ALPHA; + case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; + case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; + case GFXFormat.RGB8: return WebGLRenderingContext.RGB; + case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB; + case GFXFormat.RGB5A1: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA; + case GFXFormat.D16: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D24: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; + case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D32F_S8: return WebGLRenderingContext.DEPTH_STENCIL; + + case GFXFormat.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; + case GFXFormat.BC1_SRGB_ALPHA: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + case GFXFormat.BC2: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT; + case GFXFormat.BC2_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + case GFXFormat.BC3: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT; + case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + + case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + + case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + case GFXFormat.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + case GFXFormat.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + + default: { + console.error("Unsupported GFXFormat, convert to WebGL format failed."); + return WebGLRenderingContext.RGBA; + } + } +} + +function WebGLTypeToGFXType(glType : GLenum) : GFXType { + switch(glType) { + case WebGLRenderingContext.BOOL: return GFXType.BOOL; + case WebGLRenderingContext.BOOL_VEC2: return GFXType.BOOL2; + case WebGLRenderingContext.BOOL_VEC3: return GFXType.BOOL3; + case WebGLRenderingContext.BOOL_VEC4: return GFXType.BOOL4; + case WebGLRenderingContext.INT: return GFXType.INT; + case WebGLRenderingContext.INT_VEC2: return GFXType.INT2; + case WebGLRenderingContext.INT_VEC3: return GFXType.INT3; + case WebGLRenderingContext.INT_VEC4: return GFXType.INT4; + case WebGLRenderingContext.UNSIGNED_INT: return GFXType.UINT; + case WebGLRenderingContext.FLOAT: return GFXType.FLOAT; + case WebGLRenderingContext.FLOAT_VEC2: return GFXType.FLOAT2; + case WebGLRenderingContext.FLOAT_VEC3: return GFXType.FLOAT3; + case WebGLRenderingContext.FLOAT_VEC4: return GFXType.FLOAT4; + case WebGLRenderingContext.FLOAT_MAT2: return GFXType.MAT2; + case WebGLRenderingContext.FLOAT_MAT3: return GFXType.MAT3; + case WebGLRenderingContext.FLOAT_MAT4: return GFXType.MAT4; + case WebGLRenderingContext.SAMPLER_2D: return GFXType.SAMPLER2D; + case WebGLRenderingContext.SAMPLER_CUBE: return GFXType.SAMPLER_CUBE; + default: { + console.error("Unsupported GLType, convert to GFXType failed."); + return GFXType.UNKNOWN; + } + } +} + +function WebGLGetTypeSize(glType : GLenum) : GFXType { + switch(glType) { + case WebGLRenderingContext.BOOL: return 4; + case WebGLRenderingContext.BOOL_VEC2: return 8; + case WebGLRenderingContext.BOOL_VEC3: return 12; + case WebGLRenderingContext.BOOL_VEC4: return 16; + case WebGLRenderingContext.INT: return 4; + case WebGLRenderingContext.INT_VEC2: return 8; + case WebGLRenderingContext.INT_VEC3: return 12; + case WebGLRenderingContext.INT_VEC4: return 16; + case WebGLRenderingContext.UNSIGNED_INT: return 4; + case WebGLRenderingContext.FLOAT: return 4; + case WebGLRenderingContext.FLOAT_VEC2: return 8; + case WebGLRenderingContext.FLOAT_VEC3: return 12; + case WebGLRenderingContext.FLOAT_VEC4: return 16; + case WebGLRenderingContext.FLOAT_MAT2: return 16; + case WebGLRenderingContext.FLOAT_MAT3: return 36; + case WebGLRenderingContext.FLOAT_MAT4: return 64; + case WebGLRenderingContext.SAMPLER_2D: return 4; + case WebGLRenderingContext.SAMPLER_CUBE: return 4; + default: { + console.error("Unsupported GLType, get type failed."); + return 0; + } + } +} + +export const enum WebGLCmdType { + UNKNOWN, + CREATE_BUFFER, + DESTROY_BUFFER, +}; + +export class WebGLCmd { + type : WebGLCmdType = WebGLCmdType.UNKNOWN; + obj : any; + isFree : boolean = false; +}; + +export function WebGLCmdFuncCreateBuffer(device : WebGLGFXDevice, gpuBuffer : WebGLGPUBuffer) { + + let gl : WebGLRenderingContext = device.gl; + + if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { + + gpuBuffer.glTarget = WebGLRenderingContext.ARRAY_BUFFER; + let glBuffer = gl.createBuffer(); + if (glBuffer) { + gpuBuffer.glBuffer = glBuffer; + + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + } + + let glUsage : GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); + device.stateCache.glArrayBuffer = null; + } + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { + + gpuBuffer.glTarget = WebGLRenderingContext.ELEMENT_ARRAY_BUFFER; + let glBuffer = gl.createBuffer(); + if (glBuffer) { + gpuBuffer.glBuffer = glBuffer; + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + let glUsage : GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); + device.stateCache.glElementArrayBuffer = null; + } + } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { + console.error("WebGL 1.0 doesn't support uniform buffer."); + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else if (gpuBuffer.usage === GFXBufferUsageBit.TRANSFER_DST) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else if (gpuBuffer.usage === GFXBufferUsageBit.TRANSFER_SRC) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else { + console.error("Unsupported GFXBufferType, create buffer failed."); + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } +} + +export function WebGLCmdFuncDestroyBuffer(device : WebGLGFXDevice, gpuBuffer : WebGLGPUBuffer) { + if(gpuBuffer.glBuffer > 0) { + device.gl.deleteBuffer(gpuBuffer.glBuffer); + gpuBuffer.glBuffer = 0; + } +} + +export function WebGLCmdFuncUpdateBuffer(device : WebGLGFXDevice, gpuBuffer : WebGLGPUBuffer, offset : number, data : ArrayBuffer) { + + let gl : WebGLRenderingContext = device.gl; + + switch (gpuBuffer.glTarget) { + case WebGLRenderingContext.ARRAY_BUFFER : { + + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + } + + gl.bufferSubData(WebGLRenderingContext.ARRAY_BUFFER, offset, data); + + break; + } + case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER : { + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + gl.bufferSubData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, offset, data); + + break; + } + default : { + console.error("Unsupported GFXBufferType, update buffer failed."); + } + } +} + +export function WebGLCmdFuncCreateInputState(device : WebGLGFXDevice, gpuInputState : WebGLGPUInputState) { +} + +export function WebGLCmdFuncDestroyInputState(device : WebGLGFXDevice, gpuInputState : WebGLGPUInputState) { + /*if(gpuInputState.glVAO > 0) { + gpuInputState.glVAO = 0; + }*/ +} + +export function WebGLCmdFuncCreateTexture(device : WebGLGFXDevice, gpuTexture : WebGLGPUTexture) { + + let gl : WebGLRenderingContext = device.gl; + + gpuTexture.glInternelFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format); + gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format); + gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format); + + switch (gpuTexture.viewType) { + case GFXTextureViewType.TV2D : { + + gpuTexture.viewType = GFXTextureViewType.TV2D; + gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; + + let glTexture = gl.createTexture(); + if(glTexture) { + gpuTexture.glTexture = glTexture; + + if (device.stateCache.glTex2DUnits[device.stateCache.texUnit] !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + device.stateCache.glTex2DUnits[device.stateCache.texUnit] = gpuTexture.glTexture; + } + + let w = gpuTexture.width; + let h = gpuTexture.height; + + if (!GFXFormatInfos[gpuTexture.format].isCompressed) { + for(let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } else { + let view : ArrayBufferView = { buffer : new ArrayBuffer(0), byteLength : 0, byteOffset : 0 }; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } + + break; + } + case GFXTextureViewType.CUBE : { + + gpuTexture.viewType = GFXTextureViewType.CUBE; + gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_CUBE_MAP; + + let glTexture = gl.createTexture(); + if (glTexture) { + gpuTexture.glTexture = glTexture; + + if (device.stateCache.glTexCubeUnits[device.stateCache.texUnit] !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + device.stateCache.glTexCubeUnits[device.stateCache.texUnit] = gpuTexture.glTexture; + } + + if (!GFXFormatInfos[gpuTexture.format].isCompressed) { + for (let f = 0; f < 6; ++f) { + let w = gpuTexture.width; + let h = gpuTexture.height; + for (let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.texImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } else { + let view : ArrayBufferView = { buffer : new ArrayBuffer(0), byteLength : 0, byteOffset : 0 }; + + for (let f = 0; f < 6; ++f) { + let w = gpuTexture.width; + let h = gpuTexture.height; + for(let i = 0; i < gpuTexture.mipLevel; ++i) { + gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, view); + w = Math.max(1, w >> 1); + h = Math.max(1, h >> 1); + } + } + } + } + + break; + } + default : { + console.error("Unsupported GFXTextureType, create texture failed."); + gpuTexture.viewType = GFXTextureViewType.TV2D; + gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; + } + } +} + +export function WebGLCmdFuncDestroyTexture(device : WebGLGFXDevice, gpuTexture : WebGLGPUTexture) { + if (gpuTexture.glTexture > 0) { + device.gl.deleteTexture(gpuTexture.glTexture); + gpuTexture.glTexture = 0; + } +} + +export function WebGLCmdFuncCreateFramebuffer(device : WebGLGFXDevice, gpuFramebuffer : WebGLGPUFramebuffer) { + + if(!gpuFramebuffer.isOffscreen) { + + let gl : WebGLRenderingContext = device.gl; + + let glFramebuffer = gl.createFramebuffer(); + if (glFramebuffer) { + gpuFramebuffer.glFramebuffer = glFramebuffer; + + if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); + device.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer; + } + + for (let i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) { + + let gpuColorView = gpuFramebuffer.gpuColorViews[i]; + if (gpuColorView) { + gl.framebufferTexture2D( + WebGLRenderingContext.FRAMEBUFFER, + WebGLRenderingContext.COLOR_ATTACHMENT0 + i, + gpuColorView.gpuTexture.glTarget, + gpuColorView.gpuTexture.glTexture, + gpuColorView.baseLevel); + } + } + + if(gpuFramebuffer.gpuDepthStencilView) { + + let glAttachment = GFXFormatInfos[gpuFramebuffer.gpuDepthStencilView.format].hasStencil? + WebGLRenderingContext.DEPTH_STENCIL_ATTACHMENT : WebGLRenderingContext.DEPTH_ATTACHMENT; + + gl.framebufferTexture2D( + WebGLRenderingContext.FRAMEBUFFER, + glAttachment, + gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTarget, + gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTexture, + gpuFramebuffer.gpuDepthStencilView.baseLevel); + } + } + } +} + +export function WebGLCmdFuncDestroyFramebuffer(device : WebGLGFXDevice, gpuFramebuffer : WebGLGPUFramebuffer) { + if (gpuFramebuffer.glFramebuffer > 0) { + device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer); + gpuFramebuffer.glFramebuffer = 0; + } +} + +export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : WebGLGPUShader) { + let gl : WebGLRenderingContext = device.gl; + + for (let i = 0; i < gpuShader.gpuStages.length; ++i) { + let gpuStage = gpuShader.gpuStages[i]; + + let glShaderType : GLenum = 0; + let shaderTypeStr = ""; + + switch (gpuStage.type) { + case GFXShaderType.VERTEX: { + shaderTypeStr = "VertexShader"; + glShaderType = WebGLRenderingContext.VERTEX_SHADER; + break; + } + case GFXShaderType.FRAGMENT: { + shaderTypeStr = "FragmentShader"; + glShaderType = WebGLRenderingContext.FRAGMENT_SHADER; + break; + } + default: { + console.error("Unsupported GFXShaderType."); + return ; + } + } + + let glShader = gl.createShader(glShaderType); + if (glShader) { + gpuStage.glShader = glShader; + gl.shaderSource(gpuStage.glShader, gpuStage.source); + gl.compileShader(gpuStage.glShader); + + var isSuccess = gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS); + if (!isSuccess) { + console.error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed."); + console.error(gl.getShaderInfoLog(gpuStage.glShader)); + } else { + gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = 0; + } + } + } + + let glProgram = gl.createProgram(); + if (glProgram) { + gpuShader.glProgram = glProgram; + + // link program + for (let i = 0; i < gpuShader.gpuStages.length; ++i) { + let gpuStage = gpuShader.gpuStages[i]; + + gl.attachShader(gpuShader.glProgram, gpuStage.glShader); + } + } + + gl.linkProgram(gpuShader.glProgram); + var isSuccess = gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS); + if(!isSuccess) { + console.error("Failed to link shader '" + gpuShader.name + "'."); + console.error(gl.getProgramInfoLog(gpuShader.glProgram)); + + for (let i = 0; i < gpuShader.gpuStages.length; ++i) { + let gpuStage = gpuShader.gpuStages[i]; + if(gpuStage.glShader > 0) { + gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = 0; + } + } + } + + // parse inputs + let activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + gpuShader.glInputs = new Array(activeAttribCount); + + for (let i = 0; i < activeAttribCount; ++i) { + let info = gl.getActiveAttrib(gpuShader.glProgram, i); + if(info) { + let glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); + + let varName : string; + let nameOffset = info.name.search('['); + if (nameOffset !== -1) { + varName = info.name.substr(0, nameOffset); + } else { + varName = info.name; + } + + let type = WebGLTypeToGFXType(info.type); + let stride = WebGLGetTypeSize(info.type); + + gpuShader.glInputs[i] = { + binding : -1, + name : varName, + type : type, + stride : stride, + count : info.size, + size : stride * info.size, + + glType : info.type, + glLoc : glLoc, + }; + } + } + + // parse uniforms + let activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS); + let unitIdx = 0; + + for (let i = 0; i < activeAttribCount; ++i) { + let info = gl.getActiveUniform(gpuShader.glProgram, i); + if(info) { + let glLoc = gl.getUniformLocation(gpuShader.glProgram, info.name); + if(glLoc) { + let varName : string; + let nameOffset = info.name.search('['); + if (nameOffset !== -1) { + varName = info.name.substr(0, nameOffset); + } else { + varName = info.name; + } + + let type = WebGLTypeToGFXType(info.type); + + let isSampler = (type === WebGLRenderingContext.SAMPLER_2D) || + (type === WebGLRenderingContext.SAMPLER_CUBE); + + if(!isSampler) { + let stride = WebGLGetTypeSize(info.type); + + gpuShader.glUniforms.push({ + binding : -1, + name : varName, + type : type, + stride : stride, + count : info.size, + size : stride * info.size, + offset : 0, + + glType : info.type, + glLoc : glLoc, + }); + } else { + + let units = new Array(info.size); + for(let u = 0; u < info.size; ++u) { + units[u] = unitIdx + u; + } + + gpuShader.glSamplers.push({ + binding : -1, + name : varName, + type : type, + units : units, + + glType : info.type, + glLoc : glLoc, + }); + + unitIdx += info.size; + } + } + } + } +} + +export function WebGLCmdFuncDestroyShader(device : WebGLGFXDevice, gpuShader : WebGLGPUShader) { + + for (let i = 0; i < gpuShader.gpuStages.length; ++i) { + let gpuStage = gpuShader.gpuStages[i]; + + if (gpuStage.glShader > 0) { + device.gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = 0; + } + } + + if (gpuShader.glProgram > 0) { + device.gl.deleteProgram(gpuShader.glProgram); + gpuShader.glProgram = 0; + } +} \ No newline at end of file diff --git a/cocos/renderer/gfx/webgl/webgl-device.ts b/cocos/renderer/gfx/webgl/webgl-device.ts deleted file mode 100644 index 574f1094d7..0000000000 --- a/cocos/renderer/gfx/webgl/webgl-device.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { GFXDeviceInfo, GFXDevice } from '../gfx-device'; -import { GFXBuffer } from '../gfx-buffer'; -import { WebGLBuffer } from './webgl-buffer'; - -export class WebGLDevice extends GFXDevice { - - constructor(canvasEL : HTMLElement) { - - super(); - - try { - this._webGLRC = (canvasEL).getContext('webgl'); - } catch (err) { - console.error(err); - return; - } - - // No errors are thrown using try catch - // Tested through ios baidu browser 4.14.1 - if (!this._webGLRC) { - console.error('This device does not support WebGL.'); - } - } - - public initialize(info : GFXDeviceInfo) : boolean { - - return true; - } - - public destroy() : void { - - } - - public createBuffer() : GFXBuffer { - return new WebGLBuffer(this); - } - - public getDeviceName() : string { - return "WebGLDevice"; - } - - public get gl(): WebGLRenderingContext | null { - return this._webGLRC; - } - - private _webGLRC : WebGLRenderingContext | null = null; -}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts new file mode 100644 index 0000000000..d3ad89de4f --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts @@ -0,0 +1,62 @@ +import { GFXBufferInfo, GFXBuffer, GFXMemoryUsageBit, GFXBufferAccess, GFXBufferAccessBit, GFXBufferUsageBit } from '../gfx-buffer'; +import { GFXDevice } from '../gfx-device'; +import { WebGLGPUBuffer } from './webgl-gpu-objects'; +import { WebGLGFXDevice } from './webgl-gfx-device'; + +export class WebGLGFXBuffer extends GFXBuffer { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXBufferInfo) : boolean { + + this._usage = info.usage; + this._memUsage = info.memUsage; + this._size = info.size; + this._stride = info.stride; + + if (this._memUsage & GFXMemoryUsageBit.HOST) { + this._buffer = new ArrayBuffer(this._size); + } + + this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; + + if (!this._isSimulate) { + this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info); + } + + return true; + } + + public destroy() { + if(this._gpuBuffer) { + this.webGLDevice.emitCmdDestroyGPUBuffer(this._gpuBuffer); + this._buffer = null; + } + } + + public update(buffer : ArrayBuffer, offset : number) { + + if(this._buffer) { + let srcView : Uint8Array = new Uint8Array(buffer); + let dstView : Uint8Array = new Uint8Array(this._buffer, offset); + dstView.set(srcView); + } + + if(!this._isSimulate) { + this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, this._buffer); + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + public get gpuBuffer() : WebGLGPUBuffer | null { + return this._gpuBuffer; + } + + private _gpuBuffer : WebGLGPUBuffer | null = null; + private _isSimulate : boolean = false; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts b/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts new file mode 100644 index 0000000000..94499b104b --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts @@ -0,0 +1,27 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXCommandAllocator } from '../gfx-command-allocator'; + +export class WebGLGFXCommandPool { + + constructor(size: number) { + this._commands = new Array(size); + } + + private _commands : T[]; +}; + +export class GFXWebGLCommandAllocator extends GFXCommandAllocator { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize() : boolean { + + return true; + } + + public destroy() : void { + + } +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts new file mode 100644 index 0000000000..12b6066f8b --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -0,0 +1,261 @@ +import { GFXDeviceInfo, GFXDevice } from '../gfx-device'; +import { GFXBuffer, GFXBufferInfo } from '../gfx-buffer'; +import { WebGLGFXBuffer } from './webgl-gfx-buffer'; +import { WebGLGFXQueue } from './webgl-gfx-queue'; +import { WebGLStateCache } from './webgl-state-cache'; +import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage } from './webgl-gpu-objects'; +import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader } from './webgl-commands'; +import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit } from '../gfx-texture'; +import { GFXTextureViewType, GFXTextureViewInfo } from '../gfx-texture-view'; +import { GFXRenderPassInfo } from '../gfx-render-pass'; +import { GFXFramebufferInfo } from '../gfx-framebuffer'; +import { WebGLGFXRenderPass } from './webgl-gfx-render-pass'; +import { WebGLGFXTextureView } from './webgl-gfx-texture-view'; +import { WebGLGFXTexture } from './webgl-gfx-texture'; +import { GFXShaderInfo } from '../gfx-shader'; + +export class WebGLGFXDevice extends GFXDevice { + + stateCache : WebGLStateCache = new WebGLStateCache; + + constructor(canvasEL : HTMLElement) { + + super(); + + try { + this._webGLRC = (canvasEL).getContext('webgl'); + } catch (err) { + console.error(err); + return; + } + + // No errors are thrown using try catch + // Tested through ios baidu browser 4.14.1 + if (!this._webGLRC) { + console.error('This device does not support WebGL.'); + } + } + + public initialize(info : GFXDeviceInfo) : boolean { + + return true; + } + + public destroy() : void { + + } + + public createBuffer() : GFXBuffer { + return new WebGLGFXBuffer(this); + } + + public getDeviceName() : string { + return "WebGLDevice"; + } + + public get gl() : WebGLRenderingContext { + return this._webGLRC; + } + + public get webGLQueue(): WebGLGFXQueue { + return this._queue; + } + + public emitCmdCreateGPUBuffer(info : GFXBufferInfo) : WebGLGPUBuffer { + + let gpuBuffer : WebGLGPUBuffer = { + objType : WebGLGPUObjectType.BUFFER, + usage : info.usage, + memUsage : info.memUsage, + size : info.size, + stride : info.stride, + glTarget : 0, + glBuffer : 0, + }; + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; + + WebGLCmdFuncCreateBuffer(this, gpuBuffer); + + return gpuBuffer; + } + + public emitCmdDestroyGPUBuffer(gpuBuffer : WebGLGPUBuffer) { + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; + + WebGLCmdFuncDestroyBuffer(this, gpuBuffer); + } + + public emitCmdUpdateGPUBuffer(gpuBuffer : WebGLGPUBuffer, offset : number, data : ArrayBuffer) { + // TODO: Async + WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, data); + } + + public emitCmdCreateGPUTexture(info : GFXTextureInfo) : WebGLGPUTexture { + + let viewType : GFXTextureViewType; + + switch (info.type) { + case GFXTextureType.TEX1D : { + viewType = info.arrayLayer <= 1? GFXTextureViewType.TV1D : GFXTextureViewType.TV1D_ARRAY; + break; + } + case GFXTextureType.TEX2D : { + + if(info.arrayLayer <= 1) { + viewType = GFXTextureViewType.TV2D; + } else if(info.arrayLayer === 6 && (info.flags & GFXTextureFlagBit.CUBEMAP)) { + viewType = GFXTextureViewType.CUBE; + } else { + viewType = GFXTextureViewType.TV2D_ARRAY; + } + + break; + } + case GFXTextureType.TEX3D : { + viewType = GFXTextureViewType.TV3D; + break; + } + default: { + viewType = GFXTextureViewType.TV2D; + } + } + + let gpuTexture : WebGLGPUTexture = { + objType : WebGLGPUObjectType.TEXTURE, + type : info.type, + viewType : viewType, + format : info.format, + usage : info.usage, + width : info.width, + height : info.height, + depth : info.depth, + arrayLayer : info.arrayLayer, + mipLevel : info.mipLevel, + flags : info.flags, + + glTarget : 0, + glInternelFmt : 0, + glFormat : 0, + glType : 0, + glUsage : 0, + glTexture : 0, + }; + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; + WebGLCmdFuncCreateTexture(this, gpuTexture); + + return gpuTexture; + } + + public emitCmdDestroyGPUTexture(gpuTexture : WebGLGPUTexture) { + + // TODO: Async + // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; + WebGLCmdFuncDestroyTexture(this, gpuTexture); + } + + public emitCmdCreateGPUTextureView(info : GFXTextureViewInfo) : WebGLGPUTextureView { + let webGLTexture = info.texture; + + let gpuTextureView : WebGLGPUTextureView = { + objType : WebGLGPUObjectType.TEXTURE_VIEW, + gpuTexture : webGLTexture.gpuTexture, + type : info.type, + format : info.format, + baseLevel : info.baseLevel, + levelCount : info.levelCount, + }; + + return gpuTextureView; + } + + public emitCmdCreateGPURenderPass(info : GFXRenderPassInfo) : WebGLGPURenderPass { + let gpuRenderPass : WebGLGPURenderPass = { + objType : WebGLGPUObjectType.RENDER_PASS, + colorInfos : info.colorInfos, + depthStencilInfo : info.depthStencilInfo, + } + + return gpuRenderPass; + } + + public emitCmdCreateGPUFramebuffer(info : GFXFramebufferInfo) : WebGLGPUFramebuffer { + + let renderPass = info.renderPass; + + let gpuColorViews : (WebGLGPUTextureView | null)[] = new Array(); + + for (let i = 0; i < info.colorViews.length; ++i) { + let webGLColorView = info.colorViews[i]; + gpuColorViews[i] = webGLColorView.gpuTextureView; + } + + let webGLDSView = info.depthStencilView; + + let gpuFramebuffer : WebGLGPUFramebuffer = { + objType : WebGLGPUObjectType.FRAMEBUFFER, + gpuRenderPass : renderPass.gpuRenderPass, + gpuColorViews : gpuColorViews, + gpuDepthStencilView : webGLDSView.gpuTextureView, + isOffscreen : info.isOffscreen, + glFramebuffer : 0, + }; + + // TODO: Async + WebGLCmdFuncCreateFramebuffer(this, gpuFramebuffer); + + return gpuFramebuffer; + } + + public emitCmdDestroyGPUFramebuffer(gpuFramebuffer : WebGLGPUFramebuffer) { + + // TODO: Async + WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); + } + + public emitCmdCreateGPUShader(info : GFXShaderInfo) : WebGLGPUShader { + + let gpuStages: WebGLGPUShaderStage[] = []; + for(let i = 0; i < info.stages.length; ++i) { + let stage = info.stages[i]; + + gpuStages.push({ + type : stage.type, + source : stage.source, + macros : stage.macros, + glShader : 0, + }); + } + + let gpuShader : WebGLGPUShader = { + objType : WebGLGPUObjectType.SHADER, + name : info.name, + bindings : info.bindings, + + gpuStages : gpuStages, + glProgram : 0, + glInputs : [], + glUniforms : [], + glBlocks : [], + glSamplers : [], + }; + + // TODO: Async + WebGLCmdFuncCreateShader(this, gpuShader); + + return gpuShader; + } + + public emitCmdDestroyGPUShader(gpuShader : WebGLGPUShader) { + + // TODO: Async + WebGLCmdFuncDestroyShader(this, gpuShader); + } + + private _webGLRC : WebGLRenderingContext | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts new file mode 100644 index 0000000000..d5a789727d --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts @@ -0,0 +1,37 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXFramebuffer, GFXFramebufferInfo } from '../gfx-framebuffer'; +import { WebGLGPUFramebuffer } from './webgl-gpu-objects'; + +export class WebGLGFXFramebuffer extends GFXFramebuffer { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXFramebufferInfo) : boolean { + + this._colorViews = info.colorViews; + this._depthStencilView = info.depthStencilView; + this._isOffscreen = info.isOffscreen; + + this._gpuFramebuffer = this.webGLDevice.emitCmdCreateGPUFramebuffer(info); + + return true; + } + + public destroy() { + + if(this._gpuFramebuffer) + { + this.webGLDevice.emitCmdDestroyGPUFramebuffer(this._gpuFramebuffer); + this._gpuFramebuffer = null; + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + private _gpuFramebuffer : WebGLGPUFramebuffer | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts b/cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts new file mode 100644 index 0000000000..5b41266d2b --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts @@ -0,0 +1,22 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGPUTexture } from './webgl-gpu-objects'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXFormatSurfaceSize } from '../gfx-define'; +import { GFXInputState, GFXInputStateInfo } from '../gfx-input-state'; + +export class WebGLGFXInputState extends GFXInputState { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXInputStateInfo) : boolean { + + this._attributes = info.attributes; + + return true; + } + + public destroy() { + } +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts b/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts new file mode 100644 index 0000000000..1007da7839 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts @@ -0,0 +1,30 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; +import { GFXCommandBuffer } from '../gfx-command-buffer'; + +export class WebGLGFXQueue extends GFXQueue { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXQueueInfo) : boolean { + + this._type = info.type; + + return true; + } + + public destroy() { + + } + + public submit(cmdBuffs: GFXCommandBuffer[], fence) { + + for(let cb in cmdBuffs) { + + } + } + + private _isAsync : boolean = false; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts b/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts new file mode 100644 index 0000000000..0d64ae4606 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts @@ -0,0 +1,34 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGPUTexture, WebGLGPURenderPass } from './webgl-gpu-objects'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../gfx-texture'; +import { GFXFormatSurfaceSize } from '../gfx-define'; +import { GFXRenderPass, GFXRenderPassInfo } from '../gfx-render-pass'; + +export class WebGLGFXRenderPass extends GFXRenderPass { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXRenderPassInfo) : boolean { + + this._colorInfos = info.colorInfos; + this._depthStencilInfo = info.depthStencilInfo; + this._subPasses = info.subPasses; + + this._gpuRenderPass = (this._device).emitCmdCreateGPURenderPass(info); + + return true; + } + + public destroy() { + this._gpuRenderPass = null; + } + + public get gpuRenderPass(): WebGLGPURenderPass { + return this._gpuRenderPass; + } + + private _gpuRenderPass : WebGLGPURenderPass | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts b/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts new file mode 100644 index 0000000000..28de03d116 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts @@ -0,0 +1,30 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXSampler, GFXSamplerInfo } from '../gfx-sampler'; + +export class WebGLGFXSampler extends GFXSampler { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXSamplerInfo) : boolean { + + this._minFilter = info.minFilter; + this._magFilter = info.magFilter; + this._mipFilter = info.mipFilter; + this._addressU = info.addressU; + this._addressV = info.addressV; + this._addressW = info.addressW; + this._maxAnisotropy = info.maxAnisotropy; + this._cmpFunc = info.cmpFunc; + this._borderColor = info.borderColor; + this._minLOD = info.minLOD; + this._maxLOD = info.maxLOD; + this._mipLODBias = info.mipLODBias; + + return true; + } + + public destroy() { + } +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts b/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts new file mode 100644 index 0000000000..af0631eda8 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts @@ -0,0 +1,39 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXShader, GFXShaderInfo } from '../gfx-shader'; +import { WebGLGPUShader } from './webgl-gpu-objects'; + +export class WebGLGFXShader extends GFXShader { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXShaderInfo) : boolean { + + this._name = info.name; + this._stages = info.stages; + this._bindings = info.bindings; + + this._gpuShader = this.webGLDevice.emitCmdCreateGPUShader(info); + + return true; + } + + public destroy() { + if (this._gpuShader) { + this.webGLDevice.emitCmdDestroyGPUShader(this._gpuShader); + this._gpuShader = null; + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + public get gpuShader() : WebGLGPUShader | null { + return this._gpuShader; + } + + private _gpuShader : WebGLGPUShader | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts b/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts new file mode 100644 index 0000000000..1dbb679bec --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts @@ -0,0 +1,42 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXTextureView, GFXTextureViewInfo } from '../gfx-texture-view'; +import { WebGLGPUTextureView } from './webgl-gpu-objects'; +import { WebGLGFXDevice } from './webgl-gfx-device'; + +export class WebGLGFXTextureView extends GFXTextureView { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXTextureViewInfo) : boolean { + + this._texture = info.texture; + this._type = info.type; + this._format = info.format; + this._baseLevel = info.baseLevel; + this._format = info.format; + this._levelCount = info.levelCount; + this._baseLayer = info.baseLayer; + this._layerCount = info.layerCount; + + this.webGLDevice.emitCmdCreateGPUTextureView(info); + + return true; + } + + public destroy() { + this._gpuTextureView = null; + this._texture = null; + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + public get gpuTextureView() : WebGLGPUTextureView | null { + return this._gpuTextureView; + } + + private _gpuTextureView : WebGLGPUTextureView | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts b/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts new file mode 100644 index 0000000000..de8d880b46 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts @@ -0,0 +1,52 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGPUTexture } from './webgl-gpu-objects'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../gfx-texture'; +import { GFXFormatSurfaceSize } from '../gfx-define'; + +export class WebGLGFXTexture extends GFXTexture { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXTextureInfo) : boolean { + + this._type = info.type; + this._usage = info.usage; + this._format = info.format; + this._width = info.width; + this._height = info.height; + this._depth = info.depth; + this._arrayLayer = info.arrayLayer; + this._mipLevel = info.mipLevel; + this._flags = info.flags; + this._size = GFXFormatSurfaceSize(this._format, this.width, this.height, this.depth, this.mipLevel) * this._arrayLayer; + + if (this._flags & GFXTextureFlagBit.BAKUP_BUFFER) { + this._buffer = new ArrayBuffer(this._size); + } + + this._gpuTexture = this.webGLDevice.emitCmdCreateGPUTexture(info); + + return true; + } + + public destroy() { + + if(this._gpuTexture) { + this.webGLDevice.emitCmdDestroyGPUTexture(this._gpuTexture); + this._gpuTexture = null; + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + public get gpuTexture() : WebGLGPUTexture { + return this._gpuTexture; + } + + private _gpuTexture : WebGLGPUTexture | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts new file mode 100644 index 0000000000..23ad99a8ff --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts @@ -0,0 +1,181 @@ +import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from "../gfx-buffer"; +import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit } from "../gfx-texture"; +import { GFXTextureViewType } from "../gfx-texture-view"; +import { GFXFormat, GFX_MAX_VERTEX_ATTRIBUTES, GFXType } from "../gfx-define"; +import { GFXInputAttribute } from "../gfx-input-state"; +import { ColorAttachmentInfo, DepthStencilAttachmentInfo } from "../gfx-render-pass"; +import { GFXShaderType, GFXShaderMacro } from "../gfx-shader"; +import { GFXBinding } from "../gfx-binding-set-layout"; + +export const enum WebGLGPUObjectType { + UNKNOWN, + BUFFER, + TEXTURE, + TEXTURE_VIEW, + RENDER_PASS, + FRAMEBUFFER, + SHADER, + INPUT_STATE, +}; + +export class WebGLGPUObject { + objType : WebGLGPUObjectType; + + constructor(type : WebGLGPUObjectType) { + this.objType = type; + } +}; + +export class WebGLGPUBuffer extends WebGLGPUObject { + usage : GFXBufferUsage = GFXBufferUsageBit.NONE; + memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; + size : number = 0; + stride : number = 0; + + glTarget : GLenum = 0; + glBuffer : WebGLBuffer = 0; + + constructor() { + super(WebGLGPUObjectType.BUFFER); + } +}; + +export class WebGLGPUInputState extends WebGLGPUObject { + attributes : GFXInputAttribute[] = []; + vertexBuffers : (WebGLGPUBuffer | null)[] = Array(GFX_MAX_VERTEX_ATTRIBUTES); + indexBuffer : WebGLGPUBuffer | null = null; + glVAO : WebGLVertexArrayObjectOES = 0; +}; + +export class WebGLGPUTexture extends WebGLGPUObject { + type : GFXTextureType = GFXTextureType.TEX2D; + viewType : GFXTextureViewType = GFXTextureViewType.TV2D; + format : GFXFormat = GFXFormat.UNKNOWN; + usage : GFXTextureUsage = GFXTextureUsageBit.NONE; + width : number = 0; + height : number = 0; + depth : number = 0; + arrayLayer : number = 0; + mipLevel : number = 0; + flags : GFXTextureFlags = GFXTextureFlagBit.NONE; + + glTarget : GLenum = 0; + glInternelFmt : GLenum = 0; + glFormat : GLenum = 0; + glType : GLenum = 0; + glUsage : GLenum = 0; + glTexture : WebGLTexture = 0; + + constructor() { + super(WebGLGPUObjectType.TEXTURE); + } +}; + +export class WebGLGPUTextureView extends WebGLGPUObject { + + gpuTexture : WebGLGPUTexture; + type : GFXTextureViewType = GFXTextureViewType.TV2D; + format : GFXFormat = GFXFormat.UNKNOWN; + baseLevel : number = 0; + levelCount : number = 1; + + constructor(texture : WebGLGPUTexture) { + super(WebGLGPUObjectType.TEXTURE_VIEW); + this.gpuTexture = texture; + } +} + +export class WebGLGPURenderPass extends WebGLGPUObject { + + colorInfos : ColorAttachmentInfo[] = []; + depthStencilInfo : DepthStencilAttachmentInfo | null = null; + + constructor() { + super(WebGLGPUObjectType.RENDER_PASS); + } +}; + +export class WebGLGPUFramebuffer extends WebGLGPUObject { + + gpuRenderPass : WebGLGPURenderPass; + gpuColorViews : (WebGLGPUTextureView | null)[] = []; + gpuDepthStencilView : WebGLGPUTextureView | null = null; + isOffscreen : boolean = false; + + glFramebuffer : WebGLFramebuffer = 0; + + constructor(gpuRenderPass : WebGLGPURenderPass) { + super(WebGLGPUObjectType.FRAMEBUFFER); + + this.gpuRenderPass = gpuRenderPass; + } +}; + +export class WebGLGPUSampler extends WebGLGPUObject { + +}; + +export class WebGLGPUInput { + binding : number = -1; + name : string = ""; + type : GFXType = GFXType.UNKNOWN; + stride : number = 0; + count : number = 0; + size : number = 0; + + glType : GLenum = 0; + glLoc : GLint = 0; +}; + +export class WebGLGPUUniform { + binding : number = -1; + name : string = ""; + type : GFXType = GFXType.UNKNOWN; + stride : number = 0; + count : number = 0; + size : number = 0; + offset : number = 0; + + glType : GLenum = 0; + glLoc : WebGLUniformLocation = -1; +}; + +export class WebGLGPUUniformBlock { + binding : number = -1; + name : string = ""; + size : number = 0; + glUniforms : WebGLGPUUniform[] = []; +} + +export class WebGLGPUUniformSampler { + binding : number = -1; + name : string = ""; + type : GFXType = GFXType.UNKNOWN; + units : number[] = []; + + glType : GLenum = 0; + glLoc : WebGLUniformLocation = -1; +} + +export class WebGLGPUShaderStage { + type : GFXShaderType = GFXShaderType.VERTEX; + source : string = ""; + macros : GFXShaderMacro[] = []; + glShader : WebGLShader = 0; +}; + +export class WebGLGPUShader extends WebGLGPUObject { + name : string = ""; + bindings : GFXBinding[] = []; + + gpuStages : WebGLGPUShaderStage[] = []; + glProgram : WebGLProgram = 0; + glInputs : WebGLGPUInput[] = []; + glUniforms : WebGLGPUUniform[] = []; + glBlocks : WebGLGPUUniformBlock[] = []; + glSamplers : WebGLGPUUniformSampler[] = []; + + constructor() { + super(WebGLGPUObjectType.SHADER); + } +}; diff --git a/cocos/renderer/gfx/webgl/webgl-state-cache.ts b/cocos/renderer/gfx/webgl/webgl-state-cache.ts new file mode 100644 index 0000000000..0770c8a9c5 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-state-cache.ts @@ -0,0 +1,20 @@ +import { GFX_MAX_TEXTURE_UNITS } from "../gfx-define"; + +export class WebGLStateCache { + glArrayBuffer : WebGLBuffer | null = null; + glElementArrayBuffer : WebGLBuffer | null = null; + texUnit : number = 0; + glTex2DUnits : (WebGLTexture | null)[]; + glTexCubeUnits : (WebGLTexture | null)[]; + glFramebuffer : WebGLFramebuffer | null = null; + + constructor() { + this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); + + for(let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { + this.glTex2DUnits[i] = null; + this.glTexCubeUnits[i] = null; + } + } +}; diff --git a/playground/sample.html b/playground/sample.html index fc65c8b8a4..b654d5b526 100644 --- a/playground/sample.html +++ b/playground/sample.html @@ -29,7 +29,7 @@ From 02c52a77964ef8fcb2a686c005775be70f8108ef Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 26 Dec 2018 09:43:48 +0800 Subject: [PATCH 003/267] mod gfx --- cocos/renderer/gfx/gfx-binding-set-layout.ts | 37 +- cocos/renderer/gfx/gfx-buffer.ts | 21 +- cocos/renderer/gfx/gfx-command-allocator.ts | 2 +- cocos/renderer/gfx/gfx-command-buffer.ts | 15 +- cocos/renderer/gfx/gfx-define.ts | 183 +-- cocos/renderer/gfx/gfx-input-assembler.ts | 115 ++ cocos/renderer/gfx/gfx-input-state.ts | 26 - cocos/renderer/gfx/gfx-pipeline-layout.ts | 4 +- cocos/renderer/gfx/gfx-pipeline-state.ts | 23 +- cocos/renderer/gfx/gfx-render-pass.ts | 16 +- cocos/renderer/gfx/gfx-sampler.ts | 28 +- cocos/renderer/gfx/gfx-shader.ts | 30 +- cocos/renderer/gfx/webgl/webgl-commands.ts | 1172 +++++++++++++++-- .../gfx/webgl/webgl-gfx-binding-set-layout.ts | 55 + cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts | 50 +- .../gfx/webgl/webgl-gfx-command-allocator.ts | 56 +- .../gfx/webgl/webgl-gfx-command-buffer.ts | 136 ++ cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 381 ++++-- .../gfx/webgl/webgl-gfx-framebuffer.ts | 4 + .../gfx/webgl/webgl-gfx-input-assembler.ts | 40 + .../gfx/webgl/webgl-gfx-input-state.ts | 22 - .../gfx/webgl/webgl-gfx-pipeline-layout.ts | 32 + .../gfx/webgl/webgl-gfx-pipeline-state.ts | 45 + cocos/renderer/gfx/webgl/webgl-gfx-queue.ts | 13 +- .../gfx/webgl/webgl-gfx-render-pass.ts | 18 +- cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts | 14 + cocos/renderer/gfx/webgl/webgl-gfx-shader.ts | 1 + cocos/renderer/gfx/webgl/webgl-gpu-objects.ts | 290 ++-- cocos/renderer/gfx/webgl/webgl-state-cache.ts | 21 +- 29 files changed, 2277 insertions(+), 573 deletions(-) create mode 100644 cocos/renderer/gfx/gfx-input-assembler.ts delete mode 100644 cocos/renderer/gfx/gfx-input-state.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts delete mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts diff --git a/cocos/renderer/gfx/gfx-binding-set-layout.ts b/cocos/renderer/gfx/gfx-binding-set-layout.ts index 03b4d2512d..32985e531c 100644 --- a/cocos/renderer/gfx/gfx-binding-set-layout.ts +++ b/cocos/renderer/gfx/gfx-binding-set-layout.ts @@ -7,7 +7,6 @@ export const enum GFXBindingType { UNKNOWN, UNIFORM_BUFFER, SAMPLER, - TEXTURE_VIEW, STORAGE_BUFFER, }; @@ -39,6 +38,42 @@ export abstract class GFXBindingSetLayout { public abstract initialize(info : GFXBindingSetLayoutInfo) : boolean; public abstract destroy() : void; + public bindBuffer(binding: number, buffer: GFXBuffer) { + for (let i = 0; i < this._bindingUnits.length; ++i) { + let bindingUnit = this._bindingUnits[i]; + if (bindingUnit.type === GFXBindingType.UNIFORM_BUFFER) { + bindingUnit.buffer = buffer; + return; + } else { + console.error("Setting binding is not GFXBindingType.UNIFORM_BUFFER."); + } + } + } + + public bindSampler(binding: number, sampler: GFXSampler) { + for (let i = 0; i < this._bindingUnits.length; ++i) { + let bindingUnit = this._bindingUnits[i]; + if (bindingUnit.type === GFXBindingType.SAMPLER) { + bindingUnit.sampler = sampler; + return; + } else { + console.error("Setting binding is not GFXBindingType.SAMPLER."); + } + } + } + + public bindTextureView(binding: number, texView: GFXTextureView) { + for (let i = 0; i < this._bindingUnits.length; ++i) { + let bindingUnit = this._bindingUnits[i]; + if (bindingUnit.type === GFXBindingType.SAMPLER) { + bindingUnit.texView = texView; + return; + } else { + console.error("Setting binding is not GFXBindingType.SAMPLER."); + } + } + } + protected _device : GFXDevice; protected _bindingUnits : GFXBindingUnit[] = []; }; diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/renderer/gfx/gfx-buffer.ts index 9f3e2e87da..4fe393529a 100644 --- a/cocos/renderer/gfx/gfx-buffer.ts +++ b/cocos/renderer/gfx/gfx-buffer.ts @@ -2,14 +2,12 @@ import { GFXDevice } from './gfx-device'; export const enum GFXBufferUsageBit { NONE = 0, - MAP_READ = 0x1, - MAP_WRITE = 0x2, - TRANSFER_SRC = 0x4, - TRANSFER_DST = 0x8, - INDEX = 0x10, - VERTEX = 0x20, - UNIFORM = 0x40, - STORAGE = 0x80, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + INDEX = 0x4, + VERTEX = 0x8, + UNIFORM = 0x10, + STORAGE = 0x20, }; export type GFXBufferUsage = GFXBufferUsageBit; @@ -45,7 +43,7 @@ export abstract class GFXBuffer { public abstract initialize(info : GFXBufferInfo) : boolean; public abstract destroy() : void; - public abstract update(buffer : ArrayBuffer, offset : number); + public abstract update(buffer : Buffer, offset : number); public get usage(): GFXBufferUsage { return this._usage; @@ -63,7 +61,7 @@ export abstract class GFXBuffer { return this._stride; } - public get buffer(): ArrayBuffer | null { + public get buffer(): Buffer | null { return this._buffer; } @@ -72,5 +70,6 @@ export abstract class GFXBuffer { protected _memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; protected _size : number = 0; protected _stride : number = 1; - protected _buffer : ArrayBuffer | null = null; + protected _arrayBuffer : ArrayBuffer | null = null; + protected _buffer: Buffer | null = null; }; diff --git a/cocos/renderer/gfx/gfx-command-allocator.ts b/cocos/renderer/gfx/gfx-command-allocator.ts index 12a515ead8..fc4df8554d 100644 --- a/cocos/renderer/gfx/gfx-command-allocator.ts +++ b/cocos/renderer/gfx/gfx-command-allocator.ts @@ -7,7 +7,7 @@ export abstract class GFXCommandAllocator { } public abstract initialize() : boolean; - public abstract destroy() : void; + public abstract destroy(); protected _device : GFXDevice; } \ No newline at end of file diff --git a/cocos/renderer/gfx/gfx-command-buffer.ts b/cocos/renderer/gfx/gfx-command-buffer.ts index db15385888..bb18603cc8 100644 --- a/cocos/renderer/gfx/gfx-command-buffer.ts +++ b/cocos/renderer/gfx/gfx-command-buffer.ts @@ -1,5 +1,9 @@ import { GFXDevice } from './gfx-device'; import { GFXCommandAllocator } from './gfx-command-allocator'; +import { GFXBuffer } from './gfx-buffer'; +import { GFXInputAssembler } from './gfx-input-assembler'; +import { GFXPipelineState } from './gfx-pipeline-state'; +import { GFXBindingSetLayout } from './gfx-binding-set-layout'; export const enum GFXCommandBufferType { PRIMARY, @@ -18,12 +22,21 @@ export abstract class GFXCommandBuffer { } public abstract initialize(info : GFXCommandBufferInfo) : boolean; - public abstract destroy() : void; + public abstract destroy(); + + public abstract begin(); + public abstract end(); + public abstract bindPipelineState(pipelineState : GFXPipelineState); + public abstract bindBindingSetLayout(bindingSetLayout : GFXBindingSetLayout); + public abstract bindInputAssembler(inputAssembler : GFXInputAssembler); + public abstract draw(inputAssembler : GFXInputAssembler); + public abstract updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset : number); public get type(): number { return this._type; } protected _device : GFXDevice; + protected _allocator : GFXCommandAllocator | null = null; protected _type : GFXCommandBufferType = GFXCommandBufferType.PRIMARY; }; diff --git a/cocos/renderer/gfx/gfx-define.ts b/cocos/renderer/gfx/gfx-define.ts index 76d20ab9f5..4ed2c79f12 100644 --- a/cocos/renderer/gfx/gfx-define.ts +++ b/cocos/renderer/gfx/gfx-define.ts @@ -182,6 +182,7 @@ export const enum GFXFormat { export class GFXFormatInfo { readonly name : string = "UNKNOWN"; readonly size : number = 0; + readonly count : number = 0; readonly isFloating : boolean = false; readonly hasAlpha : boolean = false; readonly hasDepth : boolean = false; @@ -191,107 +192,107 @@ export class GFXFormatInfo { export const GFXFormatInfos : GFXFormatInfo[] = [ - { name : "UNKNOWN", size : 0, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "UNKNOWN", size : 0, count : 0, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "A8", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "L8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "LA8", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "A8", size : 1, count : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "L8", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "LA8", size : 1, count : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8SN", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8UI", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8I", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R16F", size : 2, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R16UI", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R16I", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R32F", size : 4, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R32UI", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R32I", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8SN", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8UI", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R8I", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R16F", size : 2, count : 1, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R16UI", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R16I", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R32F", size : 4, count : 1, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R32UI", size : 4, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R32I", size : 4, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8SN", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8UI", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8I", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG16F", size : 4, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG16UI", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG16I", size : 4, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG32F", size : 8, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG32UI", size : 8, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG32I", size : 8, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8SN", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8UI", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG8I", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG16F", size : 4, count : 2, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG16UI", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG16I", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG32F", size : 8, count : 2, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG32UI", size : 8, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RG32I", size : 8, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "SRGB8", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8SN", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8UI", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8I", size : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB16F", size : 6, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB16UI", size : 6, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB16I", size : 6, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB32F", size : 12, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB32UI", size : 12, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB32I", size : 12, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "SRGB8", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8SN", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8UI", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB8I", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB16F", size : 6, count : 3, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB16UI", size : 6, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB16I", size : 6, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB32F", size : 12, count : 3, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB32UI", size : 12, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB32I", size : 12, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "SRGB8_A8", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8SN", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8UI", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8I", size : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA16F", size : 8, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA16UI", size : 8, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA16I", size : 8, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA32F", size : 16, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA32UI", size : 16, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA32I", size : 16, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "SRGB8_A8", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8SN", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8UI", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA8I", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA16F", size : 8, count : 4, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA16UI", size : 8, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA16I", size : 8, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA32F", size : 16, count : 4, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA32UI", size : 16, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA32I", size : 16, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R5G6B5", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R11G11B10F", size : 4, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB5A1", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA4", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB10A2", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB10A2UI", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB9E5", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R5G6B5", size : 2, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "R11G11B10F", size : 4, count : 3, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB5A1", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGBA4", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB10A2", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB10A2UI", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, + { name : "RGB9E5", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "D16", size : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, - { name : "D24", size : 3, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, - { name : "D24S8", size : 4, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, - { name : "D32F", size : 4, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, - { name : "D32FS8", size : 5, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, + { name : "D16", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D24", size : 3, count : 1, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D24S8", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, + { name : "D32F", size : 4, count : 1, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D32FS8", size : 5, count : 2, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, - { name : "BC1", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC1_ALPHA", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC1_SRGB", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC1_SRGB_ALPHA", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC2", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC2_SRGB", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC3", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC3_SRGB", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC4", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC4_SNORM", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC5", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC5_SNORM", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC6H_UF16", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC6H_SF16", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC7", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC7_SRGB", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1_ALPHA", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1_SRGB", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC1_SRGB_ALPHA", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC2", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC2_SRGB", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC3", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC3_SRGB", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC4", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC4_SNORM", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC5", size : 1, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC5_SNORM", size : 1, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC6H_UF16", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC6H_SF16", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC7", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "BC7_SRGB", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC_RGB8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_RGB8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_SRGB8", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_RGB8_A1", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_SRGB8_A1", size : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_RGBA8", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_SRGB8_A8", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_R11", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_R11SN", size : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_RG11", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_RG11SN", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC_RGB8", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_RGB8", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_SRGB8", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_RGB8_A1", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_SRGB8_A1", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_RGBA8", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "ETC2_SRGB8_A8", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_R11", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_R11SN", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_RG11", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "EAC_RG11SN", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGB2", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGBA2", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGB4", size : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGBA4", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC2_2BPP", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC2_4BPP", size : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGB2", size : 2, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGBA2", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGB4", size : 2, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC_RGBA4", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC2_2BPP", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, + { name : "PVRTC2_4BPP", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, ]; export function GFXFormatSize(format : GFXFormat, width : number, height : number, depth : number) : number { diff --git a/cocos/renderer/gfx/gfx-input-assembler.ts b/cocos/renderer/gfx/gfx-input-assembler.ts new file mode 100644 index 0000000000..50aa6dfc6a --- /dev/null +++ b/cocos/renderer/gfx/gfx-input-assembler.ts @@ -0,0 +1,115 @@ +import { GFXDevice } from './gfx-device'; +import { GFXFormat } from './gfx-define'; +import { GFXBuffer } from './gfx-buffer'; +import { GFXShader } from './gfx-shader'; + +export class GFXInputAttribute { + name: string = ""; + format: GFXFormat = GFXFormat.UNKNOWN; + stream: number = 0; + isInstanced: boolean = false; +}; + +export class GFXInputAssemblerInfo { + attributes: GFXInputAttribute[] = []; + shader: GFXShader | null = null; + vertexBuffers: GFXBuffer[] = []; + indexBuffer: GFXBuffer | null = null; + isIndirect: boolean = false; +}; + +export abstract class GFXInputAssembler { + + constructor(device: GFXDevice) { + this._device = device; + } + + public abstract initialize(info: GFXInputAssemblerInfo): boolean; + public abstract destroy(): void; + + public get vertexBuffers(): GFXBuffer[] { + return this._vertexBuffers; + } + + public get indexBuffer(): GFXBuffer | null { + return this._indexBuffer; + } + + public getVertexBuffer(stream: number): GFXBuffer | null { + if (stream < this._vertexBuffers.length) { + return this._vertexBuffers[stream]; + } else { + return null; + } + } + + public get vertexCount(): number { + return this._vertexCount; + } + + public set vertexCount(count : number) { + this._vertexCount = count; + } + + public get firstVertex(): number { + return this._firstVertex; + } + + public set firstVertex(first : number) { + this._firstVertex = first; + } + + public get indexCount(): number { + return this._indexCount; + } + + public set indexCount(count : number) { + this._indexCount = count; + } + + public get firstIndex(): number { + return this._firstIndex; + } + + public set firstIndex(first : number) { + this._firstIndex = first; + } + + public get vertexOffset(): number { + return this._vertexOffset; + } + + public set vertexOffset(offset : number) { + this._vertexOffset = offset; + } + + public get instanceCount(): number { + return this._instanceCount; + } + + public set instanceCount(count : number) { + this._instanceCount = count; + } + + public get firstInstance(): number { + return this._firstInstance; + } + + public set firstInstance(first : number) { + this._firstInstance = first; + } + + protected _device: GFXDevice; + protected _attributes: GFXInputAttribute[] = []; + protected _vertexBuffers: GFXBuffer[] = []; + protected _indexBuffer: GFXBuffer | null = null; + protected _vertexCount: number = 0; + protected _firstVertex: number = 0; + protected _indexCount: number = 0; + protected _firstIndex: number = 0; + protected _vertexOffset: number = 0; + protected _instanceCount: number = 0; + protected _firstInstance: number = 0; + + protected _isIndirect: boolean = false; +}; diff --git a/cocos/renderer/gfx/gfx-input-state.ts b/cocos/renderer/gfx/gfx-input-state.ts deleted file mode 100644 index 2a682f6f75..0000000000 --- a/cocos/renderer/gfx/gfx-input-state.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { GFXDevice } from './gfx-device'; -import { GFX_MAX_VERTEX_ATTRIBUTES, GFXFormat } from './gfx-define'; - -export class GFXInputAttribute { - name : string = ""; - format : GFXFormat = GFXFormat.UNKNOWN; - //offset : number = 0; - isInstanced : boolean = false; -}; - -export class GFXInputStateInfo { - attributes: GFXInputAttribute[] = []; -}; - -export abstract class GFXInputState { - - constructor(device : GFXDevice) { - this._device = device; - } - - public abstract initialize(info : GFXInputStateInfo) : boolean; - public abstract destroy() : void; - - protected _device : GFXDevice; - protected _attributes: GFXInputAttribute[] = []; -}; diff --git a/cocos/renderer/gfx/gfx-pipeline-layout.ts b/cocos/renderer/gfx/gfx-pipeline-layout.ts index 0f3cbb944a..5190403b0a 100644 --- a/cocos/renderer/gfx/gfx-pipeline-layout.ts +++ b/cocos/renderer/gfx/gfx-pipeline-layout.ts @@ -1,5 +1,4 @@ import { GFXDevice } from './gfx-device'; -import { GFXRenderPass } from './gfx-render-pass'; import { GFXBindingSetLayout } from './gfx-binding-set-layout'; import { GFXShaderType } from './gfx-shader'; @@ -24,5 +23,6 @@ export abstract class GFXPipelineLayout { public abstract destroy() : void; protected _device : GFXDevice; - protected _renderPass: GFXRenderPass | null = null; + protected _pushConstantsRanges : GFXPushConstantRange[] = []; + protected _layouts: GFXBindingSetLayout[] = []; }; diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/renderer/gfx/gfx-pipeline-state.ts index c02ddc9f99..29de3c15ef 100644 --- a/cocos/renderer/gfx/gfx-pipeline-state.ts +++ b/cocos/renderer/gfx/gfx-pipeline-state.ts @@ -2,6 +2,8 @@ import { GFXDevice } from './gfx-device'; import { GFX_MAX_VERTEX_ATTRIBUTES, GFXFormat } from './gfx-define'; import { GFXShader } from './gfx-shader'; import { GFXRenderPass } from './gfx-render-pass'; +import { GFXPipelineLayout } from './gfx-pipeline-layout'; +import { GFXInputAttribute } from './gfx-input-assembler'; export const enum GFXPrimitiveMode { POINT_LIST, @@ -132,7 +134,7 @@ export class GFXDepthStencilState { frontStencilWriteMask : number = 0xffffffff; frontStencilFailOp : GFXStencilOp = GFXStencilOp.KEEP; frontStencilDepthFailOp : GFXStencilOp = GFXStencilOp.KEEP; - frontStencilPassFailOp : GFXStencilOp = GFXStencilOp.KEEP; + frontStencilPassOp : GFXStencilOp = GFXStencilOp.KEEP; frontStencilRef : number = 1; isBackStencilTest : boolean = false; backStencilFunc : GFXComparisonFunc = GFXComparisonFunc.ALWAYS; @@ -140,7 +142,7 @@ export class GFXDepthStencilState { backStencilWriteMask : number = 0xffffffff; backStencilFailOp : GFXStencilOp = GFXStencilOp.KEEP; backStencilDepthFailOp : GFXStencilOp = GFXStencilOp.KEEP; - backStencilPassFailOp : GFXStencilOp = GFXStencilOp.KEEP; + backStencilPassOp : GFXStencilOp = GFXStencilOp.KEEP; backStencilRef : number = 1; public compare(state : GFXDepthStencilState) : boolean { @@ -153,7 +155,7 @@ export class GFXDepthStencilState { (this.frontStencilWriteMask === state.frontStencilWriteMask) && (this.frontStencilFailOp === state.frontStencilFailOp) && (this.frontStencilDepthFailOp === state.frontStencilDepthFailOp) && - (this.frontStencilPassFailOp === state.frontStencilPassFailOp) && + (this.frontStencilPassOp === state.frontStencilPassOp) && (this.frontStencilRef === state.frontStencilRef) && (this.isBackStencilTest === state.isBackStencilTest) && (this.backStencilFunc === state.backStencilFunc) && @@ -161,7 +163,7 @@ export class GFXDepthStencilState { (this.backStencilWriteMask === state.backStencilWriteMask) && (this.backStencilFailOp === state.backStencilFailOp) && (this.backStencilDepthFailOp === state.backStencilDepthFailOp) && - (this.backStencilPassFailOp === state.backStencilPassFailOp) && + (this.backStencilPassOp === state.backStencilPassOp) && (this.backStencilRef === state.backStencilRef); } }; @@ -196,12 +198,18 @@ export class GFXBlendState { targets : GFXBlendTarget[] = [new GFXBlendTarget]; } +export class GFXInputState { + attributes: GFXInputAttribute[] = []; +}; + export class GFXPipelineStateInfo { - primitiveMode : GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + primitive : GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; shader : GFXShader | null = null; + is : GFXInputState | null = null; rs : GFXRasterizerState | null = null; dss : GFXDepthStencilState | null = null; - bs : GFXBlendState = new GFXBlendState; + bs : GFXBlendState | null = null; + layout : GFXPipelineLayout | null = null; renderPass : GFXRenderPass | null = null; }; @@ -216,8 +224,11 @@ export abstract class GFXPipelineState { protected _device : GFXDevice; protected _shader : GFXShader | null = null; + protected _primitive : GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + protected _is : GFXInputState | null = null; protected _rs : GFXRasterizerState | null = null; protected _dss : GFXDepthStencilState | null = null; protected _bs : GFXBlendState | null = null; + protected _layout: GFXPipelineLayout | null = null; protected _renderPass: GFXRenderPass | null = null; }; diff --git a/cocos/renderer/gfx/gfx-render-pass.ts b/cocos/renderer/gfx/gfx-render-pass.ts index 03634718e0..0fc5a925cc 100644 --- a/cocos/renderer/gfx/gfx-render-pass.ts +++ b/cocos/renderer/gfx/gfx-render-pass.ts @@ -30,7 +30,7 @@ export const enum GFXTextureLayout PRESENT_SRC, }; -export class ColorAttachmentInfo +export class GFXColorAttachment { format : GFXFormat = GFXFormat.UNKNOWN; loadOp : GFXLoadOp = GFXLoadOp.CLEAR; @@ -40,11 +40,11 @@ export class ColorAttachmentInfo endLayout : GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; }; -export class DepthStencilAttachmentInfo +export class GFXDepthStencilAttachment { format : GFXFormat = GFXFormat.UNKNOWN; - loadOp : GFXLoadOp = GFXLoadOp.CLEAR; - storeOp : GFXStoreOp = GFXStoreOp.STORE; + depthLoadOp : GFXLoadOp = GFXLoadOp.CLEAR; + depthStoreOp : GFXStoreOp = GFXStoreOp.STORE; stencilLoadOp : GFXLoadOp = GFXLoadOp.CLEAR; stencilStoreOp : GFXStoreOp = GFXStoreOp.STORE; sampleCount : number = 1; @@ -71,8 +71,8 @@ export class GFXSubPassInfo export class GFXRenderPassInfo { - colorInfos : ColorAttachmentInfo[] = []; - depthStencilInfo : DepthStencilAttachmentInfo | null = null; + colorInfos : GFXColorAttachment[] = []; + depthStencilInfo : GFXDepthStencilAttachment | null = null; subPasses : GFXSubPassInfo[] = []; }; @@ -86,7 +86,7 @@ export abstract class GFXRenderPass { public abstract destroy() : void; protected _device : GFXDevice; - protected _colorInfos : ColorAttachmentInfo[] = []; - protected _depthStencilInfo : DepthStencilAttachmentInfo | null = null; + protected _colorInfos : GFXColorAttachment[] = []; + protected _depthStencilInfo : GFXDepthStencilAttachment | null = null; protected _subPasses : GFXSubPassInfo[] = []; }; diff --git a/cocos/renderer/gfx/gfx-sampler.ts b/cocos/renderer/gfx/gfx-sampler.ts index 5b44c35ad0..4750c78372 100644 --- a/cocos/renderer/gfx/gfx-sampler.ts +++ b/cocos/renderer/gfx/gfx-sampler.ts @@ -1,14 +1,14 @@ import { GFXDevice } from './gfx-device'; import { GFXComparisonFunc } from './gfx-pipeline-state'; -export const enum GFXFilterOp { +export const enum GFXFilter { NONE, POINT, LINEAR, ANISOTROPIC, }; -export const enum GFXAddressMode { +export const enum GFXAddress { WRAP, MIRROR, CLAMP, @@ -17,12 +17,12 @@ export const enum GFXAddressMode { export class GFXSamplerInfo { name : string = ""; - minFilter : GFXFilterOp = GFXFilterOp.LINEAR; - magFilter : GFXFilterOp = GFXFilterOp.LINEAR; - mipFilter : GFXFilterOp = GFXFilterOp.LINEAR; - addressU : GFXAddressMode = GFXAddressMode.WRAP; - addressV : GFXAddressMode = GFXAddressMode.WRAP; - addressW : GFXAddressMode = GFXAddressMode.WRAP; + minFilter : GFXFilter = GFXFilter.LINEAR; + magFilter : GFXFilter = GFXFilter.LINEAR; + mipFilter : GFXFilter = GFXFilter.LINEAR; + addressU : GFXAddress = GFXAddress.WRAP; + addressV : GFXAddress = GFXAddress.WRAP; + addressW : GFXAddress = GFXAddress.WRAP; maxAnisotropy : number = 16; cmpFunc : GFXComparisonFunc = GFXComparisonFunc.NEVER; borderColor : number[] = [0.0, 0.0, 0.0, 0.0]; @@ -57,12 +57,12 @@ export abstract class GFXSampler { protected _device : GFXDevice; protected _name : string = ""; - protected _minFilter : GFXFilterOp = GFXFilterOp.LINEAR; - protected _magFilter : GFXFilterOp = GFXFilterOp.LINEAR; - protected _mipFilter : GFXFilterOp = GFXFilterOp.LINEAR; - protected _addressU : GFXAddressMode = GFXAddressMode.WRAP; - protected _addressV : GFXAddressMode = GFXAddressMode.WRAP; - protected _addressW : GFXAddressMode = GFXAddressMode.WRAP; + protected _minFilter : GFXFilter = GFXFilter.LINEAR; + protected _magFilter : GFXFilter = GFXFilter.LINEAR; + protected _mipFilter : GFXFilter = GFXFilter.LINEAR; + protected _addressU : GFXAddress = GFXAddress.WRAP; + protected _addressV : GFXAddress = GFXAddress.WRAP; + protected _addressW : GFXAddress = GFXAddress.WRAP; protected _maxAnisotropy : number = 16; protected _cmpFunc : GFXComparisonFunc = GFXComparisonFunc.NEVER; protected _borderColor : number[] = [0.0, 0.0, 0.0, 0.0]; diff --git a/cocos/renderer/gfx/gfx-shader.ts b/cocos/renderer/gfx/gfx-shader.ts index 8c400e3c8c..ae7e662ddf 100644 --- a/cocos/renderer/gfx/gfx-shader.ts +++ b/cocos/renderer/gfx/gfx-shader.ts @@ -22,28 +22,17 @@ export class GFXShaderMacro { } }; -export class GFXShaderVar { - binding : number = -1; +export class GFXUniform { name : string = ""; type : GFXType = GFXType.UNKNOWN; - stride : number = 0; - count : number = 0; - size : number = 0; - offset : number = 0; + count : number = 1; }; -export class GFXShaderBlock { +export class GFXUniformBlock { binding : number = -1; name : string = ""; - size : number = 0; - uniforms : GFXShaderVar[] = []; -}; - -export class GFXShaderSampler { - binding : number = -1; - name : string = ""; - type : GFXType = GFXType.UNKNOWN; - units : number[] = []; + //instance : string = ""; + uniforms : GFXUniform[] = []; }; export class GFXShaderStage { @@ -60,6 +49,9 @@ export class GFXShaderInfo { name : string = ""; stages : GFXShaderStage[] = []; bindings : GFXBinding[] = []; + + // blocks are used for being compatible with single uniforms + blocks : GFXUniformBlock[] = []; }; export abstract class GFXShader { @@ -75,9 +67,5 @@ export abstract class GFXShader { protected _name : string = ""; protected _stages : GFXShaderStage[] = []; protected _bindings : GFXBinding[] = []; - - protected _inputs : GFXShaderVar[] = []; - protected _uniforms : GFXShaderVar[] = []; - protected _blocks : GFXShaderBlock[] = []; - protected _samplers : GFXShaderSampler[] = []; + protected _blocks : GFXUniformBlock[] = []; }; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index e68ac7ea18..69a56c6b3c 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -1,12 +1,17 @@ -import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputState, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLGPUUniform } from "./webgl-gpu-objects"; +import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingSetLayout } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-gfx-device"; import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../gfx-buffer"; import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType } from "../gfx-define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES } from "../gfx-define"; import { GFXShaderType } from "../gfx-shader"; +import { GFXLoadOp } from "../gfx-render-pass"; +import { GFXColorMask, GFXCullMode } from "../gfx-pipeline-state"; +import { WebGLGFXCommandAllocator } from "./webgl-gfx-command-allocator"; +import { GFXBindingType } from "../gfx-binding-set-layout"; +import { Buffer } from "buffer"; -function GFXFormatToWebGLType(format : GFXFormat) : GLenum { - switch(format) { +function GFXFormatToWebGLType(format: GFXFormat): GLenum { + switch (format) { case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; case GFXFormat.R8UI: return WebGLRenderingContext.UNSIGNED_INT; @@ -107,8 +112,8 @@ function GFXFormatToWebGLType(format : GFXFormat) : GLenum { } } -function GFXFormatToWebGLInternalFormat(format : GFXFormat) : GLenum { - switch(format) { +function GFXFormatToWebGLInternalFormat(format: GFXFormat): GLenum { + switch (format) { case GFXFormat.A8: return WebGLRenderingContext.ALPHA; case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; @@ -122,7 +127,7 @@ function GFXFormatToWebGLInternalFormat(format : GFXFormat) : GLenum { case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; case GFXFormat.D32F_S8: return WebGLRenderingContext.DEPTH_STENCIL; - + case GFXFormat.BC1: return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT; case GFXFormat.BC1_ALPHA: return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT; case GFXFormat.BC1_SRGB: return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT; @@ -146,8 +151,8 @@ function GFXFormatToWebGLInternalFormat(format : GFXFormat) : GLenum { } } -function GFXFormatToWebGLFormat(format : GFXFormat) : GLenum { - switch(format) { +function GFXFormatToWebGLFormat(format: GFXFormat): GLenum { + switch (format) { case GFXFormat.A8: return WebGLRenderingContext.ALPHA; case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; @@ -172,7 +177,7 @@ function GFXFormatToWebGLFormat(format : GFXFormat) : GLenum { case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; - + case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; case GFXFormat.PVRTC_RGB4: return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; @@ -185,8 +190,8 @@ function GFXFormatToWebGLFormat(format : GFXFormat) : GLenum { } } -function WebGLTypeToGFXType(glType : GLenum) : GFXType { - switch(glType) { +function WebGLTypeToGFXType(glType: GLenum): GFXType { + switch (glType) { case WebGLRenderingContext.BOOL: return GFXType.BOOL; case WebGLRenderingContext.BOOL_VEC2: return GFXType.BOOL2; case WebGLRenderingContext.BOOL_VEC3: return GFXType.BOOL3; @@ -212,8 +217,8 @@ function WebGLTypeToGFXType(glType : GLenum) : GFXType { } } -function WebGLGetTypeSize(glType : GLenum) : GFXType { - switch(glType) { +function WebGLGetTypeSize(glType: GLenum): GFXType { + switch (glType) { case WebGLRenderingContext.BOOL: return 4; case WebGLRenderingContext.BOOL_VEC2: return 8; case WebGLRenderingContext.BOOL_VEC3: return 12; @@ -239,24 +244,215 @@ function WebGLGetTypeSize(glType : GLenum) : GFXType { } } -export const enum WebGLCmdType { - UNKNOWN, - CREATE_BUFFER, - DESTROY_BUFFER, +function WebGLGetComponentCount(glType: GLenum): GFXType { + switch (glType) { + case WebGLRenderingContext.FLOAT_MAT2: return 2; + case WebGLRenderingContext.FLOAT_MAT3: return 3; + case WebGLRenderingContext.FLOAT_MAT4: return 4; + default: { + console.error("Unsupported GLType, get component count failed."); + return 0; + } + } +} + +const WebGLCmpFuncs: GLenum[] = [ + WebGLRenderingContext.NEVER, + WebGLRenderingContext.LESS, + WebGLRenderingContext.EQUAL, + WebGLRenderingContext.LEQUAL, + WebGLRenderingContext.GREATER, + WebGLRenderingContext.NOTEQUAL, + WebGLRenderingContext.GEQUAL, + WebGLRenderingContext.ALWAYS, +]; + +const WebGLStencilOps: GLenum[] = [ + WebGLRenderingContext.KEEP, + WebGLRenderingContext.ZERO, + WebGLRenderingContext.REPLACE, + WebGLRenderingContext.INCR, + WebGLRenderingContext.DECR, + WebGLRenderingContext.INVERT, + WebGLRenderingContext.INCR_WRAP, + WebGLRenderingContext.DECR_WRAP, +]; + +const WebGLBlendOps: GLenum[] = [ + WebGLRenderingContext.FUNC_ADD, + WebGLRenderingContext.FUNC_SUBTRACT, + WebGLRenderingContext.FUNC_REVERSE_SUBTRACT, + WebGLRenderingContext.FUNC_ADD, + WebGLRenderingContext.FUNC_ADD, +]; + +const WebGLBlendFactors: GLenum[] = [ + WebGLRenderingContext.ZERO, + WebGLRenderingContext.ONE, + WebGLRenderingContext.SRC_ALPHA, + WebGLRenderingContext.DST_ALPHA, + WebGLRenderingContext.ONE_MINUS_SRC_ALPHA, + WebGLRenderingContext.ONE_MINUS_DST_ALPHA, + WebGLRenderingContext.SRC_COLOR, + WebGLRenderingContext.DST_COLOR, + WebGLRenderingContext.SRC_ALPHA_SATURATE, + WebGLRenderingContext.CONSTANT_COLOR, + WebGLRenderingContext.ONE_MINUS_CONSTANT_COLOR, + WebGLRenderingContext.CONSTANT_ALPHA, + WebGLRenderingContext.ONE_MINUS_CONSTANT_ALPHA, +]; + +export const enum WebGLCmd { + BEGIN_RENDER_PASS, + END_RENDER_PASS, + BIND_PIPELINE_STATE, + BIND_INPUT_ASSEMBLER, + BIND_BINDING_SET_LAYOUT, + DRAW, + UPDATE_BUFFER, + COUNT, }; -export class WebGLCmd { - type : WebGLCmdType = WebGLCmdType.UNKNOWN; - obj : any; - isFree : boolean = false; +export class WebGLCmdObject { + cmdType: WebGLCmd; + + constructor(type: WebGLCmd) { + this.cmdType = type; + } }; -export function WebGLCmdFuncCreateBuffer(device : WebGLGFXDevice, gpuBuffer : WebGLGPUBuffer) { +export class WebGLCmdBeginRenderPass extends WebGLCmdObject { - let gl : WebGLRenderingContext = device.gl; + gpuFramebuffer: WebGLGPUFramebuffer | null = null; + viewport: number[] = []; + numClearColors: number = 0; + clearColors: number[] = []; + clearDepth: number = 1.0; + clearStencil: number = 0; + + constructor() { + super(WebGLCmd.BEGIN_RENDER_PASS); + } +} + +export class WebGLCmdBindPipelineState extends WebGLCmdObject { + + gpuPipelineState: WebGLGPUPipelineState | null = null; + + constructor() { + super(WebGLCmd.BIND_PIPELINE_STATE); + } +}; + +export class WebGLCmdBindInputAssembler extends WebGLCmdObject { + + gpuInputAssembler: WebGLGPUInputAssembler | null = null; + + constructor() { + super(WebGLCmd.BIND_INPUT_ASSEMBLER); + } +}; + +export class WebGLCmdBindBindingSetLayout extends WebGLCmdObject { + + gpuBindingSetLayout: WebGLGPUBindingSetLayout | null = null; + + constructor() { + super(WebGLCmd.BIND_BINDING_SET_LAYOUT); + } +}; + +export class WebGLCmdDraw extends WebGLCmdObject { + + vertexCount: number = 0; + firstVertex: number = 0; + + indexCount: number = 0; + firstIndex: number = 0; + vertexOffset: number = 0; + + instanceCount: number = 0; + firstInstance: number = 0; + + constructor() { + super(WebGLCmd.DRAW); + } +}; + +export class WebGLCmdUpdateBuffer extends WebGLCmdObject { + + gpuBuffer: WebGLGPUBuffer | null = null; + data: ArrayBuffer | null = null; + offset: number = 0; + + constructor() { + super(WebGLCmd.UPDATE_BUFFER); + } +}; + +export class WebGLCmdPackage { + cmds: WebGLCmd[] = []; + beginRenderPassCmds: WebGLCmdBeginRenderPass[] = []; + bindPipelineStateCmds: WebGLCmdBindPipelineState[] = []; + bindBindingSetLayoutCmds: WebGLCmdBindBindingSetLayout[] = []; + bindInputAssemblerCmds: WebGLCmdBindInputAssembler[] = []; + drawCmds: WebGLCmdDraw[] = []; + updateBufferCmds: WebGLCmdUpdateBuffer[] = []; + + clearCmds(allocator: WebGLGFXCommandAllocator) { + + if (this.beginRenderPassCmds.length) { + for (let i = 0; i < this.beginRenderPassCmds.length; ++i) { + allocator.beginRenderPassCmdPool.free(this.beginRenderPassCmds[i]); + } + this.beginRenderPassCmds = []; + } + + if (this.bindPipelineStateCmds.length) { + for (let i = 0; i < this.bindPipelineStateCmds.length; ++i) { + allocator.bindPipelineStateCmdPool.free(this.bindPipelineStateCmds[i]); + } + this.bindPipelineStateCmds = []; + } + + if (this.bindBindingSetLayoutCmds.length) { + for (let i = 0; i < this.bindBindingSetLayoutCmds.length; ++i) { + allocator.bindBindingSetLayoutCmdPool.free(this.bindBindingSetLayoutCmds[i]); + } + this.bindBindingSetLayoutCmds = []; + } + + if (this.bindInputAssemblerCmds.length) { + for (let i = 0; i < this.bindInputAssemblerCmds.length; ++i) { + allocator.bindInputAssemblerCmdPool.free(this.bindInputAssemblerCmds[i]); + } + this.bindInputAssemblerCmds = []; + } + + if (this.drawCmds.length) { + for (let i = 0; i < this.drawCmds.length; ++i) { + allocator.drawCmdPool.free(this.drawCmds[i]); + } + this.drawCmds = []; + } + + if (this.updateBufferCmds.length) { + for (let i = 0; i < this.updateBufferCmds.length; ++i) { + allocator.updateBufferCmdPool.free(this.updateBufferCmds[i]); + } + this.updateBufferCmds = []; + } + + this.cmds = []; + } +} + +export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { + + let gl: WebGLRenderingContext = device.gl; if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { - + gpuBuffer.glTarget = WebGLRenderingContext.ARRAY_BUFFER; let glBuffer = gl.createBuffer(); if (glBuffer) { @@ -266,15 +462,15 @@ export function WebGLCmdFuncCreateBuffer(device : WebGLGFXDevice, gpuBuffer : We gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - - let glUsage : GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + + let glUsage: GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); - + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); device.stateCache.glArrayBuffer = null; } } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { - + gpuBuffer.glTarget = WebGLRenderingContext.ELEMENT_ARRAY_BUFFER; let glBuffer = gl.createBuffer(); if (glBuffer) { @@ -284,10 +480,10 @@ export function WebGLCmdFuncCreateBuffer(device : WebGLGFXDevice, gpuBuffer : We gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - - let glUsage : GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + + let glUsage: GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); - + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); device.stateCache.glElementArrayBuffer = null; } @@ -304,89 +500,84 @@ export function WebGLCmdFuncCreateBuffer(device : WebGLGFXDevice, gpuBuffer : We } } -export function WebGLCmdFuncDestroyBuffer(device : WebGLGFXDevice, gpuBuffer : WebGLGPUBuffer) { - if(gpuBuffer.glBuffer > 0) { +export function WebGLCmdFuncDestroyBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { + if (gpuBuffer.glBuffer > 0) { device.gl.deleteBuffer(gpuBuffer.glBuffer); gpuBuffer.glBuffer = 0; } } -export function WebGLCmdFuncUpdateBuffer(device : WebGLGFXDevice, gpuBuffer : WebGLGPUBuffer, offset : number, data : ArrayBuffer) { +export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: Buffer) { - let gl : WebGLRenderingContext = device.gl; + let gl: WebGLRenderingContext = device.gl; switch (gpuBuffer.glTarget) { - case WebGLRenderingContext.ARRAY_BUFFER : { - + case WebGLRenderingContext.ARRAY_BUFFER: { if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - - gl.bufferSubData(WebGLRenderingContext.ARRAY_BUFFER, offset, data); - break; } - case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER : { - + case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - - gl.bufferSubData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, offset, data); - break; } - default : { + default: { console.error("Unsupported GFXBufferType, update buffer failed."); + return; } } + + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer.buffer); } -export function WebGLCmdFuncCreateInputState(device : WebGLGFXDevice, gpuInputState : WebGLGPUInputState) { +export function WebGLCmdFuncCreateInputState(device: WebGLGFXDevice, gpuInputState: WebGLGPUInputAssembler) { } -export function WebGLCmdFuncDestroyInputState(device : WebGLGFXDevice, gpuInputState : WebGLGPUInputState) { +export function WebGLCmdFuncDestroyInputState(device: WebGLGFXDevice, gpuInputState: WebGLGPUInputAssembler) { /*if(gpuInputState.glVAO > 0) { gpuInputState.glVAO = 0; }*/ } -export function WebGLCmdFuncCreateTexture(device : WebGLGFXDevice, gpuTexture : WebGLGPUTexture) { +export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { - let gl : WebGLRenderingContext = device.gl; + let gl: WebGLRenderingContext = device.gl; gpuTexture.glInternelFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format); gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format); switch (gpuTexture.viewType) { - case GFXTextureViewType.TV2D : { + case GFXTextureViewType.TV2D: { gpuTexture.viewType = GFXTextureViewType.TV2D; gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; let glTexture = gl.createTexture(); - if(glTexture) { + if (glTexture) { gpuTexture.glTexture = glTexture; if (device.stateCache.glTex2DUnits[device.stateCache.texUnit] !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); device.stateCache.glTex2DUnits[device.stateCache.texUnit] = gpuTexture.glTexture; } - + let w = gpuTexture.width; let h = gpuTexture.height; - + if (!GFXFormatInfos[gpuTexture.format].isCompressed) { - for(let i = 0; i < gpuTexture.mipLevel; ++i) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { gl.texImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); w = Math.max(1, w >> 1); h = Math.max(1, h >> 1); } } else { - let view : ArrayBufferView = { buffer : new ArrayBuffer(0), byteLength : 0, byteOffset : 0 }; + let view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; for (let i = 0; i < gpuTexture.mipLevel; ++i) { gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, view); w = Math.max(1, w >> 1); @@ -397,7 +588,7 @@ export function WebGLCmdFuncCreateTexture(device : WebGLGFXDevice, gpuTexture : break; } - case GFXTextureViewType.CUBE : { + case GFXTextureViewType.CUBE: { gpuTexture.viewType = GFXTextureViewType.CUBE; gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_CUBE_MAP; @@ -422,12 +613,12 @@ export function WebGLCmdFuncCreateTexture(device : WebGLGFXDevice, gpuTexture : } } } else { - let view : ArrayBufferView = { buffer : new ArrayBuffer(0), byteLength : 0, byteOffset : 0 }; + let view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; for (let f = 0; f < 6; ++f) { let w = gpuTexture.width; let h = gpuTexture.height; - for(let i = 0; i < gpuTexture.mipLevel; ++i) { + for (let i = 0; i < gpuTexture.mipLevel; ++i) { gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, view); w = Math.max(1, w >> 1); h = Math.max(1, h >> 1); @@ -438,7 +629,7 @@ export function WebGLCmdFuncCreateTexture(device : WebGLGFXDevice, gpuTexture : break; } - default : { + default: { console.error("Unsupported GFXTextureType, create texture failed."); gpuTexture.viewType = GFXTextureViewType.TV2D; gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; @@ -446,19 +637,19 @@ export function WebGLCmdFuncCreateTexture(device : WebGLGFXDevice, gpuTexture : } } -export function WebGLCmdFuncDestroyTexture(device : WebGLGFXDevice, gpuTexture : WebGLGPUTexture) { +export function WebGLCmdFuncDestroyTexture(device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { if (gpuTexture.glTexture > 0) { device.gl.deleteTexture(gpuTexture.glTexture); gpuTexture.glTexture = 0; } } -export function WebGLCmdFuncCreateFramebuffer(device : WebGLGFXDevice, gpuFramebuffer : WebGLGPUFramebuffer) { +export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { + + if (!gpuFramebuffer.isOffscreen) { + + let gl: WebGLRenderingContext = device.gl; - if(!gpuFramebuffer.isOffscreen) { - - let gl : WebGLRenderingContext = device.gl; - let glFramebuffer = gl.createFramebuffer(); if (glFramebuffer) { gpuFramebuffer.glFramebuffer = glFramebuffer; @@ -467,28 +658,28 @@ export function WebGLCmdFuncCreateFramebuffer(device : WebGLGFXDevice, gpuFrameb gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); device.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer; } - + for (let i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) { - + let gpuColorView = gpuFramebuffer.gpuColorViews[i]; if (gpuColorView) { gl.framebufferTexture2D( - WebGLRenderingContext.FRAMEBUFFER, - WebGLRenderingContext.COLOR_ATTACHMENT0 + i, + WebGLRenderingContext.FRAMEBUFFER, + WebGLRenderingContext.COLOR_ATTACHMENT0 + i, gpuColorView.gpuTexture.glTarget, gpuColorView.gpuTexture.glTexture, gpuColorView.baseLevel); } } - - if(gpuFramebuffer.gpuDepthStencilView) { - - let glAttachment = GFXFormatInfos[gpuFramebuffer.gpuDepthStencilView.format].hasStencil? - WebGLRenderingContext.DEPTH_STENCIL_ATTACHMENT : WebGLRenderingContext.DEPTH_ATTACHMENT; - + + if (gpuFramebuffer.gpuDepthStencilView) { + + let glAttachment = GFXFormatInfos[gpuFramebuffer.gpuDepthStencilView.format].hasStencil ? + WebGLRenderingContext.DEPTH_STENCIL_ATTACHMENT : WebGLRenderingContext.DEPTH_ATTACHMENT; + gl.framebufferTexture2D( - WebGLRenderingContext.FRAMEBUFFER, - glAttachment, + WebGLRenderingContext.FRAMEBUFFER, + glAttachment, gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTarget, gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTexture, gpuFramebuffer.gpuDepthStencilView.baseLevel); @@ -497,20 +688,20 @@ export function WebGLCmdFuncCreateFramebuffer(device : WebGLGFXDevice, gpuFrameb } } -export function WebGLCmdFuncDestroyFramebuffer(device : WebGLGFXDevice, gpuFramebuffer : WebGLGPUFramebuffer) { +export function WebGLCmdFuncDestroyFramebuffer(device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { if (gpuFramebuffer.glFramebuffer > 0) { device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer); gpuFramebuffer.glFramebuffer = 0; } } -export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : WebGLGPUShader) { - let gl : WebGLRenderingContext = device.gl; +export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { + let gl: WebGLRenderingContext = device.gl; for (let i = 0; i < gpuShader.gpuStages.length; ++i) { let gpuStage = gpuShader.gpuStages[i]; - let glShaderType : GLenum = 0; + let glShaderType: GLenum = 0; let shaderTypeStr = ""; switch (gpuStage.type) { @@ -526,7 +717,7 @@ export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : We } default: { console.error("Unsupported GFXShaderType."); - return ; + return; } } @@ -535,7 +726,7 @@ export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : We gpuStage.glShader = glShader; gl.shaderSource(gpuStage.glShader, gpuStage.source); gl.compileShader(gpuStage.glShader); - + var isSuccess = gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS); if (!isSuccess) { console.error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed."); @@ -554,20 +745,20 @@ export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : We // link program for (let i = 0; i < gpuShader.gpuStages.length; ++i) { let gpuStage = gpuShader.gpuStages[i]; - + gl.attachShader(gpuShader.glProgram, gpuStage.glShader); } } gl.linkProgram(gpuShader.glProgram); var isSuccess = gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS); - if(!isSuccess) { + if (!isSuccess) { console.error("Failed to link shader '" + gpuShader.name + "'."); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); - + for (let i = 0; i < gpuShader.gpuStages.length; ++i) { let gpuStage = gpuShader.gpuStages[i]; - if(gpuStage.glShader > 0) { + if (gpuStage.glShader > 0) { gl.deleteShader(gpuStage.glShader); gpuStage.glShader = 0; } @@ -580,10 +771,10 @@ export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : We for (let i = 0; i < activeAttribCount; ++i) { let info = gl.getActiveAttrib(gpuShader.glProgram, i); - if(info) { + if (info) { let glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); - - let varName : string; + + let varName: string; let nameOffset = info.name.search('['); if (nameOffset !== -1) { varName = info.name.substr(0, nameOffset); @@ -595,81 +786,141 @@ export function WebGLCmdFuncCreateShader(device : WebGLGFXDevice, gpuShader : We let stride = WebGLGetTypeSize(info.type); gpuShader.glInputs[i] = { - binding : -1, - name : varName, - type : type, - stride : stride, - count : info.size, - size : stride * info.size, - - glType : info.type, - glLoc : glLoc, + binding: -1, + name: varName, + type: type, + stride: stride, + count: info.size, + size: stride * info.size, + + glType: info.type, + glLoc: glLoc, }; } } + // create uniform blocks + if (gpuShader.blocks.length > 0) { + gpuShader.glBlocks = new Array(gpuShader.blocks.length); + for (let i = 0; i < gpuShader.blocks.length; ++i) { + let block = gpuShader.blocks[i]; + let glBlock = gpuShader.glBlocks[i]; + glBlock.isUniformPackage = true; + glBlock.binding = block.binding; + glBlock.name = block.name; + } + } + // parse uniforms let activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS); let unitIdx = 0; - for (let i = 0; i < activeAttribCount; ++i) { + for (let i = 0; i < activeUniformCount; ++i) { let info = gl.getActiveUniform(gpuShader.glProgram, i); - if(info) { + if (info) { let glLoc = gl.getUniformLocation(gpuShader.glProgram, info.name); - if(glLoc) { - let varName : string; + if (glLoc) { + let varName: string; let nameOffset = info.name.search('['); if (nameOffset !== -1) { varName = info.name.substr(0, nameOffset); } else { varName = info.name; } - + let type = WebGLTypeToGFXType(info.type); let isSampler = (type === WebGLRenderingContext.SAMPLER_2D) || - (type === WebGLRenderingContext.SAMPLER_CUBE); + (type === WebGLRenderingContext.SAMPLER_CUBE); - if(!isSampler) { + if (!isSampler) { let stride = WebGLGetTypeSize(info.type); - - gpuShader.glUniforms.push({ - binding : -1, - name : varName, - type : type, - stride : stride, - count : info.size, - size : stride * info.size, - offset : 0, - - glType : info.type, - glLoc : glLoc, - }); + + // build uniform block mapping + for (let b = 0; b < gpuShader.blocks.length; ++b) { + + let block = gpuShader.blocks[b]; + let glBlock = gpuShader.glBlocks[b]; + + for (let u = 0; u < block.uniforms.length; ++u) { + let uniform = block.uniforms[u]; + if (uniform.name === varName) { + let varSize = stride * info.size; + + glBlock.glUniforms.push({ + binding: -1, + name: varName, + type: type, + stride: stride, + count: info.size, + size: varSize, + offset: glBlock.size, + + glType: info.type, + glLoc: glLoc, + bufferView: null, + }); + + glBlock.size += varSize; + + break; + } + } + } // for } else { let units = new Array(info.size); - for(let u = 0; u < info.size; ++u) { + for (let u = 0; u < info.size; ++u) { units[u] = unitIdx + u; } gpuShader.glSamplers.push({ - binding : -1, - name : varName, - type : type, - units : units, - - glType : info.type, - glLoc : glLoc, + binding: -1, + name: varName, + type: type, + units: units, + + glType: info.type, + glLoc: glLoc, }); unitIdx += info.size; } } } + } // for + + for (let b = 0; b < gpuShader.glBlocks.length; ++b) { + + let glBlock = gpuShader.glBlocks[b]; + glBlock.buffer = new ArrayBuffer(glBlock.size); + glBlock.bufferView = new Buffer(glBlock.buffer); + + for (let u = 0; u < glBlock.glUniforms.length; ++u) { + let glUniform = glBlock.glUniforms[u]; + if(glUniform.glLoc >= 0) { + switch (glUniform.glType) { + case WebGLRenderingContext.BOOL: + case WebGLRenderingContext.BOOL_VEC2: + case WebGLRenderingContext.BOOL_VEC3: + case WebGLRenderingContext.BOOL_VEC4: + case WebGLRenderingContext.INT: + case WebGLRenderingContext.INT_VEC3: + case WebGLRenderingContext.INT_VEC2: + case WebGLRenderingContext.INT_VEC4: { + glUniform.bufferView = new Int32Array(glBlock.buffer, glUniform.offset, glUniform.count); + break; + } + default: { + glUniform.bufferView = new Float32Array(glBlock.buffer, glUniform.offset, glUniform.count); + } + } + } + } } } -export function WebGLCmdFuncDestroyShader(device : WebGLGFXDevice, gpuShader : WebGLGPUShader) { +export function WebGLCmdFuncDestroyShader(device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { for (let i = 0; i < gpuShader.gpuStages.length; ++i) { let gpuStage = gpuShader.gpuStages[i]; @@ -679,9 +930,666 @@ export function WebGLCmdFuncDestroyShader(device : WebGLGFXDevice, gpuShader : W gpuStage.glShader = 0; } } - + if (gpuShader.glProgram > 0) { device.gl.deleteProgram(gpuShader.glProgram); gpuShader.glProgram = 0; } -} \ No newline at end of file +} + +export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { + + if (gpuInputAssembler.gpuShader) { + let attribCount = gpuInputAssembler.gpuShader.glInputs.length; + gpuInputAssembler.glAttribs = new Array(attribCount); + + let offsets = [0, 0, 0, 0, 0, 0, 0, 0]; + + for (let i = 0; i < attribCount; ++i) { + let glInput = gpuInputAssembler.gpuShader.glInputs[i]; + let glAttrib = gpuInputAssembler.glAttribs[i]; + glAttrib.glLoc = glInput.glLoc; + glAttrib.glType = glInput.glType; + glAttrib.size = glInput.size; + glAttrib.componentCount = WebGLGetComponentCount(glAttrib.glType); + + for (let j = 0; j < gpuInputAssembler.attributes.length; ++j) { + let attrib = gpuInputAssembler.attributes[j]; + if (glInput.name === attrib.name && attrib.stream < gpuInputAssembler.gpuVertexBuffers.length) { + + let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[attrib.stream]; + glAttrib.count = GFXFormatInfos[attrib.format].count; + glAttrib.stride = gpuBuffer.stride; + glAttrib.glBuffer = gpuBuffer.glBuffer; + glAttrib.isInstanced = attrib.isInstanced; + + glAttrib.offset = offsets[attrib.stream]; + offsets[attrib.stream] += glInput.size; + break; + } + } + } + } +} + +export function WebGLCmdFuncDestroyInputAssembler(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { +} + +export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { + + let gl: WebGLRenderingContext = device.gl; + + let beginRenderPassCmdIdx = 0; + let bindPipelineStateCmdIdx = 0; + let bindBindingSetLayoutCmdIdx = 0; + let bindInputAssemblerCmdIdx = 0; + let drawCmdIdx = 0; + let updateBufferCmdIdx = 0; + + let gpuShader: WebGLGPUShader | null = null; + let gpuInputAssembler: WebGLGPUInputAssembler | null = null; + let glPrimitive = WebGLRenderingContext.TRIANGLES; + + for (let i = 0; i < cmdPackage.cmds.length; ++i) { + switch (cmdPackage.cmds[i]) { + case WebGLCmd.BEGIN_RENDER_PASS: { + let cmd = cmdPackage.beginRenderPassCmds[beginRenderPassCmdIdx++]; + //curGPUFramebuffer = cmd.gpuFramebuffer; + + let clears: GLbitfield = 0; + + if (cmd.gpuFramebuffer) { + if (device.stateCache.glFramebuffer !== cmd.gpuFramebuffer.glFramebuffer) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, cmd.gpuFramebuffer.glFramebuffer); + device.stateCache.glFramebuffer = cmd.gpuFramebuffer.glFramebuffer; + } + + if (device.stateCache.viewport[0] !== cmd.viewport[0] || + device.stateCache.viewport[1] !== cmd.viewport[1] || + device.stateCache.viewport[2] !== cmd.viewport[2] || + device.stateCache.viewport[3] !== cmd.viewport[3]) { + + gl.viewport(cmd.viewport[0], cmd.viewport[1], cmd.viewport[2], cmd.viewport[3]); + + device.stateCache.viewport[0] = cmd.viewport[0]; + device.stateCache.viewport[1] = cmd.viewport[1]; + device.stateCache.viewport[2] = cmd.viewport[2]; + device.stateCache.viewport[3] = cmd.viewport[3]; + } + + if (device.stateCache.scissorRect[0] !== cmd.viewport[0] || + device.stateCache.scissorRect[1] !== cmd.viewport[1] || + device.stateCache.scissorRect[2] !== cmd.viewport[2] || + device.stateCache.scissorRect[3] !== cmd.viewport[3]) { + + gl.scissor(cmd.viewport[0], cmd.viewport[1], cmd.viewport[2], cmd.viewport[3]); + + device.stateCache.scissorRect[0] = cmd.viewport[0]; + device.stateCache.scissorRect[1] = cmd.viewport[1]; + device.stateCache.scissorRect[2] = cmd.viewport[2]; + device.stateCache.scissorRect[3] = cmd.viewport[3]; + } + + let curGPURenderPass = cmd.gpuFramebuffer.gpuRenderPass; + + let invalidateAttachments: GLenum[] = [0, 0, 0, 0]; + let numInvalidAttach = 0; + + if (curGPURenderPass.colorAttachments.length > 0) { + let colorAttachment = curGPURenderPass.colorAttachments[0]; + + if (colorAttachment.format !== GFXFormat.UNKNOWN) { + switch (colorAttachment.loadOp) { + case GFXLoadOp.LOAD: break; // GL default behaviour + case GFXLoadOp.CLEAR: { + + if (device.stateCache.bs.targets[0].colorWriteMask !== GFXColorMask.ALL) { + gl.colorMask(true, true, true, true); + } + + gl.clearColor(cmd.clearColors[0], cmd.clearColors[1], cmd.clearColors[2], cmd.clearColors[3]); + clears |= WebGLRenderingContext.COLOR_BUFFER_BIT; + + break; + } + case GFXLoadOp.DISCARD: { + // invalidate the framebuffer + invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.COLOR_ATTACHMENT0; + break; + } + default: ; + } + } + } // if (curGPURenderPass) + + if (curGPURenderPass.depthStencilAttachment) { + + if (curGPURenderPass.depthStencilAttachment.format !== GFXFormat.UNKNOWN) { + switch (curGPURenderPass.depthStencilAttachment.depthLoadOp) { + case GFXLoadOp.LOAD: break; // GL default behaviour + case GFXLoadOp.CLEAR: { + + if (!device.stateCache.dss.isWriteDepth) { + gl.depthMask(true); + } + + gl.clearDepth(cmd.clearDepth); + + clears |= WebGLRenderingContext.DEPTH_BUFFER_BIT; + + break; + } + case GFXLoadOp.DISCARD: { + // invalidate the framebuffer + invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.DEPTH_ATTACHMENT; + break; + } + default: ; + } + + if (GFXFormatInfos[curGPURenderPass.depthStencilAttachment.format].hasStencil) { + switch (curGPURenderPass.depthStencilAttachment.stencilLoadOp) { + case GFXLoadOp.LOAD: break; // GL default behaviour + case GFXLoadOp.CLEAR: { + + if (!device.stateCache.dss.frontStencilWriteMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0xFFFFFFFF); + } + + if (!device.stateCache.dss.backStencilWriteMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0xFFFFFFFF); + } + + gl.clearStencil(cmd.clearStencil); + clears |= WebGLRenderingContext.STENCIL_BUFFER_BIT; + + break; + } + case GFXLoadOp.DISCARD: { + // invalidate the framebuffer + invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.STENCIL_ATTACHMENT; + break; + } + default: ; + } + } + } + } // if (curGPURenderPass.depthStencilAttachment) + + /* + if (numInvalidAttach) { + gl.invalidateFramebuffer(WebGLRenderingContext.FRAMEBUFFER, numInvalidAttach, invalidateAttachments); + } + */ + + if (clears) { + gl.clear(clears); + } + + // restore states + if (clears & WebGLRenderingContext.COLOR_BUFFER_BIT) { + + let colorMask = device.stateCache.bs.targets[0].colorWriteMask; + if (colorMask !== GFXColorMask.ALL) { + let r = (colorMask & GFXColorMask.R) != GFXColorMask.NONE; + let g = (colorMask & GFXColorMask.G) != GFXColorMask.NONE; + let b = (colorMask & GFXColorMask.B) != GFXColorMask.NONE; + let a = (colorMask & GFXColorMask.A) != GFXColorMask.NONE; + gl.colorMask(r, g, b, a); + } + } + + if ((clears & WebGLRenderingContext.DEPTH_BUFFER_BIT) && + !device.stateCache.dss.isWriteDepth) { + gl.depthMask(false); + } + + if (clears & WebGLRenderingContext.STENCIL_BUFFER_BIT) { + if (!device.stateCache.dss.frontStencilWriteMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0); + } + + if (!device.stateCache.dss.backStencilWriteMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0); + } + } + } // if (curGPURenderPass) + + break; + } + case WebGLCmd.END_RENDER_PASS: { + // WebGL 1.0 doesn't support store operation of attachments. + // GFXStoreOp.Store is the default GL behaviour. + break; + } + case WebGLCmd.BIND_PIPELINE_STATE: { + + let cmd = cmdPackage.bindPipelineStateCmds[bindPipelineStateCmdIdx++]; + if (cmd.gpuPipelineState) { + + glPrimitive = cmd.gpuPipelineState.glPrimitive; + + if (cmd.gpuPipelineState.gpuShader) { + + let glProgram = cmd.gpuPipelineState.gpuShader.glProgram; + if (device.stateCache.glProgram !== glProgram) { + gl.useProgram(glProgram); + device.stateCache.glProgram = glProgram; + } + + gpuShader = cmd.gpuPipelineState.gpuShader; + } + + // rasterizater state + let rs = cmd.gpuPipelineState.rs; + if (rs) { + + if (device.stateCache.rs.cullMode !== rs.cullMode) { + switch (rs.cullMode) { + case GFXCullMode.NONE: { + gl.disable(WebGLRenderingContext.CULL_FACE); + break; + } + case GFXCullMode.FRONT: { + gl.enable(WebGLRenderingContext.CULL_FACE); + gl.cullFace(WebGLRenderingContext.FRONT); + break; + } + case GFXCullMode.BACK: { + gl.enable(WebGLRenderingContext.CULL_FACE); + gl.cullFace(WebGLRenderingContext.BACK); + break; + } + default: ; + } + + device.stateCache.rs.cullMode = rs.cullMode; + } + + if (device.stateCache.rs.isFrontFaceCCW !== rs.isFrontFaceCCW) { + gl.frontFace(rs.isFrontFaceCCW ? WebGLRenderingContext.CCW : WebGLRenderingContext.CW); + device.stateCache.rs.isFrontFaceCCW = rs.isFrontFaceCCW; + } + + if ((device.stateCache.rs.depthBias !== rs.depthBias) || + (device.stateCache.rs.depthBiasFactor !== rs.depthBiasFactor)) { + gl.polygonOffset(rs.depthBiasFactor, rs.depthBias); + device.stateCache.rs.depthBias = rs.depthBias; + device.stateCache.rs.depthBiasFactor = rs.depthBiasFactor; + } + + if (device.stateCache.rs.lineWidth !== rs.lineWidth) { + gl.lineWidth(rs.lineWidth); + device.stateCache.rs.lineWidth = rs.lineWidth; + } + } // rasterizater state + + // depth-stencil state + let dss = cmd.gpuPipelineState.dss; + if (dss) { + + if (device.stateCache.dss.isDepthTest !== dss.isDepthTest) { + if (dss.isDepthTest) { + gl.enable(WebGLRenderingContext.DEPTH_TEST); + } else { + gl.disable(WebGLRenderingContext.DEPTH_TEST); + } + device.stateCache.dss.isDepthTest = dss.isDepthTest; + } + + if (device.stateCache.dss.isWriteDepth !== dss.isWriteDepth) { + gl.depthMask(dss.isWriteDepth); + device.stateCache.dss.isWriteDepth = dss.isWriteDepth; + } + + if (device.stateCache.dss.depthFunc !== dss.depthFunc) { + gl.depthFunc(WebGLCmpFuncs[dss.depthFunc]); + device.stateCache.dss.depthFunc = dss.depthFunc; + } + + // front + if ((device.stateCache.dss.isFrontStencilTest !== dss.isFrontStencilTest) || + (device.stateCache.dss.isBackStencilTest !== dss.isBackStencilTest)) { + if (dss.isFrontStencilTest || dss.isBackStencilTest) { + gl.enable(WebGLRenderingContext.STENCIL_TEST); + } else { + gl.disable(WebGLRenderingContext.STENCIL_TEST); + } + device.stateCache.dss.isFrontStencilTest = dss.isFrontStencilTest; + device.stateCache.dss.isBackStencilTest = dss.isBackStencilTest; + } + + if ((device.stateCache.dss.frontStencilFunc !== dss.frontStencilFunc) || + (device.stateCache.dss.frontStencilRef !== dss.frontStencilRef) || + (device.stateCache.dss.frontStencilReadMask !== dss.frontStencilReadMask)) { + + gl.stencilFuncSeparate( + WebGLRenderingContext.FRONT, + WebGLCmpFuncs[dss.frontStencilFunc], + dss.frontStencilRef, + dss.frontStencilReadMask); + + device.stateCache.dss.frontStencilFunc = dss.frontStencilFunc; + device.stateCache.dss.frontStencilRef = dss.frontStencilRef; + device.stateCache.dss.frontStencilReadMask = dss.frontStencilReadMask; + } + + if ((device.stateCache.dss.frontStencilFailOp !== dss.frontStencilFailOp) || + (device.stateCache.dss.frontStencilDepthFailOp !== dss.frontStencilDepthFailOp) || + (device.stateCache.dss.frontStencilPassOp !== dss.frontStencilPassOp)) { + + gl.stencilOpSeparate( + WebGLRenderingContext.FRONT, + WebGLStencilOps[dss.frontStencilFailOp], + WebGLStencilOps[dss.frontStencilDepthFailOp], + WebGLStencilOps[dss.frontStencilPassOp]); + + device.stateCache.dss.frontStencilFailOp = dss.frontStencilFailOp; + device.stateCache.dss.frontStencilDepthFailOp = dss.frontStencilDepthFailOp; + device.stateCache.dss.frontStencilPassOp = dss.frontStencilPassOp; + } + + if (device.stateCache.dss.frontStencilWriteMask !== dss.frontStencilWriteMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, dss.frontStencilWriteMask); + device.stateCache.dss.frontStencilWriteMask = dss.frontStencilWriteMask; + } + + // back + if ((device.stateCache.dss.backStencilFunc !== dss.backStencilFunc) || + (device.stateCache.dss.backStencilRef !== dss.backStencilRef) || + (device.stateCache.dss.backStencilReadMask !== dss.backStencilReadMask)) { + + gl.stencilFuncSeparate( + WebGLRenderingContext.BACK, + WebGLCmpFuncs[dss.backStencilFunc], + dss.backStencilRef, + dss.backStencilReadMask); + + device.stateCache.dss.backStencilFunc = dss.backStencilFunc; + device.stateCache.dss.backStencilRef = dss.backStencilRef; + device.stateCache.dss.backStencilReadMask = dss.backStencilReadMask; + } + + if ((device.stateCache.dss.backStencilFailOp !== dss.backStencilFailOp) || + (device.stateCache.dss.backStencilDepthFailOp !== dss.backStencilDepthFailOp) || + (device.stateCache.dss.backStencilPassOp !== dss.backStencilPassOp)) { + + gl.stencilOpSeparate( + WebGLRenderingContext.BACK, + WebGLStencilOps[dss.backStencilFailOp], + WebGLStencilOps[dss.backStencilDepthFailOp], + WebGLStencilOps[dss.backStencilPassOp]); + + device.stateCache.dss.backStencilFailOp = dss.backStencilFailOp; + device.stateCache.dss.backStencilDepthFailOp = dss.backStencilDepthFailOp; + device.stateCache.dss.backStencilPassOp = dss.backStencilPassOp; + } + + if (device.stateCache.dss.backStencilWriteMask !== dss.backStencilWriteMask) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, dss.backStencilWriteMask); + device.stateCache.dss.backStencilWriteMask = dss.backStencilWriteMask; + } + } // depth-stencil state + + // blend state + let bs = cmd.gpuPipelineState.bs; + if (bs) { + + if (device.stateCache.bs.isA2C !== bs.isA2C) { + if (bs.isA2C) { + gl.enable(WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE); + } else { + gl.disable(WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE); + } + device.stateCache.bs.isA2C = bs.isA2C; + } + + if ((device.stateCache.bs.factor[0] !== bs.factor[0]) || + (device.stateCache.bs.factor[1] !== bs.factor[1]) || + (device.stateCache.bs.factor[2] !== bs.factor[2]) || + (device.stateCache.bs.factor[3] !== bs.factor[3])) { + + gl.blendColor(bs.factor[0], bs.factor[1], bs.factor[2], bs.factor[3]); + + device.stateCache.bs.factor[0] = bs.factor[0]; + device.stateCache.bs.factor[1] = bs.factor[1]; + device.stateCache.bs.factor[2] = bs.factor[2]; + device.stateCache.bs.factor[3] = bs.factor[3]; + } + + let target0 = bs.targets[0]; + let catchTarget0 = device.stateCache.bs.targets[0]; + + if (catchTarget0.isBlend !== target0.isBlend) { + if (target0.isBlend) { + gl.enable(WebGLRenderingContext.BLEND); + } else { + gl.disable(WebGLRenderingContext.BLEND); + } + catchTarget0.isBlend = target0.isBlend; + } + + if ((catchTarget0.blendOp !== target0.blendOp) || + (catchTarget0.alphBlendOp !== target0.alphBlendOp)) { + + gl.blendEquationSeparate(WebGLBlendOps[target0.blendOp], WebGLBlendOps[target0.alphBlendOp]); + + catchTarget0.blendOp = target0.blendOp; + catchTarget0.alphBlendOp = target0.alphBlendOp; + } + + if ((catchTarget0.srcBlend !== target0.srcBlend) || + (catchTarget0.dstBlend !== target0.dstBlend) || + (catchTarget0.srcAlphaBlend !== target0.srcAlphaBlend) || + (catchTarget0.dstAlphaBlend !== target0.dstAlphaBlend)) { + + gl.blendFuncSeparate( + WebGLBlendFactors[target0.srcBlend], + WebGLBlendFactors[target0.dstBlend], + WebGLBlendFactors[target0.srcAlphaBlend], + WebGLBlendFactors[target0.dstAlphaBlend]); + + catchTarget0.srcBlend = target0.srcBlend; + catchTarget0.dstBlend = target0.dstBlend; + catchTarget0.srcAlphaBlend = target0.srcAlphaBlend; + catchTarget0.dstAlphaBlend = target0.dstAlphaBlend; + } + + if (catchTarget0.colorWriteMask !== target0.colorWriteMask) { + + gl.colorMask( + (target0.colorWriteMask & GFXColorMask.R) !== GFXColorMask.NONE, + (target0.colorWriteMask & GFXColorMask.G) !== GFXColorMask.NONE, + (target0.colorWriteMask & GFXColorMask.B) !== GFXColorMask.NONE, + (target0.colorWriteMask & GFXColorMask.A) !== GFXColorMask.NONE); + + catchTarget0.colorWriteMask = target0.colorWriteMask; + } + } // blend state + } + + break; + } + case WebGLCmd.BIND_BINDING_SET_LAYOUT: { + + let cmd = cmdPackage.bindBindingSetLayoutCmds[bindBindingSetLayoutCmdIdx++]; + if (cmd.gpuBindingSetLayout && gpuShader) { + for (let n = 0; n < cmd.gpuBindingSetLayout.gpuBinding.length; ++n) { + let gpuBinding = cmd.gpuBindingSetLayout.gpuBinding[n]; + + switch (gpuBinding.type) { + case GFXBindingType.UNIFORM_BUFFER: { + + if (gpuBinding.gpuBuffer && gpuBinding.gpuBuffer.buffer) { + + let glBlock: WebGLGPUUniformBlock | null = null; + + for (let b = 0; b < gpuShader.glBlocks.length; ++b) { + if (gpuShader.glBlocks[b].binding === gpuBinding.binding) { + glBlock = gpuShader.glBlocks[b]; + break; + } + } + + if (glBlock && glBlock.bufferView) { + for (let u = 0; u < glBlock.glUniforms.length; ++u) { + let glUniform = glBlock.glUniforms[u]; + if (glUniform.glLoc >= 0 && + glBlock.bufferView.compare(gpuBinding.gpuBuffer.buffer, glUniform.offset, glUniform.size, glUniform.offset, glUniform.size) != 0) { + + switch (glUniform.glType) { + case WebGLRenderingContext.BOOL: + case WebGLRenderingContext.INT: { + gl.uniform1iv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.BOOL_VEC2: + case WebGLRenderingContext.INT_VEC2: { + gl.uniform2iv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.BOOL_VEC3: + case WebGLRenderingContext.INT_VEC3: { + gl.uniform3iv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.BOOL_VEC4: + case WebGLRenderingContext.INT_VEC4: { + gl.uniform4iv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT: { + gl.uniform1fv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT_VEC2: { + gl.uniform2fv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT_VEC3: { + gl.uniform3fv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT_VEC4: { + gl.uniform4fv(glUniform.glLoc, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT_MAT2: { + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT_MAT3: { + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + break; + } + case WebGLRenderingContext.FLOAT_MAT4: { + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + break; + } + default: ; + } + } // if + } + } + } // if + break; + } + } + } + } + + break; + } + case WebGLCmd.BIND_INPUT_ASSEMBLER: { + let cmd = cmdPackage.bindInputAssemblerCmds[bindInputAssemblerCmdIdx++]; + gpuInputAssembler = cmd.gpuInputAssembler; + break; + } + case WebGLCmd.DRAW: { + if (gpuInputAssembler) { + let cmd = cmdPackage.drawCmds[drawCmdIdx++]; + + for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { + device.stateCache.glCurrentAttribLocs[a] = false; + } + + for (let a = 0; a < gpuInputAssembler.glAttribs.length; ++a) { + let glAttrib = gpuInputAssembler.glAttribs[a]; + + if (device.stateCache.glArrayBuffer !== glAttrib.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, glAttrib.glBuffer); + device.stateCache.glArrayBuffer = glAttrib.glBuffer; + } + + for (let c = 0; c < glAttrib.componentCount; ++c) { + let glLoc = glAttrib.glLoc + c; + let offset = glAttrib.offset + glAttrib.size * c; + + if (!device.stateCache.glEnabledAttribLocs[a]) { + gl.enableVertexAttribArray(glLoc); + device.stateCache.glEnabledAttribLocs[a] = true; + } + device.stateCache.glCurrentAttribLocs[a] = true; + + gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, offset); + } + } + + for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { + if (device.stateCache.glEnabledAttribLocs[a] != device.stateCache.glCurrentAttribLocs[a]) { + gl.disableVertexAttribArray(a); + device.stateCache.glEnabledAttribLocs[a] = false; + } + } + + if (gpuInputAssembler.gpuIndexBuffer && cmd.indexCount > 0) { + let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + let offset = cmd.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, cmd.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, cmd.firstVertex, cmd.vertexCount); + } + } + break; + } + case WebGLCmd.UPDATE_BUFFER: { + + let cmd = cmdPackage.updateBufferCmds[updateBufferCmdIdx++]; + if (cmd.gpuBuffer) { + switch (cmd.gpuBuffer.glTarget) { + case WebGLRenderingContext.ARRAY_BUFFER: { + if (device.stateCache.glArrayBuffer !== cmd.gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, cmd.gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = cmd.gpuBuffer.glBuffer; + } + break; + } + case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { + if (device.stateCache.glElementArrayBuffer !== cmd.gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, cmd.gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = cmd.gpuBuffer.glBuffer; + } + break; + } + default: { + console.error("Unsupported GFXBufferType, update buffer failed."); + continue; + } + } + + if (cmd.data) { + gl.bufferSubData(cmd.gpuBuffer.glTarget, cmd.offset, cmd.data); + } + } + + break; + } + } + } +} diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts b/cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts new file mode 100644 index 0000000000..f9667355ff --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts @@ -0,0 +1,55 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGPUBindingSetLayout } from './webgl-gpu-objects'; +import { GFXBindingSetLayout, GFXBindingSetLayoutInfo, GFXBindingType } from '../gfx-binding-set-layout'; +import { GFXBuffer } from '../gfx-buffer'; +import { GFXSampler } from '../gfx-sampler'; +import { GFXTextureView } from '../gfx-texture-view'; + +export class WebGLGFXBindingSetLayout extends GFXBindingSetLayout { + + constructor(device: GFXDevice) { + super(device); + } + + public initialize(info: GFXBindingSetLayoutInfo): boolean { + + for (let i = 0; i < info.bindings.length; ++i) { + let binding = info.bindings[i]; + + this._bindingUnits.push({ + binding: binding.binding, + type: binding.type, + name: binding.name, + buffer: null, + texView: null, + sampler: null, + }); + } + + this._gpuBindingSetLayout = this.webGLDevice.emitCmdCreateGPUBindingSetLayout(info); + + return true; + } + + public destroy() { + if (this._gpuBindingSetLayout) { + this.webGLDevice.emitCmdDestroyGPUBindingSetLayout(this._gpuBindingSetLayout); + this._gpuBindingSetLayout = null; + } + } + + public update() { + + } + + public get webGLDevice(): WebGLGFXDevice { + return this._device; + } + + public get gpuBindingSetLayout(): WebGLGPUBindingSetLayout | null { + return this._gpuBindingSetLayout; + } + + private _gpuBindingSetLayout: WebGLGPUBindingSetLayout | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts index d3ad89de4f..afd0528b18 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts @@ -5,11 +5,11 @@ import { WebGLGFXDevice } from './webgl-gfx-device'; export class WebGLGFXBuffer extends GFXBuffer { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXBufferInfo) : boolean { + public initialize(info: GFXBufferInfo): boolean { this._usage = info.usage; this._memUsage = info.memUsage; @@ -17,46 +17,48 @@ export class WebGLGFXBuffer extends GFXBuffer { this._stride = info.stride; if (this._memUsage & GFXMemoryUsageBit.HOST) { - this._buffer = new ArrayBuffer(this._size); + this._arrayBuffer = new ArrayBuffer(this._size); + this._buffer = new Buffer(this._arrayBuffer); } this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; - if (!this._isSimulate) { - this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info); + if (!this._isSimulate || this._usage & GFXBufferUsageBit.UNIFORM) { + this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); } return true; } public destroy() { - if(this._gpuBuffer) { + if (this._gpuBuffer) { this.webGLDevice.emitCmdDestroyGPUBuffer(this._gpuBuffer); - this._buffer = null; + this._gpuBuffer = null; + } + + this._arrayBuffer = null; + this._buffer = null; + } + + public update(buffer: Buffer, offset: number) { + + if (this._buffer) { + this._buffer.set(buffer, offset); + } + + if (!this._isSimulate && this._buffer) { + this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, this._buffer); } } - public update(buffer : ArrayBuffer, offset : number) { - - if(this._buffer) { - let srcView : Uint8Array = new Uint8Array(buffer); - let dstView : Uint8Array = new Uint8Array(this._buffer, offset); - dstView.set(srcView); - } - - if(!this._isSimulate) { - this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, this._buffer); - } - } - - public get webGLDevice() : WebGLGFXDevice { + public get webGLDevice(): WebGLGFXDevice { return this._device; } - public get gpuBuffer() : WebGLGPUBuffer | null { + public get gpuBuffer(): WebGLGPUBuffer | null { return this._gpuBuffer; } - private _gpuBuffer : WebGLGPUBuffer | null = null; - private _isSimulate : boolean = false; + private _gpuBuffer: WebGLGPUBuffer | null = null; + private _isSimulate: boolean = false; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts b/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts index 94499b104b..615627a5a1 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts @@ -1,19 +1,65 @@ import { GFXDevice } from '../gfx-device'; import { GFXCommandAllocator } from '../gfx-command-allocator'; +import { WebGLCmdUpdateBuffer, WebGLCmdBeginRenderPass, WebGLCmdBindInputAssembler, WebGLCmdDraw, WebGLCmdBindPipelineState, WebGLCmdBindBindingSetLayout } from './webgl-commands'; export class WebGLGFXCommandPool { - constructor(size: number) { - this._commands = new Array(size); + constructor(count: number, increase : number) { + this._frees = new Array(count); + this._freeIdx = count - 1; + this._increase = increase; } - private _commands : T[]; + alloc(clazz: new() => T) : T | null { + + if (this._freeIdx <= 0) { + let size = this._frees.length + this._increase; + let temp = this._frees; + this._frees = new Array(size); + + for(let i = 0; i < temp.length; ++i) { + this._frees[i] = temp[i]; + } + + for(let i = temp.length + 1; i < size; ++i) { + this._frees[i] = new clazz(); + } + + this._freeIdx += (size - temp.length); + } + + let item = this._frees[this._freeIdx]; + this._frees[this._freeIdx--] = null; + + return item; + } + + free(cmd : T) { + this._frees[++this._freeIdx] = cmd; + } + + private _frees : (T|null)[]; + private _freeIdx : number = 0; + private _increase : number = 0; }; -export class GFXWebGLCommandAllocator extends GFXCommandAllocator { +export class WebGLGFXCommandAllocator extends GFXCommandAllocator { + + beginRenderPassCmdPool : WebGLGFXCommandPool; + bindPipelineStateCmdPool : WebGLGFXCommandPool; + bindBindingSetLayoutCmdPool : WebGLGFXCommandPool; + bindInputAssemblerCmdPool : WebGLGFXCommandPool; + drawCmdPool : WebGLGFXCommandPool; + updateBufferCmdPool : WebGLGFXCommandPool; constructor(device : GFXDevice) { super(device); + this.beginRenderPassCmdPool = new WebGLGFXCommandPool(64, 32); + this.bindPipelineStateCmdPool = new WebGLGFXCommandPool(64, 32); + this.bindBindingSetLayoutCmdPool = new WebGLGFXCommandPool(64, 32); + this.bindInputAssemblerCmdPool = new WebGLGFXCommandPool(64, 32); + this.drawCmdPool = new WebGLGFXCommandPool(64, 32); + this.updateBufferCmdPool = new WebGLGFXCommandPool(64, 32); } public initialize() : boolean { @@ -21,7 +67,7 @@ export class GFXWebGLCommandAllocator extends GFXCommandAllocator { return true; } - public destroy() : void { + public destroy() { } }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts new file mode 100644 index 0000000000..abd0edb1a1 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts @@ -0,0 +1,136 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXCommandBuffer, GFXCommandBufferInfo } from '../gfx-command-buffer'; +import { GFXBuffer } from '../gfx-buffer'; +import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw } from './webgl-commands'; +import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGFXBuffer } from './webgl-gfx-buffer'; +import { GFXFramebuffer } from '../gfx-framebuffer'; +import { WebGLGFXFramebuffer } from './webgl-gfx-framebuffer'; +import { GFXInputAssembler } from '../gfx-input-assembler'; +import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; +import { GFXPipelineState } from '../gfx-pipeline-state'; +import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; +import { WebGLGFXPipelineState } from './webgl-gfx-pipeline-state'; +import { GFXBindingSetLayout } from '../gfx-binding-set-layout'; + +export class WebGLGFXCommandBuffer extends GFXCommandBuffer { + + cmdPackage : WebGLCmdPackage = new WebGLCmdPackage; + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXCommandBufferInfo) : boolean { + + if(!info.allocator) { + return false; + } + + this._allocator = info.allocator; + this._type = info.type; + + return true; + } + + public destroy() { + if(this._allocator) { + this.cmdPackage.clearCmds(this._allocator); + } + } + + public begin() { + if(this._allocator) { + this.cmdPackage.clearCmds(this._allocator); + } + } + + public end() { + + } + + public beginRenderPass(framebuffer : GFXFramebuffer, viewport : number[], numClearColors : number, clearColors : number[], clearStencil : number) { + + let cmd = (this._allocator).beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); + if (cmd) { + cmd.gpuFramebuffer = (framebuffer).gpuFramebuffer; + cmd.viewport = viewport.slice(); + cmd.numClearColors = numClearColors; + cmd.clearColors = clearColors.slice(); + cmd.clearStencil = clearStencil; + this.cmdPackage.beginRenderPassCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS); + } + } + + public endRenderPass() { + + } + + public bindPipelineState(pipelineState : GFXPipelineState) { + + let cmd = (this._allocator).bindPipelineStateCmdPool.alloc(WebGLCmdBindPipelineState); + if (cmd) { + cmd.gpuPipelineState = (pipelineState).gpuPipelineState; + this.cmdPackage.bindPipelineStateCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.BIND_PIPELINE_STATE); + } + } + + public bindBindingSetLayout(bindingSetLayout : GFXBindingSetLayout) { + + // TODO + + } + + public bindInputAssembler(inputAssembler : GFXInputAssembler) { + + let cmd = (this._allocator).bindInputAssemblerCmdPool.alloc(WebGLCmdBindInputAssembler); + if (cmd) { + cmd.gpuInputAssembler = (inputAssembler).gpuInputAssembler; + this.cmdPackage.bindInputAssemblerCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.BIND_INPUT_ASSEMBLER); + } + } + + public draw(inputAssembler : GFXInputAssembler) { + let cmd = (this._allocator).drawCmdPool.alloc(WebGLCmdDraw); + if (cmd) { + cmd.vertexCount = inputAssembler.vertexCount; + cmd.firstVertex = inputAssembler.firstVertex; + cmd.indexCount = inputAssembler.indexCount; + cmd.firstIndex = inputAssembler.firstIndex; + cmd.vertexOffset = inputAssembler.vertexOffset; + cmd.instanceCount = inputAssembler.instanceCount; + cmd.firstInstance = inputAssembler.firstInstance; + + this.cmdPackage.drawCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.DRAW); + } + } + + public updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset : number) { + + let gpuBuffer = (buffer).gpuBuffer; + if(gpuBuffer) { + let cmd = (this._allocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); + if (cmd) { + cmd.gpuBuffer = gpuBuffer; + cmd.data = data.slice(0); + cmd.offset = offset; + this.cmdPackage.updateBufferCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); + } + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index 12b6066f8b..709b41c2e5 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -3,8 +3,8 @@ import { GFXBuffer, GFXBufferInfo } from '../gfx-buffer'; import { WebGLGFXBuffer } from './webgl-gfx-buffer'; import { WebGLGFXQueue } from './webgl-gfx-queue'; import { WebGLStateCache } from './webgl-state-cache'; -import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage } from './webgl-gpu-objects'; -import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader } from './webgl-commands'; +import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingSetLayout, WebGLGPUBinding } from './webgl-gpu-objects'; +import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncDestroyInputAssembler } from './webgl-commands'; import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit } from '../gfx-texture'; import { GFXTextureViewType, GFXTextureViewInfo } from '../gfx-texture-view'; import { GFXRenderPassInfo } from '../gfx-render-pass'; @@ -13,22 +13,50 @@ import { WebGLGFXRenderPass } from './webgl-gfx-render-pass'; import { WebGLGFXTextureView } from './webgl-gfx-texture-view'; import { WebGLGFXTexture } from './webgl-gfx-texture'; import { GFXShaderInfo } from '../gfx-shader'; +import { GFXSamplerInfo } from '../gfx-sampler'; +import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; +import { GFXInputAssemblerInfo } from '../gfx-input-assembler'; +import { WebGLGFXShader } from './webgl-gfx-shader'; +import { GFXCommandAllocator } from '../gfx-command-allocator'; +import { GFXPipelineStateInfo } from '../gfx-pipeline-state'; +import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; +import { GFXBindingSetLayoutInfo } from '../gfx-binding-set-layout'; + +const WebGLPrimitives: GLenum[] = [ + WebGLRenderingContext.POINTS, + WebGLRenderingContext.LINES, + WebGLRenderingContext.LINE_STRIP, + WebGLRenderingContext.LINE_LOOP, + WebGLRenderingContext.TRIANGLES, + WebGLRenderingContext.TRIANGLE_STRIP, + WebGLRenderingContext.TRIANGLE_FAN, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, + WebGLRenderingContext.NONE, +]; export class WebGLGFXDevice extends GFXDevice { - - stateCache : WebGLStateCache = new WebGLStateCache; - constructor(canvasEL : HTMLElement) { - + stateCache: WebGLStateCache = new WebGLStateCache; + webGLCmdAllocator: WebGLGFXCommandAllocator; + + constructor(canvasEL: HTMLElement) { + super(); + this.webGLCmdAllocator = new WebGLGFXCommandAllocator(this); + try { this._webGLRC = (canvasEL).getContext('webgl'); } catch (err) { console.error(err); return; } - + // No errors are thrown using try catch // Tested through ios baidu browser 4.14.1 if (!this._webGLRC) { @@ -36,24 +64,28 @@ export class WebGLGFXDevice extends GFXDevice { } } - public initialize(info : GFXDeviceInfo) : boolean { + public initialize(info: GFXDeviceInfo): boolean { return true; } - public destroy() : void { + public destroy(): void { } - public createBuffer() : GFXBuffer { + public createBuffer(): GFXBuffer { return new WebGLGFXBuffer(this); } - public getDeviceName() : string { + public createCommandAllocator(): GFXCommandAllocator { + return new WebGLGFXCommandAllocator(this); + } + + public getDeviceName(): string { return "WebGLDevice"; } - public get gl() : WebGLRenderingContext { + public get gl(): WebGLRenderingContext { return this._webGLRC; } @@ -61,18 +93,25 @@ export class WebGLGFXDevice extends GFXDevice { return this._queue; } - public emitCmdCreateGPUBuffer(info : GFXBufferInfo) : WebGLGPUBuffer { + public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer : Buffer | null): WebGLGPUBuffer | null { - let gpuBuffer : WebGLGPUBuffer = { - objType : WebGLGPUObjectType.BUFFER, - usage : info.usage, - memUsage : info.memUsage, - size : info.size, - stride : info.stride, - glTarget : 0, - glBuffer : 0, + let gpuBuffer: WebGLGPUBuffer = { + objType: WebGLGPUObjectType.BUFFER, + usage: info.usage, + memUsage: info.memUsage, + size: info.size, + stride: info.stride, + arrayBuffer: null, + buffer: null, + glTarget: 0, + glBuffer: 0, }; + if(buffer) { + gpuBuffer.arrayBuffer = buffer.buffer; + gpuBuffer.buffer = buffer; + } + // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; @@ -81,7 +120,7 @@ export class WebGLGFXDevice extends GFXDevice { return gpuBuffer; } - public emitCmdDestroyGPUBuffer(gpuBuffer : WebGLGPUBuffer) { + public emitCmdDestroyGPUBuffer(gpuBuffer: WebGLGPUBuffer) { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; @@ -89,25 +128,25 @@ export class WebGLGFXDevice extends GFXDevice { WebGLCmdFuncDestroyBuffer(this, gpuBuffer); } - public emitCmdUpdateGPUBuffer(gpuBuffer : WebGLGPUBuffer, offset : number, data : ArrayBuffer) { + public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: Buffer) { // TODO: Async - WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, data); + WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, buffer); } - public emitCmdCreateGPUTexture(info : GFXTextureInfo) : WebGLGPUTexture { + public emitCmdCreateGPUTexture(info: GFXTextureInfo): WebGLGPUTexture { + + let viewType: GFXTextureViewType; - let viewType : GFXTextureViewType; - switch (info.type) { - case GFXTextureType.TEX1D : { - viewType = info.arrayLayer <= 1? GFXTextureViewType.TV1D : GFXTextureViewType.TV1D_ARRAY; + case GFXTextureType.TEX1D: { + viewType = info.arrayLayer <= 1 ? GFXTextureViewType.TV1D : GFXTextureViewType.TV1D_ARRAY; break; } - case GFXTextureType.TEX2D : { - - if(info.arrayLayer <= 1) { + case GFXTextureType.TEX2D: { + + if (info.arrayLayer <= 1) { viewType = GFXTextureViewType.TV2D; - } else if(info.arrayLayer === 6 && (info.flags & GFXTextureFlagBit.CUBEMAP)) { + } else if (info.arrayLayer === 6 && (info.flags & GFXTextureFlagBit.CUBEMAP)) { viewType = GFXTextureViewType.CUBE; } else { viewType = GFXTextureViewType.TV2D_ARRAY; @@ -115,7 +154,7 @@ export class WebGLGFXDevice extends GFXDevice { break; } - case GFXTextureType.TEX3D : { + case GFXTextureType.TEX3D: { viewType = GFXTextureViewType.TV3D; break; } @@ -124,25 +163,25 @@ export class WebGLGFXDevice extends GFXDevice { } } - let gpuTexture : WebGLGPUTexture = { - objType : WebGLGPUObjectType.TEXTURE, - type : info.type, - viewType : viewType, - format : info.format, - usage : info.usage, - width : info.width, - height : info.height, - depth : info.depth, - arrayLayer : info.arrayLayer, - mipLevel : info.mipLevel, - flags : info.flags, + let gpuTexture: WebGLGPUTexture = { + objType: WebGLGPUObjectType.TEXTURE, + type: info.type, + viewType: viewType, + format: info.format, + usage: info.usage, + width: info.width, + height: info.height, + depth: info.depth, + arrayLayer: info.arrayLayer, + mipLevel: info.mipLevel, + flags: info.flags, - glTarget : 0, - glInternelFmt : 0, - glFormat : 0, - glType : 0, - glUsage : 0, - glTexture : 0, + glTarget: 0, + glInternelFmt: 0, + glFormat: 0, + glType: 0, + glUsage: 0, + glTexture: 0, }; // TODO: Async @@ -152,43 +191,46 @@ export class WebGLGFXDevice extends GFXDevice { return gpuTexture; } - public emitCmdDestroyGPUTexture(gpuTexture : WebGLGPUTexture) { + public emitCmdDestroyGPUTexture(gpuTexture: WebGLGPUTexture) { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; WebGLCmdFuncDestroyTexture(this, gpuTexture); } - public emitCmdCreateGPUTextureView(info : GFXTextureViewInfo) : WebGLGPUTextureView { + public emitCmdCreateGPUTextureView(info: GFXTextureViewInfo): WebGLGPUTextureView { let webGLTexture = info.texture; - let gpuTextureView : WebGLGPUTextureView = { - objType : WebGLGPUObjectType.TEXTURE_VIEW, - gpuTexture : webGLTexture.gpuTexture, - type : info.type, - format : info.format, - baseLevel : info.baseLevel, - levelCount : info.levelCount, + let gpuTextureView: WebGLGPUTextureView = { + objType: WebGLGPUObjectType.TEXTURE_VIEW, + gpuTexture: webGLTexture.gpuTexture, + type: info.type, + format: info.format, + baseLevel: info.baseLevel, + levelCount: info.levelCount, }; return gpuTextureView; } - public emitCmdCreateGPURenderPass(info : GFXRenderPassInfo) : WebGLGPURenderPass { - let gpuRenderPass : WebGLGPURenderPass = { - objType : WebGLGPUObjectType.RENDER_PASS, - colorInfos : info.colorInfos, - depthStencilInfo : info.depthStencilInfo, + public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { + let gpuRenderPass: WebGLGPURenderPass = { + objType: WebGLGPUObjectType.RENDER_PASS, + colorAttachments: info.colorInfos, + depthStencilAttachment: info.depthStencilInfo, } return gpuRenderPass; } - public emitCmdCreateGPUFramebuffer(info : GFXFramebufferInfo) : WebGLGPUFramebuffer { - + public emitCmdDestroyGPURenderPass(renderPass: WebGLGPURenderPass) { + } + + public emitCmdCreateGPUFramebuffer(info: GFXFramebufferInfo): WebGLGPUFramebuffer { + let renderPass = info.renderPass; - - let gpuColorViews : (WebGLGPUTextureView | null)[] = new Array(); + + let gpuColorViews: (WebGLGPUTextureView | null)[] = new Array(); for (let i = 0; i < info.colorViews.length; ++i) { let webGLColorView = info.colorViews[i]; @@ -197,13 +239,13 @@ export class WebGLGFXDevice extends GFXDevice { let webGLDSView = info.depthStencilView; - let gpuFramebuffer : WebGLGPUFramebuffer = { - objType : WebGLGPUObjectType.FRAMEBUFFER, - gpuRenderPass : renderPass.gpuRenderPass, - gpuColorViews : gpuColorViews, - gpuDepthStencilView : webGLDSView.gpuTextureView, - isOffscreen : info.isOffscreen, - glFramebuffer : 0, + let gpuFramebuffer: WebGLGPUFramebuffer = { + objType: WebGLGPUObjectType.FRAMEBUFFER, + gpuRenderPass: renderPass.gpuRenderPass, + gpuColorViews: gpuColorViews, + gpuDepthStencilView: webGLDSView.gpuTextureView, + isOffscreen: info.isOffscreen, + glFramebuffer: 0, }; // TODO: Async @@ -212,37 +254,62 @@ export class WebGLGFXDevice extends GFXDevice { return gpuFramebuffer; } - public emitCmdDestroyGPUFramebuffer(gpuFramebuffer : WebGLGPUFramebuffer) { + public emitCmdDestroyGPUFramebuffer(gpuFramebuffer: WebGLGPUFramebuffer) { // TODO: Async WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); } - public emitCmdCreateGPUShader(info : GFXShaderInfo) : WebGLGPUShader { + public emitCmdCreateGPUSampler(info: GFXSamplerInfo): WebGLGPUSampler { + let gpuSampler: WebGLGPUSampler = { + objType: WebGLGPUObjectType.FRAMEBUFFER, + minFilter: info.minFilter, + magFilter: info.magFilter, + mipFilter: info.minFilter, + addressU: info.addressU, + addressV: info.addressV, + addressW: info.addressW, + maxAnisotropy: info.maxAnisotropy, + cmpFunc: info.cmpFunc, + borderColor: info.borderColor, + minLOD: info.minLOD, + maxLOD: info.maxLOD, + mipLODBias: info.mipLODBias, + }; + + return gpuSampler; + } + + public emitCmdDestroyGPUSampler(gpuSampler: WebGLGPUSampler) { + // TODO: Async + } + + public emitCmdCreateGPUShader(info: GFXShaderInfo): WebGLGPUShader { let gpuStages: WebGLGPUShaderStage[] = []; - for(let i = 0; i < info.stages.length; ++i) { + for (let i = 0; i < info.stages.length; ++i) { let stage = info.stages[i]; gpuStages.push({ - type : stage.type, - source : stage.source, - macros : stage.macros, - glShader : 0, + type: stage.type, + source: stage.source, + macros: stage.macros, + glShader: 0, }); } - let gpuShader : WebGLGPUShader = { - objType : WebGLGPUObjectType.SHADER, - name : info.name, - bindings : info.bindings, + let gpuShader: WebGLGPUShader = { + objType: WebGLGPUObjectType.SHADER, + name: info.name, + bindings: info.bindings, + blocks: info.blocks, - gpuStages : gpuStages, - glProgram : 0, - glInputs : [], - glUniforms : [], - glBlocks : [], - glSamplers : [], + gpuStages: gpuStages, + glProgram: 0, + glInputs: [], + glUniforms: [], + glBlocks: [], + glSamplers: [], }; // TODO: Async @@ -251,11 +318,131 @@ export class WebGLGFXDevice extends GFXDevice { return gpuShader; } - public emitCmdDestroyGPUShader(gpuShader : WebGLGPUShader) { - + public emitCmdDestroyGPUShader(gpuShader: WebGLGPUShader) { // TODO: Async WebGLCmdFuncDestroyShader(this, gpuShader); } - private _webGLRC : WebGLRenderingContext | null = null; + public emitCmdCreateGPUPipelineState(info: GFXPipelineStateInfo): WebGLGPUPipelineState { + + let gpuShader: WebGLGPUShader | null = null; + if (info.shader) { + gpuShader = (info.shader).gpuShader; + } + + let gpuLayout: WebGLGPUPipelineLayout | null = null; + if (info.layout) { + gpuLayout = (info.layout).gpuPipelineLayout; + } + + let gpuRenderPass: WebGLGPURenderPass | null = null; + if (info.renderPass) { + gpuRenderPass = (info.renderPass).gpuRenderPass; + } + + let gpuPipelineState: WebGLGPUPipelineState = { + objType: WebGLGPUObjectType.PIPELINE_STATE, + glPrimitive: WebGLPrimitives[info.primitive], + gpuShader: gpuShader, + rs: info.rs, + dss: info.dss, + bs: info.bs, + gpuLayout: gpuLayout, + gpuRenderPass: gpuRenderPass, + }; + + return gpuPipelineState; + } + + public emitCmdDestroyGPUPipelineState(gpuPipelineState: WebGLGPUPipelineState) { + // TODO: Async + } + + public emitCmdCreateGPUBindingSetLayout(info: GFXBindingSetLayoutInfo): WebGLGPUBindingSetLayout { + + let gpuBindings: WebGLGPUBinding[] = new Array(info.bindings.length); + for (let i = 0; i < info.bindings.length; ++i) { + let binding = info.bindings[i]; + let gpuBinding = gpuBindings[i]; + gpuBinding.binding = binding.binding; + gpuBinding.type = binding.type; + gpuBinding.name = binding.name; + } + + let gpuBindingSetLayout: WebGLGPUBindingSetLayout = { + objType: WebGLGPUObjectType.BINDING_SET_LAYOUT, + gpuBinding: gpuBindings, + }; + + return gpuBindingSetLayout; + } + + public emitCmdDestroyGPUBindingSetLayout(gpuBindingSetLayout: WebGLGPUBindingSetLayout) { + // TODO: Async + } + + public emitCmdUpdateGPUBindingSetLayout(gpuBindingSetLayout: WebGLGPUBindingSetLayout) { + // TODO: Async + + + } + + public emitCmdCreateGPUInputAssembler(info: GFXInputAssemblerInfo): WebGLGPUInputAssembler { + + let gpuShader: WebGLGPUShader | null = null; + + if (info.shader) { + gpuShader = (info.shader).gpuShader; + } + + let gpuVertexBuffers: WebGLGPUBuffer[] = new Array(info.vertexBuffers.length); + + for (let i = 0; i < info.vertexBuffers.length; ++i) { + let vb = info.vertexBuffers[i]; + if (vb.gpuBuffer) { + gpuVertexBuffers[i] = vb.gpuBuffer; + } + } + + let gpuIndexBuffer: WebGLGPUBuffer | null = null; + + let glIndexType = 0; + if (info.indexBuffer) { + gpuIndexBuffer = (info.indexBuffer).gpuBuffer; + if (gpuIndexBuffer) { + switch (gpuIndexBuffer.stride) { + case 1: glIndexType = WebGLRenderingContext.UNSIGNED_BYTE; break; + case 2: glIndexType = WebGLRenderingContext.UNSIGNED_SHORT; break; + case 4: glIndexType = WebGLRenderingContext.UNSIGNED_INT; break; + default: { + console.error("Error index buffer stride."); + } + } + } + } + + let gpuInputAssembler: WebGLGPUInputAssembler = { + objType: WebGLGPUObjectType.INPUT_ASSEMBLER, + attributes: info.attributes, + gpuShader: gpuShader, + gpuVertexBuffers: gpuVertexBuffers, + gpuIndexBuffer: gpuIndexBuffer, + + glAttribs: [], + glIndexType: glIndexType, + glVAO: 0, + }; + + WebGLCmdFuncCreateInputAssember(this, gpuInputAssembler); + + // TODO: Async + return gpuInputAssembler; + } + + public emitCmdDestroyGPUInputAssembler(gpuInputAssembler: WebGLGPUInputAssembler) { + // TODO: Async + // WebGLCmdFuncDestroyInputAssembler(this, gpuInputAssembler); + } + + private _webGLRC: WebGLRenderingContext | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts index d5a789727d..ce5a68e4f9 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts @@ -33,5 +33,9 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { return this._device; } + public get gpuFramebuffer() : WebGLGPUFramebuffer | null { + return this._gpuFramebuffer; + } + private _gpuFramebuffer : WebGLGPUFramebuffer | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts b/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts new file mode 100644 index 0000000000..70d16886d8 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts @@ -0,0 +1,40 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXInputAssembler, GFXInputAssemblerInfo } from '../gfx-input-assembler'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGPUInputAssembler } from './webgl-gpu-objects'; + +export class WebGLGFXInputAssembler extends GFXInputAssembler { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXInputAssemblerInfo) : boolean { + + this._attributes = info.attributes; + this._vertexBuffers = info.vertexBuffers; + this._indexBuffer = info.indexBuffer; + this._isIndirect = info.isIndirect; + + this._gpuInputAssembler = this.webGLDevice.emitCmdCreateGPUInputAssembler(info); + + return true; + } + + public destroy() { + if(this._gpuInputAssembler) { + this.webGLDevice.emitCmdDestroyGPUInputAssembler(this._gpuInputAssembler); + this._gpuInputAssembler = null; + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + public get gpuInputAssembler() : WebGLGPUInputAssembler | null { + return this._gpuInputAssembler; + } + + private _gpuInputAssembler : WebGLGPUInputAssembler | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts b/cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts deleted file mode 100644 index 5b41266d2b..0000000000 --- a/cocos/renderer/gfx/webgl/webgl-gfx-input-state.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { GFXDevice } from '../gfx-device'; -import { WebGLGPUTexture } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { GFXFormatSurfaceSize } from '../gfx-define'; -import { GFXInputState, GFXInputStateInfo } from '../gfx-input-state'; - -export class WebGLGFXInputState extends GFXInputState { - - constructor(device : GFXDevice) { - super(device); - } - - public initialize(info : GFXInputStateInfo) : boolean { - - this._attributes = info.attributes; - - return true; - } - - public destroy() { - } -}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts new file mode 100644 index 0000000000..3a58074933 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts @@ -0,0 +1,32 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../gfx-pipeline-layout'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGPUPipelineLayout } from './webgl-gpu-objects'; + +export class WebGLGFXPipelineLayout extends GFXPipelineLayout { + + constructor(device: GFXDevice) { + super(device); + } + + public initialize(info: GFXPipelineLayoutInfo): boolean { + + this._pushConstantsRanges = info.pushConstantsRanges; + this._layouts = info.layouts; + + return true; + } + + public destroy() { + } + + public get webGLDevice(): WebGLGFXDevice { + return this._device; + } + + public get gpuPipelineLayout(): WebGLGPUPipelineLayout | null { + return this._gpuPipelineLayout; + } + + private _gpuPipelineLayout: WebGLGPUPipelineLayout | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts new file mode 100644 index 0000000000..e64dfcc6ec --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts @@ -0,0 +1,45 @@ +import { GFXDevice } from '../gfx-device'; +import { GFXPipelineState, GFXPipelineStateInfo } from '../gfx-pipeline-state'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGPUPipelineState } from './webgl-gpu-objects'; + +export class WebGLGFXPipelineState extends GFXPipelineState { + + constructor(device : GFXDevice) { + super(device); + } + + public initialize(info : GFXPipelineStateInfo) : boolean { + + this._primitive = info.primitive; + this._shader = info.shader; + this._is = info.is; + this._rs = info.rs; + this._dss = info.dss; + this._bs = info.bs; + this._layout = info.layout; + this._renderPass = info.renderPass; + + this._gpuPipelineState = this.webGLDevice.emitCmdCreateGPUPipelineState(info); + + return true; + } + + public destroy() { + if(this._gpuPipelineState) + { + this.webGLDevice.emitCmdDestroyGPUPipelineState(this._gpuPipelineState); + this._gpuPipelineState = null; + } + } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + public get gpuPipelineState() : WebGLGPUPipelineState | null { + return this._gpuPipelineState; + } + + private _gpuPipelineState : WebGLGPUPipelineState | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts b/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts index 1007da7839..30900e34a0 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts @@ -1,6 +1,9 @@ import { GFXDevice } from '../gfx-device'; import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; import { GFXCommandBuffer } from '../gfx-command-buffer'; +import { WebGLGFXCommandBuffer } from './webgl-gfx-command-buffer'; +import { WebGLCmdFuncExecuteCmds } from './webgl-commands'; +import { WebGLGFXDevice } from './webgl-gfx-device'; export class WebGLGFXQueue extends GFXQueue { @@ -19,10 +22,14 @@ export class WebGLGFXQueue extends GFXQueue { } - public submit(cmdBuffs: GFXCommandBuffer[], fence) { + public submit(cmdBuffs: GFXCommandBuffer[], fence : null = null) { - for(let cb in cmdBuffs) { - + // TODO: Async + if(!this._isAsync) { + for(let i = 0; i < cmdBuffs.length; ++i) { + let cmdBuff = cmdBuffs[i]; + WebGLCmdFuncExecuteCmds(this._device, cmdBuff.cmdPackage); + } } } diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts b/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts index 0d64ae4606..ed3c095443 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts @@ -7,28 +7,36 @@ import { GFXRenderPass, GFXRenderPassInfo } from '../gfx-render-pass'; export class WebGLGFXRenderPass extends GFXRenderPass { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXRenderPassInfo) : boolean { + public initialize(info: GFXRenderPassInfo): boolean { this._colorInfos = info.colorInfos; this._depthStencilInfo = info.depthStencilInfo; this._subPasses = info.subPasses; - this._gpuRenderPass = (this._device).emitCmdCreateGPURenderPass(info); + this._gpuRenderPass = this.webGLDevice.emitCmdCreateGPURenderPass(info); return true; } public destroy() { - this._gpuRenderPass = null; + + if (this._gpuRenderPass) { + this.webGLDevice.emitCmdDestroyGPURenderPass(this._gpuRenderPass); + this._gpuRenderPass = null; + } + } + + public get webGLDevice(): WebGLGFXDevice { + return this._device; } public get gpuRenderPass(): WebGLGPURenderPass { return this._gpuRenderPass; } - private _gpuRenderPass : WebGLGPURenderPass | null = null; + private _gpuRenderPass: WebGLGPURenderPass | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts b/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts index 28de03d116..cd76700db3 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts @@ -1,5 +1,7 @@ import { GFXDevice } from '../gfx-device'; import { GFXSampler, GFXSamplerInfo } from '../gfx-sampler'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGPUSampler } from './webgl-gpu-objects'; export class WebGLGFXSampler extends GFXSampler { @@ -22,9 +24,21 @@ export class WebGLGFXSampler extends GFXSampler { this._maxLOD = info.maxLOD; this._mipLODBias = info.mipLODBias; + this._gpuSampler = this.webGLDevice.emitCmdCreateGPUSampler(info); + return true; } public destroy() { + if(this._gpuSampler) { + this.webGLDevice.emitCmdDestroyGPUSampler(this._gpuSampler); + this._gpuSampler = null; + } } + + public get webGLDevice() : WebGLGFXDevice { + return this._device; + } + + private _gpuSampler : WebGLGPUSampler | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts b/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts index af0631eda8..1cf1045ec7 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts @@ -14,6 +14,7 @@ export class WebGLGFXShader extends GFXShader { this._name = info.name; this._stages = info.stages; this._bindings = info.bindings; + this._blocks = info.blocks; this._gpuShader = this.webGLDevice.emitCmdCreateGPUShader(info); diff --git a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts index 23ad99a8ff..619df2413a 100644 --- a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts @@ -1,11 +1,13 @@ import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from "../gfx-buffer"; import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit } from "../gfx-texture"; import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormat, GFX_MAX_VERTEX_ATTRIBUTES, GFXType } from "../gfx-define"; -import { GFXInputAttribute } from "../gfx-input-state"; -import { ColorAttachmentInfo, DepthStencilAttachmentInfo } from "../gfx-render-pass"; -import { GFXShaderType, GFXShaderMacro } from "../gfx-shader"; -import { GFXBinding } from "../gfx-binding-set-layout"; +import { GFXFormat, GFXType } from "../gfx-define"; +import { GFXColorAttachment, GFXDepthStencilAttachment } from "../gfx-render-pass"; +import { GFXShaderType, GFXShaderMacro, GFXUniformBlock } from "../gfx-shader"; +import { GFXBinding, GFXBindingType } from "../gfx-binding-set-layout"; +import { GFXFilter, GFXAddress } from "../gfx-sampler"; +import { GFXComparisonFunc, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; +import { GFXInputAttribute } from "../gfx-input-assembler"; export const enum WebGLGPUObjectType { UNKNOWN, @@ -14,57 +16,56 @@ export const enum WebGLGPUObjectType { TEXTURE_VIEW, RENDER_PASS, FRAMEBUFFER, + SAMPLER, SHADER, - INPUT_STATE, + PIPELINE_STATE, + BINDING_SET_LAYOUT, + INPUT_ASSEMBLER, + COMMAND_BUFFER, }; export class WebGLGPUObject { - objType : WebGLGPUObjectType; + objType: WebGLGPUObjectType; - constructor(type : WebGLGPUObjectType) { + constructor(type: WebGLGPUObjectType) { this.objType = type; - } -}; - -export class WebGLGPUBuffer extends WebGLGPUObject { - usage : GFXBufferUsage = GFXBufferUsageBit.NONE; - memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; - size : number = 0; - stride : number = 0; - - glTarget : GLenum = 0; - glBuffer : WebGLBuffer = 0; - - constructor() { - super(WebGLGPUObjectType.BUFFER); } }; -export class WebGLGPUInputState extends WebGLGPUObject { - attributes : GFXInputAttribute[] = []; - vertexBuffers : (WebGLGPUBuffer | null)[] = Array(GFX_MAX_VERTEX_ATTRIBUTES); - indexBuffer : WebGLGPUBuffer | null = null; - glVAO : WebGLVertexArrayObjectOES = 0; +export class WebGLGPUBuffer extends WebGLGPUObject { + usage: GFXBufferUsage = GFXBufferUsageBit.NONE; + memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; + size: number = 0; + stride: number = 0; + + glTarget: GLenum = 0; + glBuffer: WebGLBuffer = 0; + arrayBuffer: ArrayBuffer | null = null; + buffer: Buffer | null = null; + + constructor() { + super(WebGLGPUObjectType.BUFFER); + } }; export class WebGLGPUTexture extends WebGLGPUObject { - type : GFXTextureType = GFXTextureType.TEX2D; - viewType : GFXTextureViewType = GFXTextureViewType.TV2D; - format : GFXFormat = GFXFormat.UNKNOWN; - usage : GFXTextureUsage = GFXTextureUsageBit.NONE; - width : number = 0; - height : number = 0; - depth : number = 0; - arrayLayer : number = 0; - mipLevel : number = 0; - flags : GFXTextureFlags = GFXTextureFlagBit.NONE; + type: GFXTextureType = GFXTextureType.TEX2D; + viewType: GFXTextureViewType = GFXTextureViewType.TV2D; + format: GFXFormat = GFXFormat.UNKNOWN; + usage: GFXTextureUsage = GFXTextureUsageBit.NONE; + width: number = 0; + height: number = 0; + depth: number = 0; + arrayLayer: number = 0; + mipLevel: number = 0; + flags: GFXTextureFlags = GFXTextureFlagBit.NONE; - glTarget : GLenum = 0; - glInternelFmt : GLenum = 0; - glFormat : GLenum = 0; - glType : GLenum = 0; - glUsage : GLenum = 0; - glTexture : WebGLTexture = 0; + glTarget: GLenum = 0; + glInternelFmt: GLenum = 0; + glFormat: GLenum = 0; + glType: GLenum = 0; + glUsage: GLenum = 0; + glTexture: WebGLTexture = 0; constructor() { super(WebGLGPUObjectType.TEXTURE); @@ -73,22 +74,22 @@ export class WebGLGPUTexture extends WebGLGPUObject { export class WebGLGPUTextureView extends WebGLGPUObject { - gpuTexture : WebGLGPUTexture; - type : GFXTextureViewType = GFXTextureViewType.TV2D; - format : GFXFormat = GFXFormat.UNKNOWN; - baseLevel : number = 0; - levelCount : number = 1; + gpuTexture: WebGLGPUTexture; + type: GFXTextureViewType = GFXTextureViewType.TV2D; + format: GFXFormat = GFXFormat.UNKNOWN; + baseLevel: number = 0; + levelCount: number = 1; - constructor(texture : WebGLGPUTexture) { + constructor(texture: WebGLGPUTexture) { super(WebGLGPUObjectType.TEXTURE_VIEW); this.gpuTexture = texture; } } export class WebGLGPURenderPass extends WebGLGPUObject { - - colorInfos : ColorAttachmentInfo[] = []; - depthStencilInfo : DepthStencilAttachmentInfo | null = null; + + colorAttachments: GFXColorAttachment[] = []; + depthStencilAttachment: GFXDepthStencilAttachment | null = null; constructor() { super(WebGLGPUObjectType.RENDER_PASS); @@ -96,15 +97,15 @@ export class WebGLGPURenderPass extends WebGLGPUObject { }; export class WebGLGPUFramebuffer extends WebGLGPUObject { - - gpuRenderPass : WebGLGPURenderPass; - gpuColorViews : (WebGLGPUTextureView | null)[] = []; - gpuDepthStencilView : WebGLGPUTextureView | null = null; - isOffscreen : boolean = false; - glFramebuffer : WebGLFramebuffer = 0; + gpuRenderPass: WebGLGPURenderPass; + gpuColorViews: (WebGLGPUTextureView | null)[] = []; + gpuDepthStencilView: WebGLGPUTextureView | null = null; + isOffscreen: boolean = false; - constructor(gpuRenderPass : WebGLGPURenderPass) { + glFramebuffer: WebGLFramebuffer = 0; + + constructor(gpuRenderPass: WebGLGPURenderPass) { super(WebGLGPUObjectType.FRAMEBUFFER); this.gpuRenderPass = gpuRenderPass; @@ -112,70 +113,155 @@ export class WebGLGPUFramebuffer extends WebGLGPUObject { }; export class WebGLGPUSampler extends WebGLGPUObject { - + minFilter: GFXFilter = GFXFilter.LINEAR; + magFilter: GFXFilter = GFXFilter.LINEAR; + mipFilter: GFXFilter = GFXFilter.LINEAR; + addressU: GFXAddress = GFXAddress.WRAP; + addressV: GFXAddress = GFXAddress.WRAP; + addressW: GFXAddress = GFXAddress.WRAP; + maxAnisotropy: number = 16; + cmpFunc: GFXComparisonFunc = GFXComparisonFunc.NEVER; + borderColor: number[] = [0.0, 0.0, 0.0, 0.0]; + minLOD: number = 0; + maxLOD: number = 1000; + mipLODBias: number = 0.0; + + constructor() { + super(WebGLGPUObjectType.SAMPLER); + } }; export class WebGLGPUInput { - binding : number = -1; - name : string = ""; - type : GFXType = GFXType.UNKNOWN; - stride : number = 0; - count : number = 0; - size : number = 0; - - glType : GLenum = 0; - glLoc : GLint = 0; + binding: number = -1; + name: string = ""; + type: GFXType = GFXType.UNKNOWN; + stride: number = 0; + count: number = 0; + size: number = 0; + + glType: GLenum = 0; + glLoc: GLint = 0; }; export class WebGLGPUUniform { - binding : number = -1; - name : string = ""; - type : GFXType = GFXType.UNKNOWN; - stride : number = 0; - count : number = 0; - size : number = 0; - offset : number = 0; - - glType : GLenum = 0; - glLoc : WebGLUniformLocation = -1; + binding: number = -1; + name: string = ""; + type: GFXType = GFXType.UNKNOWN; + stride: number = 0; + count: number = 0; + size: number = 0; + offset: number = 0; + + glType: GLenum = 0; + glLoc: WebGLUniformLocation = -1; + bufferView: Int32Array | Float32Array | null = null; }; export class WebGLGPUUniformBlock { - binding : number = -1; - name : string = ""; - size : number = 0; - glUniforms : WebGLGPUUniform[] = []; + binding: number = -1; + name: string = ""; + size: number = 0; + glUniforms: WebGLGPUUniform[] = []; + + isUniformPackage: boolean = false; // Is a single uniform package? + buffer: ArrayBuffer | null = null; // for cache + bufferView: Buffer | null = null; } export class WebGLGPUUniformSampler { - binding : number = -1; - name : string = ""; - type : GFXType = GFXType.UNKNOWN; - units : number[] = []; + binding: number = -1; + name: string = ""; + type: GFXType = GFXType.UNKNOWN; + units: number[] = []; - glType : GLenum = 0; - glLoc : WebGLUniformLocation = -1; + glType: GLenum = 0; + glLoc: WebGLUniformLocation = -1; } export class WebGLGPUShaderStage { - type : GFXShaderType = GFXShaderType.VERTEX; - source : string = ""; - macros : GFXShaderMacro[] = []; - glShader : WebGLShader = 0; + type: GFXShaderType = GFXShaderType.VERTEX; + source: string = ""; + macros: GFXShaderMacro[] = []; + glShader: WebGLShader = 0; }; export class WebGLGPUShader extends WebGLGPUObject { - name : string = ""; - bindings : GFXBinding[] = []; + name: string = ""; + bindings: GFXBinding[] = []; + blocks: GFXUniformBlock[] = []; - gpuStages : WebGLGPUShaderStage[] = []; - glProgram : WebGLProgram = 0; - glInputs : WebGLGPUInput[] = []; - glUniforms : WebGLGPUUniform[] = []; - glBlocks : WebGLGPUUniformBlock[] = []; - glSamplers : WebGLGPUUniformSampler[] = []; + gpuStages: WebGLGPUShaderStage[] = []; + glProgram: WebGLProgram = 0; + glInputs: WebGLGPUInput[] = []; + glUniforms: WebGLGPUUniform[] = []; + glBlocks: WebGLGPUUniformBlock[] = []; + glSamplers: WebGLGPUUniformSampler[] = []; constructor() { super(WebGLGPUObjectType.SHADER); - } + } +}; + +export class WebGLGPUPipelineLayout extends WebGLGPUObject { + +}; + +export class WebGLGPUPipelineState extends WebGLGPUObject { + + glPrimitive: GLenum = WebGLRenderingContext.TRIANGLES; + gpuShader: WebGLGPUShader | null = null; + rs: GFXRasterizerState | null = null; + dss: GFXDepthStencilState | null = null; + bs: GFXBlendState | null = null; + gpuLayout: WebGLGPUPipelineLayout | null = null; + gpuRenderPass: WebGLGPURenderPass | null = null; + + constructor() { + super(WebGLGPUObjectType.PIPELINE_STATE); + } +}; + +export class WebGLGPUBinding { + binding: number = 0; + type: GFXBindingType = GFXBindingType.UNKNOWN; + name: string = ""; + gpuBuffer: WebGLGPUBuffer | null = null; + gpuTexView: WebGLGPUTextureView | null = null; + gpuSampler: WebGLGPUSampler | null = null; +}; + +export class WebGLGPUBindingSetLayout extends WebGLGPUObject { + + gpuBinding: WebGLGPUBinding[] = []; + + constructor() { + super(WebGLGPUObjectType.BINDING_SET_LAYOUT); + } +}; + +export class WebGLAttrib { + glBuffer: WebGLBuffer = 0; + glLoc: number = 0; + glType: GLenum = 0; + size: number = 0; + count: number = 0; + stride: number = 0; + componentCount: number = 1; + isInstanced: boolean = false; + offset: number = 0; +}; + +export class WebGLGPUInputAssembler extends WebGLGPUObject { + attributes: GFXInputAttribute[] = []; + gpuShader: WebGLGPUShader | null = null; + gpuVertexBuffers: WebGLGPUBuffer[] = []; + gpuIndexBuffer: WebGLGPUBuffer | null = null; + + glAttribs: WebGLAttrib[] = []; + glIndexType: GLenum = 0; + glVAO: WebGLVertexArrayObjectOES = 0; + + constructor() { + super(WebGLGPUObjectType.INPUT_ASSEMBLER); + } }; diff --git a/cocos/renderer/gfx/webgl/webgl-state-cache.ts b/cocos/renderer/gfx/webgl/webgl-state-cache.ts index 0770c8a9c5..611800b748 100644 --- a/cocos/renderer/gfx/webgl/webgl-state-cache.ts +++ b/cocos/renderer/gfx/webgl/webgl-state-cache.ts @@ -1,4 +1,5 @@ -import { GFX_MAX_TEXTURE_UNITS } from "../gfx-define"; +import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES } from "../gfx-define"; +import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; export class WebGLStateCache { glArrayBuffer : WebGLBuffer | null = null; @@ -7,14 +8,32 @@ export class WebGLStateCache { glTex2DUnits : (WebGLTexture | null)[]; glTexCubeUnits : (WebGLTexture | null)[]; glFramebuffer : WebGLFramebuffer | null = null; + viewport : number[] = [0.0, 0.0, 0.0, 0.0]; + scissorRect : number[] = [0.0, 0.0, 0.0, 0.0]; + rs : GFXRasterizerState; + dss : GFXDepthStencilState; + bs : GFXBlendState; + glProgram : WebGLProgram | null = null; + glEnabledAttribLocs : boolean[]; + glCurrentAttribLocs : boolean[]; constructor() { this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.rs = new GFXRasterizerState; + this.dss = new GFXDepthStencilState; + this.bs = new GFXBlendState; + this.glEnabledAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); + this.glCurrentAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); for(let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { this.glTex2DUnits[i] = null; this.glTexCubeUnits[i] = null; } + + for(let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { + this.glEnabledAttribLocs[i] = false; + this.glCurrentAttribLocs[i] = false; + } } }; From aa78612da91580380fe19b31705b7f639a8081df Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 27 Dec 2018 10:07:56 +0800 Subject: [PATCH 004/267] complete gfx --- ...ng-set-layout.ts => gfx-binding-layout.ts} | 6 +- cocos/renderer/gfx/gfx-buffer.ts | 30 +- cocos/renderer/gfx/gfx-command-allocator.ts | 5 +- cocos/renderer/gfx/gfx-command-buffer.ts | 42 +- cocos/renderer/gfx/gfx-device.ts | 36 +- cocos/renderer/gfx/gfx-framebuffer.ts | 25 +- cocos/renderer/gfx/gfx-input-assembler.ts | 22 +- cocos/renderer/gfx/gfx-pipeline-layout.ts | 12 +- cocos/renderer/gfx/gfx-pipeline-state.ts | 248 ++++----- cocos/renderer/gfx/gfx-queue.ts | 4 +- cocos/renderer/gfx/gfx-render-pass.ts | 8 +- cocos/renderer/gfx/gfx-sampler.ts | 14 +- cocos/renderer/gfx/gfx-shader.ts | 78 +-- cocos/renderer/gfx/gfx-texture-view.ts | 38 +- cocos/renderer/gfx/gfx-texture.ts | 57 +- cocos/renderer/gfx/gfx-window.ts | 63 +++ cocos/renderer/gfx/webgl/webgl-commands.ts | 517 +++++++++++++----- .../gfx/webgl/webgl-gfx-binding-layout.ts | 51 ++ .../gfx/webgl/webgl-gfx-binding-set-layout.ts | 55 -- cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts | 14 +- .../gfx/webgl/webgl-gfx-command-allocator.ts | 12 +- .../gfx/webgl/webgl-gfx-command-buffer.ts | 63 ++- cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 415 +++++++++++--- .../gfx/webgl/webgl-gfx-framebuffer.ts | 9 +- .../gfx/webgl/webgl-gfx-input-assembler.ts | 22 +- .../gfx/webgl/webgl-gfx-pipeline-layout.ts | 5 +- .../gfx/webgl/webgl-gfx-pipeline-state.ts | 13 +- cocos/renderer/gfx/webgl/webgl-gfx-queue.ts | 14 +- .../gfx/webgl/webgl-gfx-render-pass.ts | 5 +- cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts | 18 +- cocos/renderer/gfx/webgl/webgl-gfx-shader.ts | 17 +- .../gfx/webgl/webgl-gfx-texture-view.ts | 20 +- cocos/renderer/gfx/webgl/webgl-gfx-texture.ts | 8 +- cocos/renderer/gfx/webgl/webgl-gfx-window.ts | 149 +++++ cocos/renderer/gfx/webgl/webgl-gpu-objects.ts | 47 +- cocos/renderer/gfx/webgl/webgl-state-cache.ts | 33 +- 36 files changed, 1504 insertions(+), 671 deletions(-) rename cocos/renderer/gfx/{gfx-binding-set-layout.ts => gfx-binding-layout.ts} (93%) create mode 100644 cocos/renderer/gfx/gfx-window.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts delete mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts create mode 100644 cocos/renderer/gfx/webgl/webgl-gfx-window.ts diff --git a/cocos/renderer/gfx/gfx-binding-set-layout.ts b/cocos/renderer/gfx/gfx-binding-layout.ts similarity index 93% rename from cocos/renderer/gfx/gfx-binding-set-layout.ts rename to cocos/renderer/gfx/gfx-binding-layout.ts index 32985e531c..41e829c80d 100644 --- a/cocos/renderer/gfx/gfx-binding-set-layout.ts +++ b/cocos/renderer/gfx/gfx-binding-layout.ts @@ -16,7 +16,7 @@ export class GFXBinding { name : string = ""; }; -export class GFXBindingSetLayoutInfo { +export class GFXBindingLayoutInfo { bindings : GFXBinding[] = []; }; @@ -29,13 +29,13 @@ export class GFXBindingUnit { sampler : GFXSampler | null = null; }; -export abstract class GFXBindingSetLayout { +export abstract class GFXBindingLayout { constructor(device : GFXDevice) { this._device = device; } - public abstract initialize(info : GFXBindingSetLayoutInfo) : boolean; + public abstract initialize(info : GFXBindingLayoutInfo) : boolean; public abstract destroy() : void; public bindBuffer(binding: number, buffer: GFXBuffer) { diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/renderer/gfx/gfx-buffer.ts index 4fe393529a..05a3b3e88c 100644 --- a/cocos/renderer/gfx/gfx-buffer.ts +++ b/cocos/renderer/gfx/gfx-buffer.ts @@ -28,22 +28,22 @@ export const enum GFXBufferAccessBit { export type GFXBufferAccess = GFXBufferAccessBit; -export class GFXBufferInfo { - usage : GFXBufferUsage = GFXBufferUsageBit.NONE; - memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; - size : number = 0; - stride : number = 1; +export interface GFXBufferInfo { + usage: GFXBufferUsage; + memUsage: GFXMemoryUsage; + size: number; + stride?: number; }; export abstract class GFXBuffer { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXBufferInfo) : boolean; - public abstract destroy() : void; - public abstract update(buffer : Buffer, offset : number); + public abstract initialize(info: GFXBufferInfo): boolean; + public abstract destroy(): void; + public abstract update(buffer: Buffer, offset: number); public get usage(): GFXBufferUsage { return this._usage; @@ -65,11 +65,11 @@ export abstract class GFXBuffer { return this._buffer; } - protected _device : GFXDevice; - protected _usage : GFXBufferUsage = GFXBufferUsageBit.NONE; - protected _memUsage : GFXMemoryUsage = GFXMemoryUsageBit.NONE; - protected _size : number = 0; - protected _stride : number = 1; - protected _arrayBuffer : ArrayBuffer | null = null; + protected _device: GFXDevice; + protected _usage: GFXBufferUsage = GFXBufferUsageBit.NONE; + protected _memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; + protected _size: number = 0; + protected _stride: number = 1; + protected _arrayBuffer: ArrayBuffer | null = null; protected _buffer: Buffer | null = null; }; diff --git a/cocos/renderer/gfx/gfx-command-allocator.ts b/cocos/renderer/gfx/gfx-command-allocator.ts index fc4df8554d..e4e9bd5fc2 100644 --- a/cocos/renderer/gfx/gfx-command-allocator.ts +++ b/cocos/renderer/gfx/gfx-command-allocator.ts @@ -1,12 +1,15 @@ import { GFXDevice } from './gfx-device'; +export interface GFXCommandAllocatorInfo { +}; + export abstract class GFXCommandAllocator { constructor(device : GFXDevice) { this._device = device; } - public abstract initialize() : boolean; + public abstract initialize(info: GFXCommandAllocatorInfo) : boolean; public abstract destroy(); protected _device : GFXDevice; diff --git a/cocos/renderer/gfx/gfx-command-buffer.ts b/cocos/renderer/gfx/gfx-command-buffer.ts index bb18603cc8..462515969d 100644 --- a/cocos/renderer/gfx/gfx-command-buffer.ts +++ b/cocos/renderer/gfx/gfx-command-buffer.ts @@ -3,16 +3,44 @@ import { GFXCommandAllocator } from './gfx-command-allocator'; import { GFXBuffer } from './gfx-buffer'; import { GFXInputAssembler } from './gfx-input-assembler'; import { GFXPipelineState } from './gfx-pipeline-state'; -import { GFXBindingSetLayout } from './gfx-binding-set-layout'; +import { GFXBindingLayout } from './gfx-binding-layout'; +import { GFXTextureLayout } from './gfx-render-pass'; +import { GFXTexture } from './gfx-texture'; +import { GFXFramebuffer } from './gfx-framebuffer'; + +export class GFXTextureSubres +{ + baseMipLevel: number = 0; + levelCount: number = 1; + baseArrayLayer: number = 0; + layerCount: number = 1; +}; + +export class GFXTextureCopy { + srcSubres: GFXTextureSubres = new GFXTextureSubres; + srcOffset: number[] = [0, 0, 0]; + dstSubres: GFXTextureSubres = new GFXTextureSubres; + dstOffset: number[] = [0, 0, 0]; + extent: number[] = [0, 0, 0]; +}; + +export class GFXBufferTextureCopy { + buffOffset: number = 0; + buffStride: number = 0; + buffTexHeight: number = 0; + texOffset: number[] = [0, 0, 0]; + texExtent: number[] = [0, 0, 0]; + texSubres: GFXTextureSubres = new GFXTextureSubres; +}; export const enum GFXCommandBufferType { PRIMARY, SECONDARY, }; -export class GFXCommandBufferInfo { - allocator : GFXCommandAllocator | null = null; - type : GFXCommandBufferType = GFXCommandBufferType.PRIMARY; +export interface GFXCommandBufferInfo { + allocator : GFXCommandAllocator; + type : GFXCommandBufferType; }; export abstract class GFXCommandBuffer { @@ -26,11 +54,15 @@ export abstract class GFXCommandBuffer { public abstract begin(); public abstract end(); + public abstract beginRenderPass(framebuffer : GFXFramebuffer, viewport : number[], numClearColors : number, clearColors : number[], clearStencil : number); + public abstract endRenderPass(); public abstract bindPipelineState(pipelineState : GFXPipelineState); - public abstract bindBindingSetLayout(bindingSetLayout : GFXBindingSetLayout); + public abstract bindBindingLayout(bindingLayout : GFXBindingLayout); public abstract bindInputAssembler(inputAssembler : GFXInputAssembler); 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[]); + public abstract execute(cmdBuffs : GFXCommandBuffer[]); public get type(): number { return this._type; diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index 97761026c2..22f4284486 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -1,15 +1,40 @@ -import { GFXBuffer } from './gfx-buffer'; -import { GFXQueue } from './gfx-queue'; +import { GFXBuffer, GFXBufferInfo } from './gfx-buffer'; +import { GFXQueue, GFXQueueInfo } from './gfx-queue'; +import { GFXTexture, GFXTextureInfo } from './gfx-texture'; +import { GFXTextureViewInfo, GFXTextureView } from './gfx-texture-view'; +import { GFXFramebufferInfo, GFXFramebuffer } from './gfx-framebuffer'; +import { GFXRenderPassInfo, GFXRenderPass } from './gfx-render-pass'; +import { GFXPipelineStateInfo, GFXPipelineState } from './gfx-pipeline-state'; +import { GFXPipelineLayoutInfo, GFXPipelineLayout } from './gfx-pipeline-layout'; +import { GFXSamplerInfo, GFXSampler } from './gfx-sampler'; +import { GFXShaderInfo, GFXShader } from './gfx-shader'; +import { GFXInputAssemblerInfo, GFXInputAssembler } from './gfx-input-assembler'; +import { GFXCommandBufferInfo, GFXCommandBuffer } from './gfx-command-buffer'; +import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './gfx-command-allocator'; +import { GFXWindowInfo, GFXWindow } from './gfx-window'; export class GFXDeviceInfo { + canvasElm: HTMLElement | null = null; }; export abstract class GFXDevice { public abstract initialize(info : GFXDeviceInfo) : boolean; public abstract destroy() : void; - public abstract createBuffer() : GFXBuffer; - public abstract getDeviceName() : string; + public abstract createBuffer(info: GFXBufferInfo) : GFXBuffer | null; + public abstract createTexture(info: GFXTextureInfo) : GFXTexture | null; + public abstract createTextureView(info: GFXTextureViewInfo) : GFXTextureView | null; + public abstract createSampler(info: GFXSamplerInfo) : GFXSampler | null; + public abstract createShader(info: GFXShaderInfo) : GFXShader | null; + public abstract createInputAssembler(info: GFXInputAssemblerInfo) : GFXInputAssembler | null; + public abstract createRenderPass(info: GFXRenderPassInfo) : GFXRenderPass | null; + public abstract createFramebuffer(info: GFXFramebufferInfo) : GFXFramebuffer | null; + public abstract createPipelineLayout(info: GFXPipelineLayoutInfo) : GFXPipelineLayout | null; + public abstract createPipelineState(info: GFXPipelineStateInfo) : GFXPipelineState | null; + public abstract createCommandAllocator(info: GFXCommandAllocatorInfo): GFXCommandAllocator | null; + public abstract createCommandBuffer(info: GFXCommandBufferInfo) : GFXCommandBuffer | null; + public abstract createQueue(info: GFXQueueInfo) : GFXQueue | null; + public abstract createWindow(info: GFXWindowInfo) : GFXWindow | null; public get queue(): GFXQueue { return this._queue; @@ -19,7 +44,10 @@ export abstract class GFXDevice { return this._maxVertexAttributes; } + protected _deviceName : string = ""; protected _queue : GFXQueue | null = null; + protected _primaryWindow : GFXWindow | null = null; + protected _windows : GFXWindow[] = []; protected _maxVertexAttributes : number = 0; }; diff --git a/cocos/renderer/gfx/gfx-framebuffer.ts b/cocos/renderer/gfx/gfx-framebuffer.ts index 71bee525e8..ed394a182f 100644 --- a/cocos/renderer/gfx/gfx-framebuffer.ts +++ b/cocos/renderer/gfx/gfx-framebuffer.ts @@ -2,25 +2,24 @@ import { GFXDevice } from './gfx-device'; import { GFXTextureView } from './gfx-texture-view'; import { GFXRenderPass } from './gfx-render-pass'; -export class GFXFramebufferInfo -{ - renderPass : GFXRenderPass | null = null; - colorViews : GFXTextureView[] = []; - depthStencilView : GFXTextureView | null = null; - isOffscreen : boolean = false; +export interface GFXFramebufferInfo { + renderPass: GFXRenderPass; + colorViews?: GFXTextureView[]; + depthStencilView?: GFXTextureView; + isOffscreen?: boolean; }; export abstract class GFXFramebuffer { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXFramebufferInfo) : boolean; - public abstract destroy() : void; + public abstract initialize(info: GFXFramebufferInfo): boolean; + public abstract destroy(): void; - protected _device : GFXDevice; - protected _colorViews : GFXTextureView[] = []; - protected _depthStencilView : GFXTextureView | null = null; - protected _isOffscreen : boolean = false; + protected _device: GFXDevice; + protected _colorViews: GFXTextureView[] = []; + protected _depthStencilView: GFXTextureView | null = null; + protected _isOffscreen: boolean = true; }; diff --git a/cocos/renderer/gfx/gfx-input-assembler.ts b/cocos/renderer/gfx/gfx-input-assembler.ts index 50aa6dfc6a..ba4f5adcdb 100644 --- a/cocos/renderer/gfx/gfx-input-assembler.ts +++ b/cocos/renderer/gfx/gfx-input-assembler.ts @@ -3,19 +3,19 @@ import { GFXFormat } from './gfx-define'; import { GFXBuffer } from './gfx-buffer'; import { GFXShader } from './gfx-shader'; -export class GFXInputAttribute { - name: string = ""; - format: GFXFormat = GFXFormat.UNKNOWN; - stream: number = 0; - isInstanced: boolean = false; +export interface GFXInputAttribute { + name: string; + format: GFXFormat; + stream?: number; + isInstanced?: boolean; }; -export class GFXInputAssemblerInfo { - attributes: GFXInputAttribute[] = []; - shader: GFXShader | null = null; - vertexBuffers: GFXBuffer[] = []; - indexBuffer: GFXBuffer | null = null; - isIndirect: boolean = false; +export interface GFXInputAssemblerInfo { + attributes: GFXInputAttribute[]; + shader: GFXShader; + vertexBuffers: GFXBuffer[]; + indexBuffer?: GFXBuffer; + isIndirect?: boolean; }; export abstract class GFXInputAssembler { diff --git a/cocos/renderer/gfx/gfx-pipeline-layout.ts b/cocos/renderer/gfx/gfx-pipeline-layout.ts index 5190403b0a..811d3e4afd 100644 --- a/cocos/renderer/gfx/gfx-pipeline-layout.ts +++ b/cocos/renderer/gfx/gfx-pipeline-layout.ts @@ -1,5 +1,5 @@ import { GFXDevice } from './gfx-device'; -import { GFXBindingSetLayout } from './gfx-binding-set-layout'; +import { GFXBindingLayout } from './gfx-binding-layout'; import { GFXShaderType } from './gfx-shader'; export class GFXPushConstantRange { @@ -8,12 +8,12 @@ export class GFXPushConstantRange { count : number = 0; }; -export class GFXPipelineLayoutInfo { - pushConstantsRanges : GFXPushConstantRange[] = []; - layouts : GFXBindingSetLayout[] = []; +export interface GFXPipelineLayoutInfo { + pushConstantsRanges? : GFXPushConstantRange[]; + layouts : GFXBindingLayout[]; }; -export abstract class GFXPipelineLayout { +export abstract class GFXPipelineLayout { constructor(device : GFXDevice) { this._device = device; @@ -24,5 +24,5 @@ export abstract class GFXPipelineLayout { protected _device : GFXDevice; protected _pushConstantsRanges : GFXPushConstantRange[] = []; - protected _layouts: GFXBindingSetLayout[] = []; + protected _layouts: GFXBindingLayout[] = []; }; diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/renderer/gfx/gfx-pipeline-state.ts index 29de3c15ef..5921edc045 100644 --- a/cocos/renderer/gfx/gfx-pipeline-state.ts +++ b/cocos/renderer/gfx/gfx-pipeline-state.ts @@ -51,26 +51,26 @@ export const enum GFXComparisonFunc { }; export const enum GFXStencilOp { - KEEP, - ZERO, - REPLACE, - INCR, - DECR, - INVERT, - INCR_WRAP, - DECR_WRAP, + KEEP, + ZERO, + REPLACE, + INCR, + DECR, + INVERT, + INCR_WRAP, + DECR_WRAP, }; export const enum GFXBlendOp { - ADD, - SUB, - REV_SUB, - MIN, - MAX, + ADD, + SUB, + REV_SUB, + MIN, + MAX, }; export const enum GFXBlendFactor { - ZERO, + ZERO, ONE, SRC_ALPHA, DST_ALPHA, @@ -88,147 +88,147 @@ export const enum GFXBlendFactor { }; export const enum GFXColorMask { - NONE = 0x0, - R = 0x1, - G = 0x2, - B = 0x4, - A = 0x8, - ALL = R | G | B | A, + NONE = 0x0, + R = 0x1, + G = 0x2, + B = 0x4, + A = 0x8, + ALL = R | G | B | A, }; export class GFXRasterizerState { - name : string = ""; - isDiscard : boolean = false; - polygonMode : GFXPolygonMode = GFXPolygonMode.FILL; - shadeModel : GFXShadeModel = GFXShadeModel.GOURAND; - cullMode : GFXCullMode = GFXCullMode.BACK; - isFrontFaceCCW : boolean = true; - depthBias : number = 0.0; - depthBiasFactor : number = 0.0; - isDepthClip : boolean = true; - isMultisample : boolean = false; - lineWidth : number = 1.0; + name: string = ""; + isDiscard: boolean = false; + polygonMode: GFXPolygonMode = GFXPolygonMode.FILL; + shadeModel: GFXShadeModel = GFXShadeModel.GOURAND; + cullMode: GFXCullMode = GFXCullMode.BACK; + isFrontFaceCCW: boolean = true; + depthBias: number = 0.0; + depthBiasFactor: number = 0.0; + isDepthClip: boolean = true; + isMultisample: boolean = false; + lineWidth: number = 1.0; - public compare(state : GFXRasterizerState) : boolean { - return (this.isDiscard === state.isDiscard) && - (this.polygonMode === state.polygonMode) && - (this.shadeModel === state.shadeModel) && - (this.cullMode === state.cullMode) && - (this.isFrontFaceCCW === state.isFrontFaceCCW) && - (this.depthBias === state.depthBias) && - (this.depthBiasFactor === state.depthBiasFactor) && - (this.isDepthClip === state.isDepthClip) && - (this.isMultisample === state.isMultisample) && - (this.lineWidth === state.lineWidth); + public compare(state: GFXRasterizerState): boolean { + return (this.isDiscard === state.isDiscard) && + (this.polygonMode === state.polygonMode) && + (this.shadeModel === state.shadeModel) && + (this.cullMode === state.cullMode) && + (this.isFrontFaceCCW === state.isFrontFaceCCW) && + (this.depthBias === state.depthBias) && + (this.depthBiasFactor === state.depthBiasFactor) && + (this.isDepthClip === state.isDepthClip) && + (this.isMultisample === state.isMultisample) && + (this.lineWidth === state.lineWidth); } }; export class GFXDepthStencilState { - name : string = ""; - isDepthTest : boolean = true; - isWriteDepth : boolean = true; - depthFunc : GFXComparisonFunc = GFXComparisonFunc.LESS; - isFrontStencilTest : boolean = false; - frontStencilFunc : GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - frontStencilReadMask : number = 0xffffffff; - frontStencilWriteMask : number = 0xffffffff; - frontStencilFailOp : GFXStencilOp = GFXStencilOp.KEEP; - frontStencilDepthFailOp : GFXStencilOp = GFXStencilOp.KEEP; - frontStencilPassOp : GFXStencilOp = GFXStencilOp.KEEP; - frontStencilRef : number = 1; - isBackStencilTest : boolean = false; - backStencilFunc : GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - backStencilReadMask : number = 0xffffffff; - backStencilWriteMask : number = 0xffffffff; - backStencilFailOp : GFXStencilOp = GFXStencilOp.KEEP; - backStencilDepthFailOp : GFXStencilOp = GFXStencilOp.KEEP; - backStencilPassOp : GFXStencilOp = GFXStencilOp.KEEP; - backStencilRef : number = 1; + name: string = ""; + isDepthTest: boolean = true; + isWriteDepth: boolean = true; + depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; + isFrontStencilTest: boolean = false; + frontStencilFunc: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + frontStencilReadMask: number = 0xffffffff; + frontStencilWriteMask: number = 0xffffffff; + frontStencilFailOp: GFXStencilOp = GFXStencilOp.KEEP; + frontStencilDepthFailOp: GFXStencilOp = GFXStencilOp.KEEP; + frontStencilPassOp: GFXStencilOp = GFXStencilOp.KEEP; + frontStencilRef: number = 1; + isBackStencilTest: boolean = false; + backStencilFunc: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + backStencilReadMask: number = 0xffffffff; + backStencilWriteMask: number = 0xffffffff; + backStencilFailOp: GFXStencilOp = GFXStencilOp.KEEP; + backStencilDepthFailOp: GFXStencilOp = GFXStencilOp.KEEP; + backStencilPassOp: GFXStencilOp = GFXStencilOp.KEEP; + backStencilRef: number = 1; - public compare(state : GFXDepthStencilState) : boolean { - return (this.isDepthTest === state.isDepthTest) && - (this.isWriteDepth === state.isWriteDepth) && - (this.depthFunc === state.depthFunc) && - (this.isFrontStencilTest === state.isFrontStencilTest) && - (this.frontStencilFunc === state.frontStencilFunc) && - (this.frontStencilReadMask === state.frontStencilReadMask) && - (this.frontStencilWriteMask === state.frontStencilWriteMask) && - (this.frontStencilFailOp === state.frontStencilFailOp) && - (this.frontStencilDepthFailOp === state.frontStencilDepthFailOp) && - (this.frontStencilPassOp === state.frontStencilPassOp) && - (this.frontStencilRef === state.frontStencilRef) && - (this.isBackStencilTest === state.isBackStencilTest) && - (this.backStencilFunc === state.backStencilFunc) && - (this.backStencilReadMask === state.backStencilReadMask) && - (this.backStencilWriteMask === state.backStencilWriteMask) && - (this.backStencilFailOp === state.backStencilFailOp) && - (this.backStencilDepthFailOp === state.backStencilDepthFailOp) && - (this.backStencilPassOp === state.backStencilPassOp) && - (this.backStencilRef === state.backStencilRef); + public compare(state: GFXDepthStencilState): boolean { + return (this.isDepthTest === state.isDepthTest) && + (this.isWriteDepth === state.isWriteDepth) && + (this.depthFunc === state.depthFunc) && + (this.isFrontStencilTest === state.isFrontStencilTest) && + (this.frontStencilFunc === state.frontStencilFunc) && + (this.frontStencilReadMask === state.frontStencilReadMask) && + (this.frontStencilWriteMask === state.frontStencilWriteMask) && + (this.frontStencilFailOp === state.frontStencilFailOp) && + (this.frontStencilDepthFailOp === state.frontStencilDepthFailOp) && + (this.frontStencilPassOp === state.frontStencilPassOp) && + (this.frontStencilRef === state.frontStencilRef) && + (this.isBackStencilTest === state.isBackStencilTest) && + (this.backStencilFunc === state.backStencilFunc) && + (this.backStencilReadMask === state.backStencilReadMask) && + (this.backStencilWriteMask === state.backStencilWriteMask) && + (this.backStencilFailOp === state.backStencilFailOp) && + (this.backStencilDepthFailOp === state.backStencilDepthFailOp) && + (this.backStencilPassOp === state.backStencilPassOp) && + (this.backStencilRef === state.backStencilRef); } }; export class GFXBlendTarget { - isBlend : boolean = false; - srcBlend : GFXBlendFactor = GFXBlendFactor.ONE; - dstBlend : GFXBlendFactor = GFXBlendFactor.ZERO; - blendOp : GFXBlendOp = GFXBlendOp.ADD; - srcAlphaBlend : GFXBlendFactor = GFXBlendFactor.ONE; - dstAlphaBlend : GFXBlendFactor = GFXBlendFactor.ZERO; - alphBlendOp : GFXBlendOp = GFXBlendOp.ADD; - colorWriteMask : GFXColorMask = GFXColorMask.ALL; + isBlend: boolean = false; + srcBlend: GFXBlendFactor = GFXBlendFactor.ONE; + dstBlend: GFXBlendFactor = GFXBlendFactor.ZERO; + blendOp: GFXBlendOp = GFXBlendOp.ADD; + srcAlphaBlend: GFXBlendFactor = GFXBlendFactor.ONE; + dstAlphaBlend: GFXBlendFactor = GFXBlendFactor.ZERO; + alphBlendOp: GFXBlendOp = GFXBlendOp.ADD; + colorWriteMask: GFXColorMask = GFXColorMask.ALL; - public compare(state : GFXBlendTarget) : boolean { - return (this.isBlend === state.isBlend) && - (this.srcBlend === state.srcBlend) && - (this.dstBlend === state.dstBlend) && - (this.blendOp === state.blendOp) && - (this.srcAlphaBlend === state.srcAlphaBlend) && - (this.dstAlphaBlend === state.dstAlphaBlend) && - (this.alphBlendOp === state.alphBlendOp) && - (this.colorWriteMask === state.colorWriteMask); + public compare(state: GFXBlendTarget): boolean { + return (this.isBlend === state.isBlend) && + (this.srcBlend === state.srcBlend) && + (this.dstBlend === state.dstBlend) && + (this.blendOp === state.blendOp) && + (this.srcAlphaBlend === state.srcAlphaBlend) && + (this.dstAlphaBlend === state.dstAlphaBlend) && + (this.alphBlendOp === state.alphBlendOp) && + (this.colorWriteMask === state.colorWriteMask); } }; export class GFXBlendState { - name : string = ""; - isA2C : boolean = false; - isIndepend : boolean = false; - factor : number[] = [0, 0, 0, 0]; - targets : GFXBlendTarget[] = [new GFXBlendTarget]; + name: string = ""; + isA2C: boolean = false; + isIndepend: boolean = false; + factor: number[] = [0, 0, 0, 0]; + targets: GFXBlendTarget[] = [new GFXBlendTarget]; } export class GFXInputState { attributes: GFXInputAttribute[] = []; }; -export class GFXPipelineStateInfo { - primitive : GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; - shader : GFXShader | null = null; - is : GFXInputState | null = null; - rs : GFXRasterizerState | null = null; - dss : GFXDepthStencilState | null = null; - bs : GFXBlendState | null = null; - layout : GFXPipelineLayout | null = null; - renderPass : GFXRenderPass | null = null; +export interface GFXPipelineStateInfo { + primitive: GFXPrimitiveMode; + shader: GFXShader; + is: GFXInputState; + rs: GFXRasterizerState; + dss: GFXDepthStencilState; + bs: GFXBlendState; + layout: GFXPipelineLayout; + renderPass: GFXRenderPass; }; -export abstract class GFXPipelineState { +export abstract class GFXPipelineState { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXPipelineStateInfo) : boolean; - public abstract destroy() : void; + public abstract initialize(info: GFXPipelineStateInfo): boolean; + public abstract destroy(): void; - protected _device : GFXDevice; - protected _shader : GFXShader | null = null; - protected _primitive : GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; - protected _is : GFXInputState | null = null; - protected _rs : GFXRasterizerState | null = null; - protected _dss : GFXDepthStencilState | null = null; - protected _bs : GFXBlendState | null = null; + protected _device: GFXDevice; + protected _shader: GFXShader | null = null; + protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + protected _is: GFXInputState | null = null; + protected _rs: GFXRasterizerState | null = null; + protected _dss: GFXDepthStencilState | null = null; + protected _bs: GFXBlendState | null = null; protected _layout: GFXPipelineLayout | null = null; protected _renderPass: GFXRenderPass | null = null; }; diff --git a/cocos/renderer/gfx/gfx-queue.ts b/cocos/renderer/gfx/gfx-queue.ts index 597767b5ca..c380de58bc 100644 --- a/cocos/renderer/gfx/gfx-queue.ts +++ b/cocos/renderer/gfx/gfx-queue.ts @@ -6,8 +6,8 @@ export const enum GFXQueueType { TRANSFER, }; -export class GFXQueueInfo { - type : GFXQueueType = GFXQueueType.GRAPHICS; +export interface GFXQueueInfo { + type : GFXQueueType; }; export abstract class GFXQueue { diff --git a/cocos/renderer/gfx/gfx-render-pass.ts b/cocos/renderer/gfx/gfx-render-pass.ts index 0fc5a925cc..4127456b34 100644 --- a/cocos/renderer/gfx/gfx-render-pass.ts +++ b/cocos/renderer/gfx/gfx-render-pass.ts @@ -71,9 +71,9 @@ export class GFXSubPassInfo export class GFXRenderPassInfo { - colorInfos : GFXColorAttachment[] = []; - depthStencilInfo : GFXDepthStencilAttachment | null = null; - subPasses : GFXSubPassInfo[] = []; + colorAttachment : GFXColorAttachment[] = []; + depthStencilAttachment : GFXDepthStencilAttachment | null = null; + //subPasses : GFXSubPassInfo[] = []; }; export abstract class GFXRenderPass { @@ -88,5 +88,5 @@ export abstract class GFXRenderPass { protected _device : GFXDevice; protected _colorInfos : GFXColorAttachment[] = []; protected _depthStencilInfo : GFXDepthStencilAttachment | null = null; - protected _subPasses : GFXSubPassInfo[] = []; + //protected _subPasses : GFXSubPassInfo[] = []; }; diff --git a/cocos/renderer/gfx/gfx-sampler.ts b/cocos/renderer/gfx/gfx-sampler.ts index 4750c78372..36fb915b45 100644 --- a/cocos/renderer/gfx/gfx-sampler.ts +++ b/cocos/renderer/gfx/gfx-sampler.ts @@ -56,17 +56,5 @@ export abstract class GFXSampler { public abstract destroy() : void; protected _device : GFXDevice; - protected _name : string = ""; - protected _minFilter : GFXFilter = GFXFilter.LINEAR; - protected _magFilter : GFXFilter = GFXFilter.LINEAR; - protected _mipFilter : GFXFilter = GFXFilter.LINEAR; - protected _addressU : GFXAddress = GFXAddress.WRAP; - protected _addressV : GFXAddress = GFXAddress.WRAP; - protected _addressW : GFXAddress = GFXAddress.WRAP; - protected _maxAnisotropy : number = 16; - protected _cmpFunc : GFXComparisonFunc = GFXComparisonFunc.NEVER; - protected _borderColor : number[] = [0.0, 0.0, 0.0, 0.0]; - protected _minLOD : number = 0; - protected _maxLOD : number = 1000; - protected _mipLODBias : number = 0.0; + protected _state : GFXSamplerInfo | null = null; }; diff --git a/cocos/renderer/gfx/gfx-shader.ts b/cocos/renderer/gfx/gfx-shader.ts index ae7e662ddf..0ef1078db1 100644 --- a/cocos/renderer/gfx/gfx-shader.ts +++ b/cocos/renderer/gfx/gfx-shader.ts @@ -1,5 +1,5 @@ import { GFXDevice } from './gfx-device'; -import { GFXBinding } from './gfx-binding-set-layout'; +import { GFXBinding } from './gfx-binding-layout'; import { GFXType } from './gfx-define'; export const enum GFXShaderType { @@ -12,60 +12,60 @@ export const enum GFXShaderType { COUNT, }; -export class GFXShaderMacro { - macro : string = ""; - value : string = ""; - - constructor(macro : string, value : string = "") { - this.macro = macro; - this.value = value; - } +export interface GFXShaderMacro { + macro: string; + value: string; }; -export class GFXUniform { - name : string = ""; - type : GFXType = GFXType.UNKNOWN; - count : number = 1; +export interface GFXUniform { + name: string; + type: GFXType; + count: number; }; -export class GFXUniformBlock { - binding : number = -1; - name : string = ""; - //instance : string = ""; - uniforms : GFXUniform[] = []; +export interface GFXUniformBlock { + binding: number; + name: string; + //instance : string; + uniforms: GFXUniform[]; }; -export class GFXShaderStage { - type : GFXShaderType = GFXShaderType.VERTEX; - source : string = ""; - macros : GFXShaderMacro[] = []; - - public define(macro : string, value : string = "") : void { - this.macros.push({ macro, value }); - } +export interface GFXUniformSampler { + binding: number; + name: string; + type: GFXType; + count: number; }; -export class GFXShaderInfo { - name : string = ""; - stages : GFXShaderStage[] = []; - bindings : GFXBinding[] = []; +export interface GFXShaderStage { + type: GFXShaderType; + source: string; + macros?: GFXShaderMacro[]; +}; + +export interface GFXShaderInfo { + name?: string; + stages: GFXShaderStage[]; + //bindings: GFXBinding[]; // blocks are used for being compatible with single uniforms - blocks : GFXUniformBlock[] = []; + blocks?: GFXUniformBlock[]; + samplers?: GFXUniformSampler[]; }; export abstract class GFXShader { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXShaderInfo) : boolean; - public abstract destroy() : void; + public abstract initialize(info: GFXShaderInfo): boolean; + public abstract destroy(); - protected _device : GFXDevice; - protected _name : string = ""; - protected _stages : GFXShaderStage[] = []; - protected _bindings : GFXBinding[] = []; - protected _blocks : GFXUniformBlock[] = []; + protected _device: GFXDevice; + protected _name: string = ""; + protected _stages: GFXShaderStage[] = []; + //protected _bindings: GFXBinding[] = []; + protected _blocks?: GFXUniformBlock[]; + protected _samplers?: GFXUniformSampler[]; }; diff --git a/cocos/renderer/gfx/gfx-texture-view.ts b/cocos/renderer/gfx/gfx-texture-view.ts index 5698b30149..9078b00520 100644 --- a/cocos/renderer/gfx/gfx-texture-view.ts +++ b/cocos/renderer/gfx/gfx-texture-view.ts @@ -11,24 +11,24 @@ export const enum GFXTextureViewType { TV2D_ARRAY, }; -export class GFXTextureViewInfo { - texture : GFXTexture | null = null; - type : GFXTextureViewType = GFXTextureViewType.TV2D; - format : GFXFormat = GFXFormat.UNKNOWN; - baseLevel : number = 0; - levelCount : number = 1; - baseLayer : number = 0; - layerCount : number = 1; +export interface GFXTextureViewInfo { + texture: GFXTexture; + type: GFXTextureViewType; + format: GFXFormat; + baseLevel?: number; + levelCount?: number; + baseLayer?: number; + layerCount?: number; }; export abstract class GFXTextureView { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXTextureViewInfo) : boolean; - public abstract destroy() : void; + public abstract initialize(info: GFXTextureViewInfo): boolean; + public abstract destroy(): void; public get texture(): GFXTexture { return this._texture; @@ -58,12 +58,12 @@ export abstract class GFXTextureView { return this._layerCount; } - protected _device : GFXDevice; - protected _texture : GFXTexture | null = null; - protected _type : GFXTextureViewType = GFXTextureViewType.TV2D; - protected _format : GFXFormat = GFXFormat.UNKNOWN; - protected _baseLevel : number = 0; - protected _levelCount : number = 1; - protected _baseLayer : number = 0; - protected _layerCount : number = 1; + protected _device: GFXDevice; + protected _texture: GFXTexture | null = null; + protected _type: GFXTextureViewType = GFXTextureViewType.TV2D; + protected _format: GFXFormat = GFXFormat.UNKNOWN; + protected _baseLevel: number = 0; + protected _levelCount: number = 1; + protected _baseLayer: number = 0; + protected _layerCount: number = 1; }; diff --git a/cocos/renderer/gfx/gfx-texture.ts b/cocos/renderer/gfx/gfx-texture.ts index fc9f0f3795..ee998e0c32 100644 --- a/cocos/renderer/gfx/gfx-texture.ts +++ b/cocos/renderer/gfx/gfx-texture.ts @@ -13,9 +13,10 @@ export const enum GFXTextureUsageBit { TRANSFER_DST = 0x2, SAMPLED = 0x4, STORAGE = 0x8, - INPUT_ATTACHMENT = 0x10, - OUTPUT_ATTACHMENT = 0x20, - PRESENT = 0x30, + COLOR_ATTACHMENT = 0x10, + DEPTH_STENCIL_ATTACHMENT = 0x20, + TRANSIENT_ATTACHMENT = 0x40, + INPUT_ATTACHMENT = 0x80, }; export type GFXTextureUsage = GFXTextureUsageBit; @@ -29,26 +30,26 @@ export const enum GFXTextureFlagBit { export type GFXTextureFlags = GFXTextureFlagBit; -export class GFXTextureInfo { - type : GFXTextureType = GFXTextureType.TEX2D; - usage : GFXTextureUsage = GFXTextureUsageBit.NONE; - format : GFXFormat = GFXFormat.UNKNOWN; - width : number = 0; - height : number = 0; - depth : number = 1; - arrayLayer : number = 1; - mipLevel : number = 1; - flags : GFXTextureFlags = GFXTextureFlagBit.NONE; +export interface GFXTextureInfo { + type: GFXTextureType; + usage: GFXTextureUsage; + format: GFXFormat; + width: number; + height: number; + depth?: number; + arrayLayer?: number; + mipLevel?: number; + flags?: GFXTextureFlags; }; export abstract class GFXTexture { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXTextureInfo) : boolean; - public abstract destroy() : void; + public abstract initialize(info: GFXTextureInfo): boolean; + public abstract destroy(): void; public get type(): GFXTextureType { return this._type; @@ -94,16 +95,16 @@ export abstract class GFXTexture { return this._buffer; } - protected _device : GFXDevice; - protected _type : GFXTextureType = GFXTextureType.TEX2D; - protected _usage : GFXTextureUsage = GFXTextureUsageBit.NONE; - protected _format : GFXFormat = GFXFormat.UNKNOWN; - protected _width : number = 0; - protected _height : number = 0; - protected _depth : number = 1; - protected _arrayLayer : number = 1; - protected _mipLevel : number = 1; - protected _flags : GFXTextureFlags = GFXTextureFlagBit.NONE; - protected _size : number = 0; - protected _buffer : ArrayBuffer | null = null; + protected _device: GFXDevice; + protected _type: GFXTextureType = GFXTextureType.TEX2D; + protected _usage: GFXTextureUsage = GFXTextureUsageBit.NONE; + protected _format: GFXFormat = GFXFormat.UNKNOWN; + protected _width: number = 0; + protected _height: number = 0; + protected _depth: number = 1; + protected _arrayLayer: number = 1; + protected _mipLevel: number = 1; + protected _flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + protected _size: number = 0; + protected _buffer: ArrayBuffer | null = null; }; diff --git a/cocos/renderer/gfx/gfx-window.ts b/cocos/renderer/gfx/gfx-window.ts new file mode 100644 index 0000000000..d949f769ec --- /dev/null +++ b/cocos/renderer/gfx/gfx-window.ts @@ -0,0 +1,63 @@ +import { GFXDevice } from './gfx-device'; +import { GFXFramebuffer } from './gfx-framebuffer'; +import { GFXTexture } from './gfx-texture'; +import { GFXTextureView } from './gfx-texture-view'; +import { GFXFormat } from './gfx-define'; +import { GFXRenderPass } from './gfx-render-pass'; + +export interface GFXWindowInfo { + title?: string; + left?: number; + top?: number; + width: number; + height: number; +}; + +export abstract class GFXWindow { + + constructor(device: GFXDevice) { + this._device = device; + } + + public abstract initialize(info: GFXWindowInfo): boolean; + public abstract destroy(): void; + + public get width(): number { + return this._width; + } + + public get height(): number { + return this._height; + } + + public get colorFormat(): GFXFormat | null { + return this._colorFmt; + } + + public get detphStencilFormat(): GFXFormat | null { + return this._depthStencilFmt; + } + + public get renderPass(): GFXRenderPass | null { + return this._renderPass; + } + + public get framebuffer(): GFXFramebuffer | null { + return this._framebuffer; + } + + protected _device: GFXDevice; + protected _title: string = ""; + protected _left: number = 0; + protected _top: number = 0; + protected _width: number = 0; + protected _height: number = 0; + protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _renderPass: GFXRenderPass | null = null; + protected _colorTex: GFXTexture | null = null; + protected _colorTexView: GFXTextureView | null = null; + protected _depthStencilTex: GFXTexture | null = null; + protected _depthStencilTexView: GFXTextureView | null = null; + protected _framebuffer: GFXFramebuffer | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index 69a56c6b3c..bfb83df32e 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -1,14 +1,17 @@ -import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingSetLayout } from "./webgl-gpu-objects"; +import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-gfx-device"; import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../gfx-buffer"; import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES } from "../gfx-define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize } from "../gfx-define"; import { GFXShaderType } from "../gfx-shader"; -import { GFXLoadOp } from "../gfx-render-pass"; +import { GFXLoadOp, GFXTextureLayout } from "../gfx-render-pass"; import { GFXColorMask, GFXCullMode } from "../gfx-pipeline-state"; import { WebGLGFXCommandAllocator } from "./webgl-gfx-command-allocator"; -import { GFXBindingType } from "../gfx-binding-set-layout"; +import { GFXBindingType } from "../gfx-binding-layout"; import { Buffer } from "buffer"; +import { WebGLTexUnit } from "./webgl-state-cache"; +import { GFXBufferTextureCopy } from "../gfx-command-buffer"; +import { GFXTextureFlagBit } from "../gfx-texture"; function GFXFormatToWebGLType(format: GFXFormat): GLenum { switch (format) { @@ -190,6 +193,33 @@ function GFXFormatToWebGLFormat(format: GFXFormat): GLenum { } } +function GFXTypeToWebGLType(type: GFXType): GLenum { + switch (type) { + case GFXType.BOOL: return WebGLRenderingContext.BOOL; + case GFXType.BOOL2: return WebGLRenderingContext.BOOL_VEC2; + case GFXType.BOOL3: return WebGLRenderingContext.BOOL_VEC3; + case GFXType.BOOL4: return WebGLRenderingContext.BOOL_VEC4; + case GFXType.INT: return WebGLRenderingContext.INT; + case GFXType.INT2: return WebGLRenderingContext.INT_VEC2; + case GFXType.INT3: return WebGLRenderingContext.INT_VEC3; + case GFXType.INT4: return WebGLRenderingContext.INT_VEC4; + case GFXType.UINT: return WebGLRenderingContext.UNSIGNED_INT; + case GFXType.FLOAT: return WebGLRenderingContext.FLOAT; + case GFXType.FLOAT2: return WebGLRenderingContext.FLOAT_VEC2; + case GFXType.FLOAT3: return WebGLRenderingContext.FLOAT_VEC3; + case GFXType.FLOAT4: return WebGLRenderingContext.FLOAT_VEC4; + case GFXType.MAT2: return WebGLRenderingContext.FLOAT_MAT2; + case GFXType.MAT3: return WebGLRenderingContext.FLOAT_MAT3; + case GFXType.MAT4: return WebGLRenderingContext.FLOAT_MAT4; + case GFXType.SAMPLER2D: return WebGLRenderingContext.SAMPLER_2D; + case GFXType.SAMPLER_CUBE: return WebGLRenderingContext.SAMPLER_CUBE; + default: { + console.error("Unsupported GLType, convert to GL type failed."); + return GFXType.UNKNOWN; + } + } +} + function WebGLTypeToGFXType(glType: GLenum): GFXType { switch (glType) { case WebGLRenderingContext.BOOL: return GFXType.BOOL; @@ -307,9 +337,10 @@ export const enum WebGLCmd { END_RENDER_PASS, BIND_PIPELINE_STATE, BIND_INPUT_ASSEMBLER, - BIND_BINDING_SET_LAYOUT, + BIND_BINDING_LAYOUT, DRAW, UPDATE_BUFFER, + COPY_BUFFER_TO_TEXTURE, COUNT, }; @@ -353,12 +384,12 @@ export class WebGLCmdBindInputAssembler extends WebGLCmdObject { } }; -export class WebGLCmdBindBindingSetLayout extends WebGLCmdObject { +export class WebGLCmdBindBindingLayout extends WebGLCmdObject { - gpuBindingSetLayout: WebGLGPUBindingSetLayout | null = null; + gpuBindingLayout: WebGLGPUBindingLayout | null = null; constructor() { - super(WebGLCmd.BIND_BINDING_SET_LAYOUT); + super(WebGLCmd.BIND_BINDING_LAYOUT); } }; @@ -382,7 +413,7 @@ export class WebGLCmdDraw extends WebGLCmdObject { export class WebGLCmdUpdateBuffer extends WebGLCmdObject { gpuBuffer: WebGLGPUBuffer | null = null; - data: ArrayBuffer | null = null; + buffer: Buffer | null = null; offset: number = 0; constructor() { @@ -390,14 +421,27 @@ export class WebGLCmdUpdateBuffer extends WebGLCmdObject { } }; +export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { + + gpuBuffer: WebGLGPUBuffer | null = null; + gpuTexture: WebGLGPUTexture | null = null; + dstLayout: GFXTextureLayout | null = null; + regions: GFXBufferTextureCopy[] = []; + + constructor() { + super(WebGLCmd.COPY_BUFFER_TO_TEXTURE); + } +}; + export class WebGLCmdPackage { cmds: WebGLCmd[] = []; beginRenderPassCmds: WebGLCmdBeginRenderPass[] = []; bindPipelineStateCmds: WebGLCmdBindPipelineState[] = []; - bindBindingSetLayoutCmds: WebGLCmdBindBindingSetLayout[] = []; + bindBindingLayoutCmds: WebGLCmdBindBindingLayout[] = []; bindInputAssemblerCmds: WebGLCmdBindInputAssembler[] = []; drawCmds: WebGLCmdDraw[] = []; updateBufferCmds: WebGLCmdUpdateBuffer[] = []; + copyBufferToTextureCmds: WebGLCmdCopyBufferToTexture[] = []; clearCmds(allocator: WebGLGFXCommandAllocator) { @@ -415,11 +459,11 @@ export class WebGLCmdPackage { this.bindPipelineStateCmds = []; } - if (this.bindBindingSetLayoutCmds.length) { - for (let i = 0; i < this.bindBindingSetLayoutCmds.length; ++i) { - allocator.bindBindingSetLayoutCmdPool.free(this.bindBindingSetLayoutCmds[i]); + if (this.bindBindingLayoutCmds.length) { + for (let i = 0; i < this.bindBindingLayoutCmds.length; ++i) { + allocator.bindBindingLayoutCmdPool.free(this.bindBindingLayoutCmds[i]); } - this.bindBindingSetLayoutCmds = []; + this.bindBindingLayoutCmds = []; } if (this.bindInputAssemblerCmds.length) { @@ -443,13 +487,20 @@ export class WebGLCmdPackage { this.updateBufferCmds = []; } + if (this.copyBufferToTextureCmds.length) { + for (let i = 0; i < this.copyBufferToTextureCmds.length; ++i) { + allocator.copyBufferToTextureCmdPool.free(this.copyBufferToTextureCmds[i]); + } + this.copyBufferToTextureCmds = []; + } + this.cmds = []; } } export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { - let gl: WebGLRenderingContext = device.gl; + let gl = device.gl; if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { @@ -467,7 +518,7 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); - device.stateCache.glArrayBuffer = null; + device.stateCache.glArrayBuffer = 0; } } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { @@ -485,14 +536,14 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); - device.stateCache.glElementArrayBuffer = null; + device.stateCache.glElementArrayBuffer = 0; } } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { - console.error("WebGL 1.0 doesn't support uniform buffer."); + //console.error("WebGL 1.0 doesn't support uniform buffer."); gpuBuffer.glTarget = WebGLRenderingContext.NONE; - } else if (gpuBuffer.usage === GFXBufferUsageBit.TRANSFER_DST) { + } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_DST) { gpuBuffer.glTarget = WebGLRenderingContext.NONE; - } else if (gpuBuffer.usage === GFXBufferUsageBit.TRANSFER_SRC) { + } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) { gpuBuffer.glTarget = WebGLRenderingContext.NONE; } else { console.error("Unsupported GFXBufferType, create buffer failed."); @@ -509,7 +560,7 @@ export function WebGLCmdFuncDestroyBuffer(device: WebGLGFXDevice, gpuBuffer: Web export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: Buffer) { - let gl: WebGLRenderingContext = device.gl; + let gl = device.gl; switch (gpuBuffer.glTarget) { case WebGLRenderingContext.ARRAY_BUFFER: { @@ -517,6 +568,7 @@ export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer.buffer); break; } case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { @@ -524,29 +576,18 @@ export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer.buffer); break; } default: { console.error("Unsupported GFXBufferType, update buffer failed."); - return; } } - - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer.buffer); -} - -export function WebGLCmdFuncCreateInputState(device: WebGLGFXDevice, gpuInputState: WebGLGPUInputAssembler) { -} - -export function WebGLCmdFuncDestroyInputState(device: WebGLGFXDevice, gpuInputState: WebGLGPUInputAssembler) { - /*if(gpuInputState.glVAO > 0) { - gpuInputState.glVAO = 0; - }*/ } export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { - let gl: WebGLRenderingContext = device.gl; + let gl = device.gl; gpuTexture.glInternelFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format); @@ -561,10 +602,11 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We let glTexture = gl.createTexture(); if (glTexture) { gpuTexture.glTexture = glTexture; + let glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; - if (device.stateCache.glTex2DUnits[device.stateCache.texUnit] !== gpuTexture.glTexture) { + if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); - device.stateCache.glTex2DUnits[device.stateCache.texUnit] = gpuTexture.glTexture; + glTexUnit.glTexture = gpuTexture.glTexture; } let w = gpuTexture.width; @@ -596,10 +638,11 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We let glTexture = gl.createTexture(); if (glTexture) { gpuTexture.glTexture = glTexture; + let glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; - if (device.stateCache.glTexCubeUnits[device.stateCache.texUnit] !== gpuTexture.glTexture) { + if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); - device.stateCache.glTexCubeUnits[device.stateCache.texUnit] = gpuTexture.glTexture; + glTexUnit.glTexture = gpuTexture.glTexture; } if (!GFXFormatInfos[gpuTexture.format].isCompressed) { @@ -648,7 +691,7 @@ export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebu if (!gpuFramebuffer.isOffscreen) { - let gl: WebGLRenderingContext = device.gl; + let gl = device.gl; let glFramebuffer = gl.createFramebuffer(); if (glFramebuffer) { @@ -696,7 +739,7 @@ export function WebGLCmdFuncDestroyFramebuffer(device: WebGLGFXDevice, gpuFrameb } export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { - let gl: WebGLRenderingContext = device.gl; + let gl = device.gl; for (let i = 0; i < gpuShader.gpuStages.length; ++i) { let gpuStage = gpuShader.gpuStages[i]; @@ -800,7 +843,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // create uniform blocks - if (gpuShader.blocks.length > 0) { + if (gpuShader.blocks && gpuShader.blocks.length > 0) { gpuShader.glBlocks = new Array(gpuShader.blocks.length); for (let i = 0; i < gpuShader.blocks.length; ++i) { let block = gpuShader.blocks[i]; @@ -808,6 +851,61 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG glBlock.isUniformPackage = true; glBlock.binding = block.binding; glBlock.name = block.name; + glBlock.glUniforms = new Array(block.uniforms.length); + + for (let u = 0; u < block.uniforms.length; ++u) { + let uniform = block.uniforms[u]; + let glUniform = glBlock.glUniforms[u]; + + glUniform.name = uniform.name; + glUniform.type = uniform.type; + glUniform.glType = GFXTypeToWebGLType(glUniform.type); + glUniform.stride = WebGLGetTypeSize(glUniform.glType); + glUniform.count = uniform.count; + glUniform.size = glUniform.stride * uniform.count; + glUniform.offset = glBlock.size; + + glBlock.size += glUniform.size; + } + + glBlock.buffer = new ArrayBuffer(glBlock.size); + glBlock.bufferView = new Buffer(glBlock.buffer); + + for (let u = 0; u < glBlock.glUniforms.length; ++u) { + let glUniform = glBlock.glUniforms[u]; + if (glUniform.glLoc >= 0) { + switch (glUniform.glType) { + case WebGLRenderingContext.BOOL: + case WebGLRenderingContext.BOOL_VEC2: + case WebGLRenderingContext.BOOL_VEC3: + case WebGLRenderingContext.BOOL_VEC4: + case WebGLRenderingContext.INT: + case WebGLRenderingContext.INT_VEC3: + case WebGLRenderingContext.INT_VEC2: + case WebGLRenderingContext.INT_VEC4: { + glUniform.bufferView = new Int32Array(glBlock.buffer, glUniform.offset, glUniform.count); + break; + } + default: { + glUniform.bufferView = new Float32Array(glBlock.buffer, glUniform.offset, glUniform.count); + } + } + } + } // for + } + } + + // create uniform samplers + if (gpuShader.samplers && gpuShader.samplers.length > 0) { + gpuShader.glSamplers = new Array(gpuShader.samplers.length); + + for (let i = 0; i < gpuShader.samplers.length; ++i) { + let sampler = gpuShader.samplers[i]; + let glSampler = gpuShader.glSamplers[i]; + glSampler.binding = sampler.binding; + glSampler.name = sampler.name; + glSampler.type = sampler.type; + glSampler.glType = GFXTypeToWebGLType(glSampler.type); } } @@ -834,34 +932,19 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG (type === WebGLRenderingContext.SAMPLER_CUBE); if (!isSampler) { - let stride = WebGLGetTypeSize(info.type); + //let stride = WebGLGetTypeSize(info.type); // build uniform block mapping - for (let b = 0; b < gpuShader.blocks.length; ++b) { + for (let b = 0; b < gpuShader.glBlocks.length; ++b) { - let block = gpuShader.blocks[b]; let glBlock = gpuShader.glBlocks[b]; - for (let u = 0; u < block.uniforms.length; ++u) { - let uniform = block.uniforms[u]; - if (uniform.name === varName) { - let varSize = stride * info.size; + for (let u = 0; u < glBlock.glUniforms.length; ++u) { + let glUniform = glBlock.glUniforms[u]; + if (glUniform.name === varName) { + //let varSize = stride * info.size; - glBlock.glUniforms.push({ - binding: -1, - name: varName, - type: type, - stride: stride, - count: info.size, - size: varSize, - offset: glBlock.size, - - glType: info.type, - glLoc: glLoc, - bufferView: null, - }); - - glBlock.size += varSize; + glUniform.glLoc = glLoc; break; } @@ -869,55 +952,27 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // for } else { - let units = new Array(info.size); - for (let u = 0; u < info.size; ++u) { - units[u] = unitIdx + u; - } + for (let s = 0; s < gpuShader.glSamplers.length; ++s) { + let glSampler = gpuShader.glSamplers[s]; + if (glSampler.name === varName) { + //let varSize = stride * info.size; - gpuShader.glSamplers.push({ - binding: -1, - name: varName, - type: type, - units: units, + glSampler.units = new Array(info.size); + for (let t = 0; t < glSampler.units.length; ++t) { + glSampler.units[t] = unitIdx + t; + } - glType: info.type, - glLoc: glLoc, - }); + glSampler.glLoc = glLoc; - unitIdx += info.size; + unitIdx += info.size; + + break; + } + } // for } } } } // for - - for (let b = 0; b < gpuShader.glBlocks.length; ++b) { - - let glBlock = gpuShader.glBlocks[b]; - glBlock.buffer = new ArrayBuffer(glBlock.size); - glBlock.bufferView = new Buffer(glBlock.buffer); - - for (let u = 0; u < glBlock.glUniforms.length; ++u) { - let glUniform = glBlock.glUniforms[u]; - if(glUniform.glLoc >= 0) { - switch (glUniform.glType) { - case WebGLRenderingContext.BOOL: - case WebGLRenderingContext.BOOL_VEC2: - case WebGLRenderingContext.BOOL_VEC3: - case WebGLRenderingContext.BOOL_VEC4: - case WebGLRenderingContext.INT: - case WebGLRenderingContext.INT_VEC3: - case WebGLRenderingContext.INT_VEC2: - case WebGLRenderingContext.INT_VEC4: { - glUniform.bufferView = new Int32Array(glBlock.buffer, glUniform.offset, glUniform.count); - break; - } - default: { - glUniform.bufferView = new Float32Array(glBlock.buffer, glUniform.offset, glUniform.count); - } - } - } - } - } } export function WebGLCmdFuncDestroyShader(device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { @@ -955,16 +1010,22 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput for (let j = 0; j < gpuInputAssembler.attributes.length; ++j) { let attrib = gpuInputAssembler.attributes[j]; - if (glInput.name === attrib.name && attrib.stream < gpuInputAssembler.gpuVertexBuffers.length) { - let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[attrib.stream]; + let stream = attrib.stream ? attrib.stream : 0; + + if (glInput.name === attrib.name && stream < gpuInputAssembler.gpuVertexBuffers.length) { + + let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; glAttrib.count = GFXFormatInfos[attrib.format].count; glAttrib.stride = gpuBuffer.stride; glAttrib.glBuffer = gpuBuffer.glBuffer; - glAttrib.isInstanced = attrib.isInstanced; - glAttrib.offset = offsets[attrib.stream]; - offsets[attrib.stream] += glInput.size; + if (attrib.isInstanced) { + glAttrib.isInstanced = attrib.isInstanced; + } + + glAttrib.offset = offsets[stream]; + offsets[stream] += glInput.size; break; } } @@ -977,14 +1038,15 @@ export function WebGLCmdFuncDestroyInputAssembler(device: WebGLGFXDevice, gpuInp export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { - let gl: WebGLRenderingContext = device.gl; + let gl = device.gl; let beginRenderPassCmdIdx = 0; let bindPipelineStateCmdIdx = 0; - let bindBindingSetLayoutCmdIdx = 0; + let bindBindingLayoutCmdIdx = 0; let bindInputAssemblerCmdIdx = 0; let drawCmdIdx = 0; let updateBufferCmdIdx = 0; + let copyBufferToTextureCmdIdx = 0; let gpuShader: WebGLGPUShader | null = null; let gpuInputAssembler: WebGLGPUInputAssembler | null = null; @@ -994,7 +1056,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG switch (cmdPackage.cmds[i]) { case WebGLCmd.BEGIN_RENDER_PASS: { let cmd = cmdPackage.beginRenderPassCmds[beginRenderPassCmdIdx++]; - //curGPUFramebuffer = cmd.gpuFramebuffer; let clears: GLbitfield = 0; @@ -1410,12 +1471,12 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } - case WebGLCmd.BIND_BINDING_SET_LAYOUT: { + case WebGLCmd.BIND_BINDING_LAYOUT: { - let cmd = cmdPackage.bindBindingSetLayoutCmds[bindBindingSetLayoutCmdIdx++]; - if (cmd.gpuBindingSetLayout && gpuShader) { - for (let n = 0; n < cmd.gpuBindingSetLayout.gpuBinding.length; ++n) { - let gpuBinding = cmd.gpuBindingSetLayout.gpuBinding[n]; + let cmd = cmdPackage.bindBindingLayoutCmds[bindBindingLayoutCmdIdx++]; + if (cmd.gpuBindingLayout && gpuShader) { + for (let n = 0; n < cmd.gpuBindingLayout.gpuBindings.length; ++n) { + let gpuBinding = cmd.gpuBindingLayout.gpuBindings[n]; switch (gpuBinding.type) { case GFXBindingType.UNIFORM_BUFFER: { @@ -1434,7 +1495,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG if (glBlock && glBlock.bufferView) { for (let u = 0; u < glBlock.glUniforms.length; ++u) { let glUniform = glBlock.glUniforms[u]; - if (glUniform.glLoc >= 0 && + if (glUniform.glLoc >= 0 && glBlock.bufferView.compare(gpuBinding.gpuBuffer.buffer, glUniform.offset, glUniform.size, glUniform.offset, glUniform.size) != 0) { switch (glUniform.glType) { @@ -1492,6 +1553,92 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } } } // if + + break; + } + case GFXBindingType.SAMPLER: { + + if (gpuBinding.gpuSampler && gpuBinding.gpuTexView && gpuBinding.gpuTexView.gpuTexture) { + + let glSampler: WebGLGPUUniformSampler | null = null; + + for (let s = 0; s < gpuShader.glSamplers.length; ++s) { + if (gpuShader.glSamplers[s].binding === gpuBinding.binding) { + glSampler = gpuShader.glSamplers[s]; + break; + } + } + + if (glSampler) { + let gpuTexture = gpuBinding.gpuTexView.gpuTexture; + + for (let u = 0; u < glSampler.units.length; ++u) { + + let texUnit = glSampler.units[u]; + if (device.stateCache.texUnit !== texUnit) { + gl.activeTexture(WebGLRenderingContext.TEXTURE0 + u); + device.stateCache.texUnit == texUnit; + } + + let glTexUnit: WebGLTexUnit | null = null; + + switch (glSampler.glType) { + case WebGLRenderingContext.SAMPLER_2D: { + glTexUnit = device.stateCache.glTex2DUnits[texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + break; + } + case WebGLRenderingContext.SAMPLER_CUBE: { + glTexUnit = device.stateCache.glTexCubeUnits[texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + break; + } + default: { + console.error("Unsupported GL Texture type."); + } + } + + if (glTexUnit) { + let gpuSampler = gpuBinding.gpuSampler; + + if (glTexUnit.minFilter !== gpuSampler.glMinFilter) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuSampler.glMinFilter); + glTexUnit.minFilter = gpuSampler.glMinFilter; + } + + if (glTexUnit.magFilter !== gpuSampler.glMagFilter) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter); + glTexUnit.magFilter = gpuSampler.glMagFilter; + } + + if (glTexUnit.wrapS !== gpuSampler.glWrapS) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuSampler.glWrapS); + glTexUnit.wrapS = gpuSampler.glWrapS; + } + + if (glTexUnit.wrapT !== gpuSampler.glWrapT) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuSampler.glWrapT); + glTexUnit.wrapT = gpuSampler.glWrapT; + } + + /* + if(glTexUnit.wrapR !== gpuSampler.glWrapR) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_R, gpuSampler.glWrapR); + glTexUnit.wrapR = gpuSampler.glWrapR; + } + */ + } + } + } // if + } // if + break; } } @@ -1559,7 +1706,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLCmd.UPDATE_BUFFER: { - let cmd = cmdPackage.updateBufferCmds[updateBufferCmdIdx++]; if (cmd.gpuBuffer) { switch (cmd.gpuBuffer.glTarget) { @@ -1583,8 +1729,135 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } } - if (cmd.data) { - gl.bufferSubData(cmd.gpuBuffer.glTarget, cmd.offset, cmd.data); + if (cmd.buffer) { + gl.bufferSubData(cmd.gpuBuffer.glTarget, cmd.offset, cmd.buffer); + } + } + + break; + } + case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { + let cmd = cmdPackage.copyBufferToTextureCmds[copyBufferToTextureCmdIdx++]; + if (cmd.gpuBuffer && cmd.gpuBuffer.buffer && cmd.gpuTexture) { + switch (cmd.gpuTexture.glTarget) { + case WebGLRenderingContext.TEXTURE_2D: { + let texUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + if (texUnit.glTexture !== cmd.gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, cmd.gpuTexture.glTexture); + texUnit.glTexture = cmd.gpuTexture.glTexture; + } + + let isCompressed = GFXFormatInfos[cmd.gpuTexture.format].isCompressed; + if (!isCompressed) { + for (let r = 0; r < cmd.regions.length; ++r) { + let region = cmd.regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + let w = region.texExtent[0]; + let h = region.texExtent[1]; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); + let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset[0], region.texOffset[1], w, h, + cmd.gpuTexture.glFormat, cmd.gpuTexture.glType, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } else { + for (let r = 0; r < cmd.regions.length; ++r) { + let region = cmd.regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + let w = region.texExtent[0]; + let h = region.texExtent[1]; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); + let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset[0], region.texOffset[1], w, h, + cmd.gpuTexture.glFormat, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + break; + } + case WebGLRenderingContext.TEXTURE_CUBE_MAP: { + let texUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + if (texUnit.glTexture !== cmd.gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, cmd.gpuTexture.glTexture); + texUnit.glTexture = cmd.gpuTexture.glTexture; + } + + let isCompressed = GFXFormatInfos[cmd.gpuTexture.format].isCompressed; + if (!isCompressed) { + for (let r = 0; r < cmd.regions.length; ++r) { + let region = cmd.regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + for (let f = 0; f < 6; ++f) { + let w = region.texExtent[0]; + let h = region.texExtent[1]; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); + let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, + region.texOffset[0], region.texOffset[1], w, h, + cmd.gpuTexture.glFormat, cmd.gpuTexture.glType, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + } else { + for (let r = 0; r < cmd.regions.length; ++r) { + let region = cmd.regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + for (let f = 0; f < 6; ++f) { + let w = region.texExtent[0]; + let h = region.texExtent[1]; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); + let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, + region.texOffset[0], region.texOffset[1], w, h, + cmd.gpuTexture.glFormat, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + } + break; + } + default: { + console.error("Unsupported GL texture type, copy buffer to texture failed."); + continue; + } + } + + if (cmd.gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { + gl.generateMipmap(cmd.gpuTexture.glTarget); } } diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts b/cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts new file mode 100644 index 0000000000..8a484b6712 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts @@ -0,0 +1,51 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGPUBindingLayout } from './webgl-gpu-objects'; +import { GFXBindingLayout, GFXBindingLayoutInfo, GFXBindingUnit } from '../gfx-binding-layout'; + +export class WebGLGFXBindingLayout extends GFXBindingLayout { + + constructor(device: GFXDevice) { + super(device); + } + + public initialize(info: GFXBindingLayoutInfo): boolean { + + this._bindingUnits = new Array(info.bindings.length); + for (let i = 0; i < info.bindings.length; ++i) { + let binding = info.bindings[i]; + let bindingUnit = this._bindingUnits[i]; + bindingUnit.binding = binding.binding; + bindingUnit.type = binding.type; + bindingUnit.name = binding.name; + } + + this._gpuBindingLayout = this.webGLDevice.emitCmdCreateGPUBindingLayout(info); + + return true; + } + + public destroy() { + if (this._gpuBindingLayout) { + this.webGLDevice.emitCmdDestroyGPUBindingLayout(this._gpuBindingLayout); + this._gpuBindingLayout = null; + } + } + + public update() { + if (this._gpuBindingLayout) { + this.webGLDevice.emitCmdUpdateGPUBindingLayout(this._gpuBindingLayout, this._bindingUnits); + this._gpuBindingLayout = null; + } + } + + public get webGLDevice(): WebGLGFXDevice { + return this._device; + } + + public get gpuBindingLayout(): WebGLGPUBindingLayout | null { + return this._gpuBindingLayout; + } + + private _gpuBindingLayout: WebGLGPUBindingLayout | null = null; +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts b/cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts deleted file mode 100644 index f9667355ff..0000000000 --- a/cocos/renderer/gfx/webgl/webgl-gfx-binding-set-layout.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { GFXDevice } from '../gfx-device'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { WebGLGPUBindingSetLayout } from './webgl-gpu-objects'; -import { GFXBindingSetLayout, GFXBindingSetLayoutInfo, GFXBindingType } from '../gfx-binding-set-layout'; -import { GFXBuffer } from '../gfx-buffer'; -import { GFXSampler } from '../gfx-sampler'; -import { GFXTextureView } from '../gfx-texture-view'; - -export class WebGLGFXBindingSetLayout extends GFXBindingSetLayout { - - constructor(device: GFXDevice) { - super(device); - } - - public initialize(info: GFXBindingSetLayoutInfo): boolean { - - for (let i = 0; i < info.bindings.length; ++i) { - let binding = info.bindings[i]; - - this._bindingUnits.push({ - binding: binding.binding, - type: binding.type, - name: binding.name, - buffer: null, - texView: null, - sampler: null, - }); - } - - this._gpuBindingSetLayout = this.webGLDevice.emitCmdCreateGPUBindingSetLayout(info); - - return true; - } - - public destroy() { - if (this._gpuBindingSetLayout) { - this.webGLDevice.emitCmdDestroyGPUBindingSetLayout(this._gpuBindingSetLayout); - this._gpuBindingSetLayout = null; - } - } - - public update() { - - } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuBindingSetLayout(): WebGLGPUBindingSetLayout | null { - return this._gpuBindingSetLayout; - } - - private _gpuBindingSetLayout: WebGLGPUBindingSetLayout | null = null; -}; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts index afd0528b18..5e68f99cb9 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts @@ -14,18 +14,15 @@ export class WebGLGFXBuffer extends GFXBuffer { this._usage = info.usage; this._memUsage = info.memUsage; this._size = info.size; - this._stride = info.stride; + this._stride = info.stride? info.stride : 1; if (this._memUsage & GFXMemoryUsageBit.HOST) { this._arrayBuffer = new ArrayBuffer(this._size); this._buffer = new Buffer(this._arrayBuffer); } - this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; - - if (!this._isSimulate || this._usage & GFXBufferUsageBit.UNIFORM) { - this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); - } + //this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; + this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); return true; } @@ -46,9 +43,7 @@ export class WebGLGFXBuffer extends GFXBuffer { this._buffer.set(buffer, offset); } - if (!this._isSimulate && this._buffer) { - this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, this._buffer); - } + this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, buffer); } public get webGLDevice(): WebGLGFXDevice { @@ -60,5 +55,4 @@ export class WebGLGFXBuffer extends GFXBuffer { } private _gpuBuffer: WebGLGPUBuffer | null = null; - private _isSimulate: boolean = false; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts b/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts index 615627a5a1..4c6ba5256b 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts @@ -1,6 +1,6 @@ import { GFXDevice } from '../gfx-device'; -import { GFXCommandAllocator } from '../gfx-command-allocator'; -import { WebGLCmdUpdateBuffer, WebGLCmdBeginRenderPass, WebGLCmdBindInputAssembler, WebGLCmdDraw, WebGLCmdBindPipelineState, WebGLCmdBindBindingSetLayout } from './webgl-commands'; +import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../gfx-command-allocator'; +import { WebGLCmdUpdateBuffer, WebGLCmdBeginRenderPass, WebGLCmdBindInputAssembler, WebGLCmdDraw, WebGLCmdBindPipelineState, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; export class WebGLGFXCommandPool { @@ -47,22 +47,24 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { beginRenderPassCmdPool : WebGLGFXCommandPool; bindPipelineStateCmdPool : WebGLGFXCommandPool; - bindBindingSetLayoutCmdPool : WebGLGFXCommandPool; + bindBindingLayoutCmdPool : WebGLGFXCommandPool; bindInputAssemblerCmdPool : WebGLGFXCommandPool; drawCmdPool : WebGLGFXCommandPool; updateBufferCmdPool : WebGLGFXCommandPool; + copyBufferToTextureCmdPool : WebGLGFXCommandPool; constructor(device : GFXDevice) { super(device); this.beginRenderPassCmdPool = new WebGLGFXCommandPool(64, 32); this.bindPipelineStateCmdPool = new WebGLGFXCommandPool(64, 32); - this.bindBindingSetLayoutCmdPool = new WebGLGFXCommandPool(64, 32); + this.bindBindingLayoutCmdPool = new WebGLGFXCommandPool(64, 32); this.bindInputAssemblerCmdPool = new WebGLGFXCommandPool(64, 32); this.drawCmdPool = new WebGLGFXCommandPool(64, 32); this.updateBufferCmdPool = new WebGLGFXCommandPool(64, 32); + this.copyBufferToTextureCmdPool = new WebGLGFXCommandPool(64, 32); } - public initialize() : boolean { + public initialize(info: GFXCommandAllocatorInfo) : boolean { return true; } diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts index abd0edb1a1..8ad6fc47dc 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts @@ -1,7 +1,7 @@ import { GFXDevice } from '../gfx-device'; -import { GFXCommandBuffer, GFXCommandBufferInfo } from '../gfx-command-buffer'; +import { GFXCommandBuffer, GFXCommandBufferInfo, GFXBufferTextureCopy } from '../gfx-command-buffer'; import { GFXBuffer } from '../gfx-buffer'; -import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw } from './webgl-commands'; +import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; import { WebGLGFXDevice } from './webgl-gfx-device'; import { WebGLGFXBuffer } from './webgl-gfx-buffer'; @@ -10,9 +10,12 @@ import { WebGLGFXFramebuffer } from './webgl-gfx-framebuffer'; import { GFXInputAssembler } from '../gfx-input-assembler'; import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; import { GFXPipelineState } from '../gfx-pipeline-state'; -import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; import { WebGLGFXPipelineState } from './webgl-gfx-pipeline-state'; -import { GFXBindingSetLayout } from '../gfx-binding-set-layout'; +import { GFXBindingLayout } from '../gfx-binding-layout'; +import { WebGLGFXBindingLayout } from './webgl-gfx-binding-layout'; +import { GFXTexture } from '../gfx-texture'; +import { GFXTextureLayout } from '../gfx-render-pass'; +import { WebGLGFXTexture } from './webgl-gfx-texture'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { @@ -47,11 +50,9 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public end() { - } public beginRenderPass(framebuffer : GFXFramebuffer, viewport : number[], numClearColors : number, clearColors : number[], clearStencil : number) { - let cmd = (this._allocator).beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); if (cmd) { cmd.gpuFramebuffer = (framebuffer).gpuFramebuffer; @@ -66,11 +67,9 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public endRenderPass() { - } public bindPipelineState(pipelineState : GFXPipelineState) { - let cmd = (this._allocator).bindPipelineStateCmdPool.alloc(WebGLCmdBindPipelineState); if (cmd) { cmd.gpuPipelineState = (pipelineState).gpuPipelineState; @@ -80,10 +79,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public bindBindingSetLayout(bindingSetLayout : GFXBindingSetLayout) { - - // TODO + public bindBindingLayout(bindingLayout : GFXBindingLayout) { + let cmd = (this._allocator).bindBindingLayoutCmdPool.alloc(WebGLCmdBindBindingLayout); + if (cmd) { + cmd.gpuBindingLayout= (bindingLayout).gpuBindingLayout; + this.cmdPackage.bindBindingLayoutCmds.push(cmd); + this.cmdPackage.cmds.push(WebGLCmd.BIND_BINDING_LAYOUT); + } } public bindInputAssembler(inputAssembler : GFXInputAssembler) { @@ -114,14 +117,13 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset : number) { - + public updateBuffer(buffer : GFXBuffer, data : Buffer, offset : number) { let gpuBuffer = (buffer).gpuBuffer; if(gpuBuffer) { let cmd = (this._allocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { cmd.gpuBuffer = gpuBuffer; - cmd.data = data.slice(0); + cmd.buffer = data.slice(0); cmd.offset = offset; this.cmdPackage.updateBufferCmds.push(cmd); @@ -130,6 +132,39 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } + public copyBufferToTexture(srcBuff : GFXBuffer, dstTex : GFXTexture, dstLayout: GFXTextureLayout, regions : GFXBufferTextureCopy[]) { + let gpuBuffer = (srcBuff).gpuBuffer; + let gpuTexture = (dstTex).gpuTexture; + if(gpuBuffer && gpuTexture) { + let cmd = (this._allocator).copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); + if (cmd) { + cmd.gpuBuffer = gpuBuffer; + cmd.gpuTexture = gpuTexture; + cmd.dstLayout = dstLayout; + cmd.regions = regions; + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE); + } + } + } + + public execute(cmdBuffs : GFXCommandBuffer[]) { + + for(let i = 0; i < cmdBuffs.length; ++i) { + let webGLCmdBuff = cmdBuffs[i]; + + this.cmdPackage.beginRenderPassCmds = this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); + this.cmdPackage.bindPipelineStateCmds = this.cmdPackage.bindPipelineStateCmds.concat(webGLCmdBuff.cmdPackage.bindPipelineStateCmds); + this.cmdPackage.bindBindingLayoutCmds = this.cmdPackage.bindBindingLayoutCmds.concat(webGLCmdBuff.cmdPackage.bindBindingLayoutCmds); + this.cmdPackage.bindInputAssemblerCmds = this.cmdPackage.bindInputAssemblerCmds.concat(webGLCmdBuff.cmdPackage.bindInputAssemblerCmds); + this.cmdPackage.drawCmds = this.cmdPackage.drawCmds.concat(webGLCmdBuff.cmdPackage.drawCmds); + this.cmdPackage.updateBufferCmds = this.cmdPackage.updateBufferCmds.concat(webGLCmdBuff.cmdPackage.updateBufferCmds); + this.cmdPackage.copyBufferToTextureCmds = this.cmdPackage.copyBufferToTextureCmds.concat(webGLCmdBuff.cmdPackage.copyBufferToTextureCmds); + this.cmdPackage.cmds = this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); + } + } + public get webGLDevice() : WebGLGFXDevice { return this._device; } diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index 709b41c2e5..9733cd6d82 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -1,26 +1,36 @@ import { GFXDeviceInfo, GFXDevice } from '../gfx-device'; -import { GFXBuffer, GFXBufferInfo } from '../gfx-buffer'; +import { GFXBuffer, GFXBufferInfo, GFXBufferUsageBit } from '../gfx-buffer'; import { WebGLGFXBuffer } from './webgl-gfx-buffer'; import { WebGLGFXQueue } from './webgl-gfx-queue'; import { WebGLStateCache } from './webgl-state-cache'; -import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingSetLayout, WebGLGPUBinding } from './webgl-gpu-objects'; +import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncDestroyInputAssembler } from './webgl-commands'; -import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit } from '../gfx-texture'; -import { GFXTextureViewType, GFXTextureViewInfo } from '../gfx-texture-view'; -import { GFXRenderPassInfo } from '../gfx-render-pass'; -import { GFXFramebufferInfo } from '../gfx-framebuffer'; +import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit, GFXTexture } from '../gfx-texture'; +import { GFXTextureViewType, GFXTextureViewInfo, GFXTextureView } from '../gfx-texture-view'; +import { GFXRenderPassInfo, GFXRenderPass } from '../gfx-render-pass'; +import { GFXFramebufferInfo, GFXFramebuffer } from '../gfx-framebuffer'; import { WebGLGFXRenderPass } from './webgl-gfx-render-pass'; import { WebGLGFXTextureView } from './webgl-gfx-texture-view'; import { WebGLGFXTexture } from './webgl-gfx-texture'; -import { GFXShaderInfo } from '../gfx-shader'; -import { GFXSamplerInfo } from '../gfx-sampler'; +import { GFXShaderInfo, GFXShader } from '../gfx-shader'; +import { GFXSamplerInfo, GFXFilter, GFXSampler, GFXAddress } from '../gfx-sampler'; import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; -import { GFXInputAssemblerInfo } from '../gfx-input-assembler'; +import { GFXInputAssemblerInfo, GFXInputAssembler } from '../gfx-input-assembler'; import { WebGLGFXShader } from './webgl-gfx-shader'; -import { GFXCommandAllocator } from '../gfx-command-allocator'; -import { GFXPipelineStateInfo } from '../gfx-pipeline-state'; +import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../gfx-command-allocator'; +import { GFXPipelineStateInfo, GFXPipelineState, GFXPrimitiveMode, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from '../gfx-pipeline-state'; import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; -import { GFXBindingSetLayoutInfo } from '../gfx-binding-set-layout'; +import { GFXBindingLayoutInfo, GFXBinding, GFXBindingUnit, GFXBindingType } from '../gfx-binding-layout'; +import { WebGLGFXSampler } from './webgl-gfx-sampler'; +import { GFXCommandBufferInfo, GFXCommandBuffer } from '../gfx-command-buffer'; +import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; +import { WebGLGFXCommandBuffer } from './webgl-gfx-command-buffer'; +import { WebGLGFXPipelineState } from './webgl-gfx-pipeline-state'; +import { GFXPipelineLayoutInfo, GFXPipelineLayout } from '../gfx-pipeline-layout'; +import { WebGLGFXFramebuffer } from './webgl-gfx-framebuffer'; +import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; +import { GFXWindowInfo, GFXWindow } from '../gfx-window'; +import { WebGLGFXWindow } from './webgl-gfx-window'; const WebGLPrimitives: GLenum[] = [ WebGLRenderingContext.POINTS, @@ -39,22 +49,45 @@ const WebGLPrimitives: GLenum[] = [ WebGLRenderingContext.NONE, ]; +const WebGLWraps: GLenum[] = [ + WebGLRenderingContext.REPEAT, + WebGLRenderingContext.MIRRORED_REPEAT, + WebGLRenderingContext.CLAMP_TO_EDGE, + WebGLRenderingContext.CLAMP_TO_EDGE, +]; + export class WebGLGFXDevice extends GFXDevice { stateCache: WebGLStateCache = new WebGLStateCache; - webGLCmdAllocator: WebGLGFXCommandAllocator; + //webGLCmdAllocator: WebGLGFXCommandAllocator; constructor(canvasEL: HTMLElement) { super(); - this.webGLCmdAllocator = new WebGLGFXCommandAllocator(this); + //this.webGLCmdAllocator = new WebGLGFXCommandAllocator(this); + } + + public initialize(info: GFXDeviceInfo): boolean { + + this._canvasElm = info.canvasElm; try { - this._webGLRC = (canvasEL).getContext('webgl'); + let webGLCtxAttribs: WebGLContextAttributes = { + alpha: true, + antialias: true, + depth: true, + stencil: true, + premultipliedAlpha: true, + preserveDrawingBuffer: false, + powerPreference: "default", + failIfMajorPerformanceCaveat: false, + }; + + this._webGLRC = this._canvasElm.getContext('webgl', webGLCtxAttribs); } catch (err) { console.error(err); - return; + return false; } // No errors are thrown using try catch @@ -62,27 +95,169 @@ export class WebGLGFXDevice extends GFXDevice { if (!this._webGLRC) { console.error('This device does not support WebGL.'); } - } - public initialize(info: GFXDeviceInfo): boolean { + this._deviceName = "WebGL"; + + this._primaryWindow = this.createWindow({ + title: this._canvasElm.title, + left: this._canvasElm.offsetLeft, + top: this._canvasElm.offsetTop, + width: this._canvasElm.width, + height: this._canvasElm.height, + }); return true; } public destroy(): void { + if (this._primaryWindow) { + this._primaryWindow.destroy(); + this._primaryWindow = null; + } + + this._canvasElm = null; } - public createBuffer(): GFXBuffer { - return new WebGLGFXBuffer(this); + public createBuffer(info: GFXBufferInfo): GFXBuffer | null { + let buffer = new WebGLGFXBuffer(this); + if (buffer.initialize(info)) { + return buffer; + } else { + buffer.destroy(); + return null; + } } - public createCommandAllocator(): GFXCommandAllocator { - return new WebGLGFXCommandAllocator(this); + public createTexture(info: GFXTextureInfo): GFXTexture | null { + let texture = new WebGLGFXTexture(this); + if (texture.initialize(info)) { + return texture; + } else { + texture.destroy(); + return null; + } } - public getDeviceName(): string { - return "WebGLDevice"; + public createTextureView(info: GFXTextureViewInfo): GFXTextureView | null { + let texView = new WebGLGFXTextureView(this); + if (texView.initialize(info)) { + return texView; + } else { + texView.destroy(); + return null; + } + } + + public createSampler(info: GFXSamplerInfo): GFXSampler | null { + let sampler = new WebGLGFXSampler(this); + if (sampler.initialize(info)) { + return sampler; + } else { + sampler.destroy(); + return null; + } + } + + public createShader(info: GFXShaderInfo): GFXShader | null { + let shader = new WebGLGFXShader(this); + if (shader.initialize(info)) { + return shader; + } else { + shader.destroy(); + return null; + } + } + + public createInputAssembler(info: GFXInputAssemblerInfo): GFXInputAssembler | null { + let inputAssembler = new WebGLGFXInputAssembler(this); + if (inputAssembler.initialize(info)) { + return inputAssembler; + } else { + inputAssembler.destroy(); + return null; + } + } + + public createRenderPass(info: GFXRenderPassInfo): GFXRenderPass | null { + let renderPass = new WebGLGFXRenderPass(this); + if (renderPass.initialize(info)) { + return renderPass; + } else { + renderPass.destroy(); + return null; + } + } + + public createFramebuffer(info: GFXFramebufferInfo): GFXFramebuffer | null { + let framebuffer = new WebGLGFXFramebuffer(this); + if (framebuffer.initialize(info)) { + return framebuffer; + } else { + framebuffer.destroy(); + return null; + } + } + + public createPipelineLayout(info: GFXPipelineLayoutInfo): GFXPipelineLayout | null { + let pipelineLayout = new WebGLGFXPipelineLayout(this); + if (pipelineLayout.initialize(info)) { + return pipelineLayout; + } else { + pipelineLayout.destroy(); + return null; + } + } + + public createPipelineState(info: GFXPipelineStateInfo): GFXPipelineState | null { + let pipelineState = new WebGLGFXPipelineState(this); + if (pipelineState.initialize(info)) { + return pipelineState; + } else { + pipelineState.destroy(); + return null; + } + } + + public createCommandAllocator(info: GFXCommandAllocatorInfo): GFXCommandAllocator | null { + let cmdAllocator = new WebGLGFXCommandAllocator(this); + if (cmdAllocator.initialize(info)) { + return cmdAllocator; + } else { + cmdAllocator.destroy(); + return null; + } + } + + public createCommandBuffer(info: GFXCommandBufferInfo): GFXCommandBuffer | null { + let cmdBuff = new WebGLGFXCommandBuffer(this); + if (cmdBuff.initialize(info)) { + return cmdBuff; + } else { + cmdBuff.destroy(); + return null; + } + } + + public createQueue(info: GFXQueueInfo): GFXQueue | null { + let queue = new WebGLGFXQueue(this); + if (queue.initialize(info)) { + return queue; + } else { + queue.destroy(); + return null; + } + } + + public createWindow(info: GFXWindowInfo): GFXWindow | null { + let window = new WebGLGFXWindow(this); + if (window.initialize(info)) { + this._windows.push(window); + return window; + } else { + window.destroy(); + return null; + } } public get gl(): WebGLRenderingContext { @@ -93,28 +268,28 @@ export class WebGLGFXDevice extends GFXDevice { return this._queue; } - public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer : Buffer | null): WebGLGPUBuffer | null { + public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer: Buffer | null): WebGLGPUBuffer | null { let gpuBuffer: WebGLGPUBuffer = { objType: WebGLGPUObjectType.BUFFER, usage: info.usage, memUsage: info.memUsage, size: info.size, - stride: info.stride, + stride: info.stride ? info.stride : 1, arrayBuffer: null, buffer: null, glTarget: 0, glBuffer: 0, }; - if(buffer) { + if (buffer) { gpuBuffer.arrayBuffer = buffer.buffer; gpuBuffer.buffer = buffer; } + //let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncCreateBuffer(this, gpuBuffer); return gpuBuffer; @@ -124,13 +299,16 @@ export class WebGLGFXDevice extends GFXDevice { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncDestroyBuffer(this, gpuBuffer); } public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: Buffer) { // TODO: Async - WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, buffer); + let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; + let isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; + if (!isUBOSimulate && !isStagingBuffer) { + WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, buffer); + } } public emitCmdCreateGPUTexture(info: GFXTextureInfo): WebGLGPUTexture { @@ -139,19 +317,34 @@ export class WebGLGFXDevice extends GFXDevice { switch (info.type) { case GFXTextureType.TEX1D: { - viewType = info.arrayLayer <= 1 ? GFXTextureViewType.TV1D : GFXTextureViewType.TV1D_ARRAY; + + if (info.arrayLayer) { + viewType = info.arrayLayer <= 1 ? GFXTextureViewType.TV1D : GFXTextureViewType.TV1D_ARRAY; + } else { + viewType = GFXTextureViewType.TV1D; + } + break; } case GFXTextureType.TEX2D: { - - if (info.arrayLayer <= 1) { - viewType = GFXTextureViewType.TV2D; - } else if (info.arrayLayer === 6 && (info.flags & GFXTextureFlagBit.CUBEMAP)) { - viewType = GFXTextureViewType.CUBE; - } else { - viewType = GFXTextureViewType.TV2D_ARRAY; + let flags = GFXTextureFlagBit.NONE; + if (info.flags) { + flags = info.flags; } + if (info.arrayLayer) { + if (info.arrayLayer <= 1) { + viewType = GFXTextureViewType.TV2D; + } else if (info.arrayLayer === 6 && (flags & GFXTextureFlagBit.CUBEMAP)) { + viewType = GFXTextureViewType.CUBE; + } else { + viewType = GFXTextureViewType.TV2D_ARRAY; + } + } else { + viewType = GFXTextureViewType.TV2D; + } + + break; } case GFXTextureType.TEX3D: { @@ -171,10 +364,10 @@ export class WebGLGFXDevice extends GFXDevice { usage: info.usage, width: info.width, height: info.height, - depth: info.depth, - arrayLayer: info.arrayLayer, - mipLevel: info.mipLevel, - flags: info.flags, + depth: info.depth ? info.depth : 1, + arrayLayer: info.arrayLayer ? info.arrayLayer : 1, + mipLevel: info.mipLevel ? info.mipLevel : 1, + flags: info.flags ? info.flags : GFXTextureFlagBit.NONE, glTarget: 0, glInternelFmt: 0, @@ -206,8 +399,8 @@ export class WebGLGFXDevice extends GFXDevice { gpuTexture: webGLTexture.gpuTexture, type: info.type, format: info.format, - baseLevel: info.baseLevel, - levelCount: info.levelCount, + baseLevel: info.baseLevel ? info.baseLevel : 0, + levelCount: info.levelCount ? info.levelCount : 1, }; return gpuTextureView; @@ -216,8 +409,8 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { let gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, - colorAttachments: info.colorInfos, - depthStencilAttachment: info.depthStencilInfo, + colorAttachments: info.colorAttachment, + depthStencilAttachment: info.depthStencilAttachment, } return gpuRenderPass; @@ -232,18 +425,24 @@ export class WebGLGFXDevice extends GFXDevice { let gpuColorViews: (WebGLGPUTextureView | null)[] = new Array(); - for (let i = 0; i < info.colorViews.length; ++i) { - let webGLColorView = info.colorViews[i]; - gpuColorViews[i] = webGLColorView.gpuTextureView; + if (info.colorViews) { + for (let i = 0; i < info.colorViews.length; ++i) { + let webGLColorView = info.colorViews[i]; + gpuColorViews[i] = webGLColorView.gpuTextureView; + } } - let webGLDSView = info.depthStencilView; + let gpuDepthStencilView: WebGLGPUTextureView | null = null; + + if (info.depthStencilView) { + gpuDepthStencilView = (info.depthStencilView).gpuTextureView; + } let gpuFramebuffer: WebGLGPUFramebuffer = { objType: WebGLGPUObjectType.FRAMEBUFFER, gpuRenderPass: renderPass.gpuRenderPass, gpuColorViews: gpuColorViews, - gpuDepthStencilView: webGLDSView.gpuTextureView, + gpuDepthStencilView: gpuDepthStencilView, isOffscreen: info.isOffscreen, glFramebuffer: 0, }; @@ -261,20 +460,46 @@ export class WebGLGFXDevice extends GFXDevice { } public emitCmdCreateGPUSampler(info: GFXSamplerInfo): WebGLGPUSampler { + + let glMinFilter = WebGLRenderingContext.NONE; + let glMagFilter = WebGLRenderingContext.NONE; + + if (info.minFilter === GFXFilter.LINEAR || info.minFilter === GFXFilter.ANISOTROPIC) { + if (info.mipFilter === GFXFilter.LINEAR || info.mipFilter === GFXFilter.ANISOTROPIC) { + glMinFilter = WebGLRenderingContext.LINEAR_MIPMAP_LINEAR; + } else if (info.mipFilter === GFXFilter.POINT) { + glMinFilter = WebGLRenderingContext.LINEAR_MIPMAP_NEAREST; + } else { + glMinFilter = WebGLRenderingContext.LINEAR; + } + } else { + if (info.mipFilter === GFXFilter.LINEAR || info.mipFilter === GFXFilter.ANISOTROPIC) { + glMinFilter = WebGLRenderingContext.NEAREST_MIPMAP_LINEAR; + } else if (info.mipFilter === GFXFilter.POINT) { + glMinFilter = WebGLRenderingContext.NEAREST_MIPMAP_NEAREST; + } else { + glMinFilter = WebGLRenderingContext.NEAREST; + } + } + + if (info.magFilter === GFXFilter.LINEAR || info.magFilter === GFXFilter.ANISOTROPIC) { + glMagFilter = WebGLRenderingContext.LINEAR; + } else { + glMagFilter = WebGLRenderingContext.NEAREST; + } + + let glWrapS = info.addressU ? WebGLWraps[info.addressU] : GFXAddress.WRAP; + let glWrapT = info.addressV ? WebGLWraps[info.addressV] : GFXAddress.WRAP; + let glWrapR = info.addressW ? WebGLWraps[info.addressW] : GFXAddress.WRAP; + let gpuSampler: WebGLGPUSampler = { - objType: WebGLGPUObjectType.FRAMEBUFFER, - minFilter: info.minFilter, - magFilter: info.magFilter, - mipFilter: info.minFilter, - addressU: info.addressU, - addressV: info.addressV, - addressW: info.addressW, - maxAnisotropy: info.maxAnisotropy, - cmpFunc: info.cmpFunc, - borderColor: info.borderColor, - minLOD: info.minLOD, - maxLOD: info.maxLOD, - mipLODBias: info.mipLODBias, + objType: WebGLGPUObjectType.SAMPLER, + + glMinFilter: glMinFilter, + glMagFilter: glMagFilter, + glWrapS: glWrapS, + glWrapT: glWrapT, + glWrapR: glWrapR, }; return gpuSampler; @@ -286,23 +511,24 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPUShader(info: GFXShaderInfo): WebGLGPUShader { - let gpuStages: WebGLGPUShaderStage[] = []; + let gpuStages: WebGLGPUShaderStage[] = new Array(info.stages.length); + for (let i = 0; i < info.stages.length; ++i) { let stage = info.stages[i]; + let gpuStage = gpuStages[i]; + gpuStage.type = stage.type; + gpuStage.source = stage.source; - gpuStages.push({ - type: stage.type, - source: stage.source, - macros: stage.macros, - glShader: 0, - }); + if (stage.macros) { + gpuStage.macros = stage.macros; + } } let gpuShader: WebGLGPUShader = { objType: WebGLGPUObjectType.SHADER, - name: info.name, - bindings: info.bindings, + name: info.name ? info.name : "", blocks: info.blocks, + samplers: info.samplers, gpuStages: gpuStages, glProgram: 0, @@ -342,7 +568,7 @@ export class WebGLGFXDevice extends GFXDevice { let gpuPipelineState: WebGLGPUPipelineState = { objType: WebGLGPUObjectType.PIPELINE_STATE, - glPrimitive: WebGLPrimitives[info.primitive], + glPrimitive: info.primitive, gpuShader: gpuShader, rs: info.rs, dss: info.dss, @@ -358,7 +584,7 @@ export class WebGLGFXDevice extends GFXDevice { // TODO: Async } - public emitCmdCreateGPUBindingSetLayout(info: GFXBindingSetLayoutInfo): WebGLGPUBindingSetLayout { + public emitCmdCreateGPUBindingLayout(info: GFXBindingLayoutInfo): WebGLGPUBindingLayout { let gpuBindings: WebGLGPUBinding[] = new Array(info.bindings.length); for (let i = 0; i < info.bindings.length; ++i) { @@ -369,22 +595,48 @@ export class WebGLGFXDevice extends GFXDevice { gpuBinding.name = binding.name; } - let gpuBindingSetLayout: WebGLGPUBindingSetLayout = { - objType: WebGLGPUObjectType.BINDING_SET_LAYOUT, - gpuBinding: gpuBindings, + let gpuBindingLayout: WebGLGPUBindingLayout = { + objType: WebGLGPUObjectType.BINDING_LAYOUT, + gpuBindings: gpuBindings, }; - return gpuBindingSetLayout; + return gpuBindingLayout; } - public emitCmdDestroyGPUBindingSetLayout(gpuBindingSetLayout: WebGLGPUBindingSetLayout) { + public emitCmdDestroyGPUBindingLayout(gpuBindingLayout: WebGLGPUBindingLayout) { // TODO: Async } - public emitCmdUpdateGPUBindingSetLayout(gpuBindingSetLayout: WebGLGPUBindingSetLayout) { + public emitCmdUpdateGPUBindingLayout(gpuBindingLayout: WebGLGPUBindingLayout, bindingUnits: GFXBindingUnit[]) { + // TODO: Async + for (let i = 0; i < bindingUnits.length; ++i) { + let bindingUnit = bindingUnits[i]; + let gpuBinding = gpuBindingLayout.gpuBindings[i]; + gpuBinding.binding = bindingUnit.binding; + gpuBinding.type = bindingUnit.type; + gpuBinding.name = bindingUnit.name; + switch (bindingUnit.type) { + case GFXBindingType.UNIFORM_BUFFER: { + if (bindingUnit.buffer) { + gpuBinding.gpuBuffer = (bindingUnit.buffer).gpuBuffer; + } + break; + } + case GFXBindingType.SAMPLER: { + if (bindingUnit.texView) { + gpuBinding.gpuTexView = (bindingUnit.texView).gpuTextureView; + } + if (bindingUnit.sampler) { + gpuBinding.gpuSampler = (bindingUnit.sampler).gpuSampler; + } + break; + } + default: ; + } + } } public emitCmdCreateGPUInputAssembler(info: GFXInputAssemblerInfo): WebGLGPUInputAssembler { @@ -445,4 +697,5 @@ export class WebGLGFXDevice extends GFXDevice { } private _webGLRC: WebGLRenderingContext | null = null; + private _canvasElm: HTMLCanvasElement | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts index ce5a68e4f9..e4cff04ace 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts @@ -11,9 +11,12 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { public initialize(info : GFXFramebufferInfo) : boolean { - this._colorViews = info.colorViews; - this._depthStencilView = info.depthStencilView; - this._isOffscreen = info.isOffscreen; + if(info.colorViews) { + this._colorViews = info.colorViews; + } + + this._depthStencilView = info.depthStencilView? info.depthStencilView : null; + this._isOffscreen = info.isOffscreen? info.isOffscreen : true; this._gpuFramebuffer = this.webGLDevice.emitCmdCreateGPUFramebuffer(info); diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts b/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts index 70d16886d8..21c8382099 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts @@ -5,16 +5,22 @@ import { WebGLGPUInputAssembler } from './webgl-gpu-objects'; export class WebGLGFXInputAssembler extends GFXInputAssembler { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXInputAssemblerInfo) : boolean { + public initialize(info: GFXInputAssemblerInfo): boolean { this._attributes = info.attributes; this._vertexBuffers = info.vertexBuffers; - this._indexBuffer = info.indexBuffer; - this._isIndirect = info.isIndirect; + + if (info.indexBuffer) { + this._indexBuffer = info.indexBuffer; + } + + if (info.isIndirect) { + this._isIndirect = info.isIndirect; + } this._gpuInputAssembler = this.webGLDevice.emitCmdCreateGPUInputAssembler(info); @@ -22,19 +28,19 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { } public destroy() { - if(this._gpuInputAssembler) { + if (this._gpuInputAssembler) { this.webGLDevice.emitCmdDestroyGPUInputAssembler(this._gpuInputAssembler); this._gpuInputAssembler = null; } } - public get webGLDevice() : WebGLGFXDevice { + public get webGLDevice(): WebGLGFXDevice { return this._device; } - public get gpuInputAssembler() : WebGLGPUInputAssembler | null { + public get gpuInputAssembler(): WebGLGPUInputAssembler | null { return this._gpuInputAssembler; } - private _gpuInputAssembler : WebGLGPUInputAssembler | null = null; + private _gpuInputAssembler: WebGLGPUInputAssembler | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts index 3a58074933..6f94a12493 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts @@ -11,9 +11,12 @@ export class WebGLGFXPipelineLayout extends GFXPipelineLayout { public initialize(info: GFXPipelineLayoutInfo): boolean { - this._pushConstantsRanges = info.pushConstantsRanges; this._layouts = info.layouts; + if(info.pushConstantsRanges) { + this._pushConstantsRanges = info.pushConstantsRanges; + } + return true; } diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts index e64dfcc6ec..72f7118013 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts @@ -5,11 +5,11 @@ import { WebGLGPUPipelineState } from './webgl-gpu-objects'; export class WebGLGFXPipelineState extends GFXPipelineState { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXPipelineStateInfo) : boolean { + public initialize(info: GFXPipelineStateInfo): boolean { this._primitive = info.primitive; this._shader = info.shader; @@ -26,20 +26,19 @@ export class WebGLGFXPipelineState extends GFXPipelineState { } public destroy() { - if(this._gpuPipelineState) - { + if (this._gpuPipelineState) { this.webGLDevice.emitCmdDestroyGPUPipelineState(this._gpuPipelineState); this._gpuPipelineState = null; } } - public get webGLDevice() : WebGLGFXDevice { + public get webGLDevice(): WebGLGFXDevice { return this._device; } - public get gpuPipelineState() : WebGLGPUPipelineState | null { + public get gpuPipelineState(): WebGLGPUPipelineState | null { return this._gpuPipelineState; } - private _gpuPipelineState : WebGLGPUPipelineState | null = null; + private _gpuPipelineState: WebGLGPUPipelineState | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts b/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts index 30900e34a0..542eb4b375 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts @@ -7,11 +7,11 @@ import { WebGLGFXDevice } from './webgl-gfx-device'; export class WebGLGFXQueue extends GFXQueue { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXQueueInfo) : boolean { + public initialize(info: GFXQueueInfo): boolean { this._type = info.type; @@ -22,16 +22,16 @@ export class WebGLGFXQueue extends GFXQueue { } - public submit(cmdBuffs: GFXCommandBuffer[], fence : null = null) { - + public submit(cmdBuffs: GFXCommandBuffer[], fence: null = null) { + // TODO: Async - if(!this._isAsync) { - for(let i = 0; i < cmdBuffs.length; ++i) { + if (!this._isAsync) { + for (let i = 0; i < cmdBuffs.length; ++i) { let cmdBuff = cmdBuffs[i]; WebGLCmdFuncExecuteCmds(this._device, cmdBuff.cmdPackage); } } } - private _isAsync : boolean = false; + private _isAsync: boolean = false; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts b/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts index ed3c095443..7276d3d523 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts @@ -13,9 +13,8 @@ export class WebGLGFXRenderPass extends GFXRenderPass { public initialize(info: GFXRenderPassInfo): boolean { - this._colorInfos = info.colorInfos; - this._depthStencilInfo = info.depthStencilInfo; - this._subPasses = info.subPasses; + this._colorInfos = info.colorAttachment; + this._depthStencilInfo = info.depthStencilAttachment; this._gpuRenderPass = this.webGLDevice.emitCmdCreateGPURenderPass(info); diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts b/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts index cd76700db3..9f98edded1 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts @@ -11,19 +11,7 @@ export class WebGLGFXSampler extends GFXSampler { public initialize(info : GFXSamplerInfo) : boolean { - this._minFilter = info.minFilter; - this._magFilter = info.magFilter; - this._mipFilter = info.mipFilter; - this._addressU = info.addressU; - this._addressV = info.addressV; - this._addressW = info.addressW; - this._maxAnisotropy = info.maxAnisotropy; - this._cmpFunc = info.cmpFunc; - this._borderColor = info.borderColor; - this._minLOD = info.minLOD; - this._maxLOD = info.maxLOD; - this._mipLODBias = info.mipLODBias; - + this._state = info; this._gpuSampler = this.webGLDevice.emitCmdCreateGPUSampler(info); return true; @@ -40,5 +28,9 @@ export class WebGLGFXSampler extends GFXSampler { return this._device; } + public get gpuSampler() : WebGLGPUSampler | null { + return this._gpuSampler; + } + private _gpuSampler : WebGLGPUSampler | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts b/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts index 1cf1045ec7..4d6a752c38 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts @@ -5,16 +5,19 @@ import { WebGLGPUShader } from './webgl-gpu-objects'; export class WebGLGFXShader extends GFXShader { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXShaderInfo) : boolean { + public initialize(info: GFXShaderInfo): boolean { + + if (info.name) { + this._name = info.name; + } - this._name = info.name; this._stages = info.stages; - this._bindings = info.bindings; this._blocks = info.blocks; + this._samplers = info.samplers; this._gpuShader = this.webGLDevice.emitCmdCreateGPUShader(info); @@ -28,13 +31,13 @@ export class WebGLGFXShader extends GFXShader { } } - public get webGLDevice() : WebGLGFXDevice { + public get webGLDevice(): WebGLGFXDevice { return this._device; } - public get gpuShader() : WebGLGPUShader | null { + public get gpuShader(): WebGLGPUShader | null { return this._gpuShader; } - private _gpuShader : WebGLGPUShader | null = null; + private _gpuShader: WebGLGPUShader | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts b/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts index 1dbb679bec..1877a3593f 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts @@ -14,11 +14,23 @@ export class WebGLGFXTextureView extends GFXTextureView { this._texture = info.texture; this._type = info.type; this._format = info.format; - this._baseLevel = info.baseLevel; this._format = info.format; - this._levelCount = info.levelCount; - this._baseLayer = info.baseLayer; - this._layerCount = info.layerCount; + + if(info.baseLevel) { + this._baseLevel = info.baseLevel; + } + + if(info.levelCount) { + this._levelCount = info.levelCount; + } + + if(info.baseLayer) { + this._baseLayer = info.baseLayer; + } + + if(info.layerCount) { + this._layerCount = info.layerCount; + } this.webGLDevice.emitCmdCreateGPUTextureView(info); diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts b/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts index de8d880b46..47d3b53bab 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts @@ -17,10 +17,10 @@ export class WebGLGFXTexture extends GFXTexture { this._format = info.format; this._width = info.width; this._height = info.height; - this._depth = info.depth; - this._arrayLayer = info.arrayLayer; - this._mipLevel = info.mipLevel; - this._flags = info.flags; + this._depth = info.depth? info.depth : 1; + this._arrayLayer = info.arrayLayer? info.arrayLayer : 1; + this._mipLevel = info.mipLevel? info.mipLevel : 1; + this._flags = info.flags? info.flags : GFXTextureFlagBit.NONE; this._size = GFXFormatSurfaceSize(this._format, this.width, this.height, this.depth, this.mipLevel) * this._arrayLayer; if (this._flags & GFXTextureFlagBit.BAKUP_BUFFER) { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-window.ts b/cocos/renderer/gfx/webgl/webgl-gfx-window.ts new file mode 100644 index 0000000000..52a70146a4 --- /dev/null +++ b/cocos/renderer/gfx/webgl/webgl-gfx-window.ts @@ -0,0 +1,149 @@ +import { GFXDevice } from '../gfx-device'; +import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXWindow, GFXWindowInfo } from '../gfx-window'; +import { GFXFramebufferInfo } from '../gfx-framebuffer'; +import { GFXRenderPassInfo, GFXColorAttachment, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint, GFXDepthStencilAttachment } from '../gfx-render-pass'; +import { GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit } from '../gfx-texture'; +import { GFXTextureViewType } from '../gfx-texture-view'; + +export class WebGLGFXWindow extends GFXWindow { + + constructor(device: GFXDevice) { + super(device); + } + + public initialize(info: GFXWindowInfo): boolean { + + if(info.title) { + this._title = info.title; + } + + if(info.left) { + this._left = info.left; + } + + if(info.top) { + this._top = info.top; + } + + this._width = info.width; + this._height = info.height; + + this._renderPass = this._device.createRenderPass({ + colorAttachment: [{ + format: this._colorFmt, + loadOp: GFXLoadOp.CLEAR, + storeOp: GFXStoreOp.STORE, + sampleCount: 1, + beginLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + endLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + }], + depthStencilAttachment: { + format : this._depthStencilFmt, + depthLoadOp : GFXLoadOp.CLEAR, + depthStoreOp : GFXStoreOp.STORE, + stencilLoadOp : GFXLoadOp.CLEAR, + stencilStoreOp : GFXStoreOp.STORE, + sampleCount : 1, + beginLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + endLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + }, + }); + + this._colorTex = this._device.createTexture({ + type : GFXTextureType.TEX2D, + usage : GFXTextureUsageBit.COLOR_ATTACHMENT, + format : this._colorFmt, + width : this._width, + height : this._height, + depth : 1, + arrayLayer : 1, + mipLevel : 1, + flags : GFXTextureFlagBit.NONE, + }); + + if(this._colorTex) { + this._colorTexView = this._device.createTextureView({ + texture : this._colorTex, + type : GFXTextureViewType.TV2D, + format : this._colorFmt, + baseLevel : 0, + levelCount : 1, + baseLayer : 0, + layerCount : 1, + }); + } + + this._depthStencilTex = this._device.createTexture({ + type : GFXTextureType.TEX2D, + usage : GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT, + format : this._depthStencilFmt, + width : this._width, + height : this._height, + depth : 1, + arrayLayer : 1, + mipLevel : 1, + flags : GFXTextureFlagBit.NONE, + }); + + if(this._depthStencilTex) { + this._depthStencilTexView = this._device.createTextureView({ + texture : this._depthStencilTex, + type : GFXTextureViewType.TV2D, + format : this._depthStencilFmt, + baseLevel : 0, + levelCount : 1, + baseLayer : 0, + layerCount : 1, + }); + } + + if(this._colorTexView && this._renderPass && this._depthStencilTexView) { + this._framebuffer = this._device.createFramebuffer({ + renderPass: this._renderPass, + colorViews: [this._colorTexView], + depthStencilView: this._depthStencilTexView, + isOffscreen: false, + }); + } + + return true; + } + + public destroy() { + if(this._depthStencilTexView) { + this._depthStencilTexView.destroy(); + this._depthStencilTexView = null; + } + + if(this._depthStencilTex) { + this._depthStencilTex.destroy(); + this._depthStencilTex = null; + } + + if(this._colorTexView) { + this._colorTexView.destroy(); + this._colorTexView = null; + } + + if(this._colorTex) { + this._colorTex.destroy(); + this._colorTex = null; + } + + if(this._framebuffer) { + this._framebuffer.destroy(); + this._framebuffer = null; + } + + if(this._renderPass) { + this._renderPass.destroy(); + this._renderPass = null; + } + } + + public get webGLDevice(): WebGLGFXDevice { + return this._device; + } + +}; diff --git a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts index 619df2413a..306b8ca86c 100644 --- a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts @@ -3,8 +3,8 @@ import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, G import { GFXTextureViewType } from "../gfx-texture-view"; import { GFXFormat, GFXType } from "../gfx-define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../gfx-render-pass"; -import { GFXShaderType, GFXShaderMacro, GFXUniformBlock } from "../gfx-shader"; -import { GFXBinding, GFXBindingType } from "../gfx-binding-set-layout"; +import { GFXShaderType, GFXShaderMacro, GFXUniformBlock, GFXUniformSampler } from "../gfx-shader"; +import { GFXBinding, GFXBindingType } from "../gfx-binding-layout"; import { GFXFilter, GFXAddress } from "../gfx-sampler"; import { GFXComparisonFunc, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; import { GFXInputAttribute } from "../gfx-input-assembler"; @@ -19,7 +19,7 @@ export const enum WebGLGPUObjectType { SAMPLER, SHADER, PIPELINE_STATE, - BINDING_SET_LAYOUT, + BINDING_LAYOUT, INPUT_ASSEMBLER, COMMAND_BUFFER, }; @@ -55,9 +55,9 @@ export class WebGLGPUTexture extends WebGLGPUObject { usage: GFXTextureUsage = GFXTextureUsageBit.NONE; width: number = 0; height: number = 0; - depth: number = 0; - arrayLayer: number = 0; - mipLevel: number = 0; + depth: number = 1; + arrayLayer: number = 1; + mipLevel: number = 1; flags: GFXTextureFlags = GFXTextureFlagBit.NONE; glTarget: GLenum = 0; @@ -101,7 +101,7 @@ export class WebGLGPUFramebuffer extends WebGLGPUObject { gpuRenderPass: WebGLGPURenderPass; gpuColorViews: (WebGLGPUTextureView | null)[] = []; gpuDepthStencilView: WebGLGPUTextureView | null = null; - isOffscreen: boolean = false; + isOffscreen?: boolean = false; glFramebuffer: WebGLFramebuffer = 0; @@ -113,18 +113,11 @@ export class WebGLGPUFramebuffer extends WebGLGPUObject { }; export class WebGLGPUSampler extends WebGLGPUObject { - minFilter: GFXFilter = GFXFilter.LINEAR; - magFilter: GFXFilter = GFXFilter.LINEAR; - mipFilter: GFXFilter = GFXFilter.LINEAR; - addressU: GFXAddress = GFXAddress.WRAP; - addressV: GFXAddress = GFXAddress.WRAP; - addressW: GFXAddress = GFXAddress.WRAP; - maxAnisotropy: number = 16; - cmpFunc: GFXComparisonFunc = GFXComparisonFunc.NEVER; - borderColor: number[] = [0.0, 0.0, 0.0, 0.0]; - minLOD: number = 0; - maxLOD: number = 1000; - mipLODBias: number = 0.0; + glMinFilter: GLenum = WebGLRenderingContext.NONE; + glMagFilter: GLenum = WebGLRenderingContext.NONE; + glWrapS: GLenum = WebGLRenderingContext.NONE; + glWrapT: GLenum = WebGLRenderingContext.NONE; + glWrapR: GLenum = WebGLRenderingContext.NONE; constructor() { super(WebGLGPUObjectType.SAMPLER); @@ -187,8 +180,8 @@ export class WebGLGPUShaderStage { export class WebGLGPUShader extends WebGLGPUObject { name: string = ""; - bindings: GFXBinding[] = []; - blocks: GFXUniformBlock[] = []; + blocks?: GFXUniformBlock[]; + samplers?: GFXUniformSampler[]; gpuStages: WebGLGPUShaderStage[] = []; glProgram: WebGLProgram = 0; @@ -210,9 +203,9 @@ export class WebGLGPUPipelineState extends WebGLGPUObject { glPrimitive: GLenum = WebGLRenderingContext.TRIANGLES; gpuShader: WebGLGPUShader | null = null; - rs: GFXRasterizerState | null = null; - dss: GFXDepthStencilState | null = null; - bs: GFXBlendState | null = null; + rs: GFXRasterizerState = new GFXRasterizerState; + dss: GFXDepthStencilState = new GFXDepthStencilState; + bs: GFXBlendState = new GFXBlendState; gpuLayout: WebGLGPUPipelineLayout | null = null; gpuRenderPass: WebGLGPURenderPass | null = null; @@ -230,12 +223,12 @@ export class WebGLGPUBinding { gpuSampler: WebGLGPUSampler | null = null; }; -export class WebGLGPUBindingSetLayout extends WebGLGPUObject { +export class WebGLGPUBindingLayout extends WebGLGPUObject { - gpuBinding: WebGLGPUBinding[] = []; + gpuBindings: WebGLGPUBinding[] = []; constructor() { - super(WebGLGPUObjectType.BINDING_SET_LAYOUT); + super(WebGLGPUObjectType.BINDING_LAYOUT); } }; diff --git a/cocos/renderer/gfx/webgl/webgl-state-cache.ts b/cocos/renderer/gfx/webgl/webgl-state-cache.ts index 611800b748..353bec8c35 100644 --- a/cocos/renderer/gfx/webgl/webgl-state-cache.ts +++ b/cocos/renderer/gfx/webgl/webgl-state-cache.ts @@ -1,36 +1,43 @@ import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES } from "../gfx-define"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; +export class WebGLTexUnit +{ + glTexture : WebGLTexture = 0; + minFilter : GLenum = WebGLRenderingContext.NONE; + magFilter : GLenum = WebGLRenderingContext.NONE; + wrapS : GLenum = WebGLRenderingContext.NONE; + wrapT : GLenum = WebGLRenderingContext.NONE; + wrapR : GLenum = WebGLRenderingContext.NONE; + baseLevel : number = 0; + maxLevel : number = 1000; +}; + export class WebGLStateCache { - glArrayBuffer : WebGLBuffer | null = null; - glElementArrayBuffer : WebGLBuffer | null = null; + glArrayBuffer : WebGLBuffer = 0; + glElementArrayBuffer : WebGLBuffer = 0; texUnit : number = 0; - glTex2DUnits : (WebGLTexture | null)[]; - glTexCubeUnits : (WebGLTexture | null)[]; - glFramebuffer : WebGLFramebuffer | null = null; + glTex2DUnits : WebGLTexUnit[]; + glTexCubeUnits : WebGLTexUnit[]; + glFramebuffer : WebGLFramebuffer = 0; viewport : number[] = [0.0, 0.0, 0.0, 0.0]; scissorRect : number[] = [0.0, 0.0, 0.0, 0.0]; rs : GFXRasterizerState; dss : GFXDepthStencilState; bs : GFXBlendState; - glProgram : WebGLProgram | null = null; + glProgram : WebGLProgram = -1; glEnabledAttribLocs : boolean[]; glCurrentAttribLocs : boolean[]; constructor() { - this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); - this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); this.rs = new GFXRasterizerState; this.dss = new GFXDepthStencilState; this.bs = new GFXBlendState; this.glEnabledAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); this.glCurrentAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); - for(let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { - this.glTex2DUnits[i] = null; - this.glTexCubeUnits[i] = null; - } - for(let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { this.glEnabledAttribLocs[i] = false; this.glCurrentAttribLocs[i] = false; From 5d46cf05fc64430e1980ff73ef4df27454520ed4 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 27 Dec 2018 10:48:01 +0800 Subject: [PATCH 005/267] del sample.html --- playground/sample.html | 38 -------------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 playground/sample.html diff --git a/playground/sample.html b/playground/sample.html deleted file mode 100644 index b654d5b526..0000000000 --- a/playground/sample.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - - sample - - - - - - - - - - - - - From 0f542d6299cd1dcaed3151641b3532cb59e681dd Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 27 Dec 2018 13:31:47 +0800 Subject: [PATCH 006/267] remove Buffer class reference --- cocos/renderer/gfx/gfx-buffer.ts | 7 +- cocos/renderer/gfx/gfx-define.ts | 2 + cocos/renderer/gfx/webgl/webgl-commands.ts | 180 +++++++++++++++--- cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts | 15 +- cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 19 +- cocos/renderer/gfx/webgl/webgl-gpu-objects.ts | 8 +- 6 files changed, 185 insertions(+), 46 deletions(-) diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/renderer/gfx/gfx-buffer.ts index 05a3b3e88c..2c52b15217 100644 --- a/cocos/renderer/gfx/gfx-buffer.ts +++ b/cocos/renderer/gfx/gfx-buffer.ts @@ -1,4 +1,5 @@ import { GFXDevice } from './gfx-device'; +import { BufferView } from './gfx-define'; export const enum GFXBufferUsageBit { NONE = 0, @@ -61,7 +62,7 @@ export abstract class GFXBuffer { return this._stride; } - public get buffer(): Buffer | null { + public get buffer(): ArrayBuffer | null { return this._buffer; } @@ -70,6 +71,6 @@ export abstract class GFXBuffer { protected _memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; protected _size: number = 0; protected _stride: number = 1; - protected _arrayBuffer: ArrayBuffer | null = null; - protected _buffer: Buffer | null = null; + protected _buffer: ArrayBuffer | null = null; + protected _bufferView: BufferView | null = null; }; diff --git a/cocos/renderer/gfx/gfx-define.ts b/cocos/renderer/gfx/gfx-define.ts index 4ed2c79f12..9599049256 100644 --- a/cocos/renderer/gfx/gfx-define.ts +++ b/cocos/renderer/gfx/gfx-define.ts @@ -401,3 +401,5 @@ export function GFXGetTypeSize(type : GFXType) : number { } } } + +export type BufferView = Uint8Array; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index bfb83df32e..cecff14aae 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -2,13 +2,12 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFrameb import { WebGLGFXDevice } from "./webgl-gfx-device"; import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../gfx-buffer"; import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize } from "../gfx-define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, BufferView } from "../gfx-define"; import { GFXShaderType } from "../gfx-shader"; import { GFXLoadOp, GFXTextureLayout } from "../gfx-render-pass"; import { GFXColorMask, GFXCullMode } from "../gfx-pipeline-state"; import { WebGLGFXCommandAllocator } from "./webgl-gfx-command-allocator"; import { GFXBindingType } from "../gfx-binding-layout"; -import { Buffer } from "buffer"; import { WebGLTexUnit } from "./webgl-state-cache"; import { GFXBufferTextureCopy } from "../gfx-command-buffer"; import { GFXTextureFlagBit } from "../gfx-texture"; @@ -558,7 +557,7 @@ export function WebGLCmdFuncDestroyBuffer(device: WebGLGFXDevice, gpuBuffer: Web } } -export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: Buffer) { +export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: BufferView) { let gl = device.gl; @@ -869,7 +868,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } glBlock.buffer = new ArrayBuffer(glBlock.size); - glBlock.bufferView = new Buffer(glBlock.buffer); + glBlock.bufferView = new DataView(glBlock.buffer); for (let u = 0; u < glBlock.glUniforms.length; ++u) { let glUniform = glBlock.glUniforms[u]; @@ -1495,56 +1494,191 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG if (glBlock && glBlock.bufferView) { for (let u = 0; u < glBlock.glUniforms.length; ++u) { let glUniform = glBlock.glUniforms[u]; - if (glUniform.glLoc >= 0 && - glBlock.bufferView.compare(gpuBinding.gpuBuffer.buffer, glUniform.offset, glUniform.size, glUniform.offset, glUniform.size) != 0) { + if (glUniform.glLoc >= 0 && glUniform.bufferView) { switch (glUniform.glType) { case WebGLRenderingContext.BOOL: case WebGLRenderingContext.INT: { - gl.uniform1iv(glUniform.glLoc, glUniform.bufferView); - break; + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[m]) { + gl.uniform1iv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 4; + } } case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { - gl.uniform2iv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 2*m; + if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1]) { + gl.uniform2iv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 8; + } break; } case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { - gl.uniform3iv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 3*m; + if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2]) { + gl.uniform3iv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 12; + } break; } case WebGLRenderingContext.BOOL_VEC4: case WebGLRenderingContext.INT_VEC4: { - gl.uniform4iv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 4*m; + if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getInt32(offset+12) !== glUniform.bufferView[idx+3]) { + gl.uniform4iv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 16; + } break; } case WebGLRenderingContext.FLOAT: { - gl.uniform1fv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[m]) { + gl.uniform1fv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 4; + } break; } case WebGLRenderingContext.FLOAT_VEC2: { - gl.uniform2fv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 2*m; + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1]) { + gl.uniform2fv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 8; + } break; } case WebGLRenderingContext.FLOAT_VEC3: { - gl.uniform3fv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 3*m; + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2]) { + gl.uniform3fv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 12; + } break; } case WebGLRenderingContext.FLOAT_VEC4: { - gl.uniform4fv(glUniform.glLoc, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 4*m; + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3]) { + gl.uniform4fv(glUniform.glLoc, glUniform.bufferView); + break; + } + offset += 16; + } break; } case WebGLRenderingContext.FLOAT_MAT2: { - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 4*m; + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3]) { + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + break; + } + offset += 16; + } + break; } case WebGLRenderingContext.FLOAT_MAT3: { - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 9*m; + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3] || + glBlock.bufferView.getFloat32(offset+16) !== glUniform.bufferView[idx+4] || + glBlock.bufferView.getFloat32(offset+20) !== glUniform.bufferView[idx+5] || + glBlock.bufferView.getFloat32(offset+24) !== glUniform.bufferView[idx+6] || + glBlock.bufferView.getFloat32(offset+28) !== glUniform.bufferView[idx+7] || + glBlock.bufferView.getFloat32(offset+32) !== glUniform.bufferView[idx+8]) { + gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.bufferView); + break; + } + offset += 36; + } + break; } case WebGLRenderingContext.FLOAT_MAT4: { - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + + let offset = glUniform.offset; + for (let m = 0; m < glUniform.count; ++m) { + let idx = 9*m; + if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3] || + glBlock.bufferView.getFloat32(offset+16) !== glUniform.bufferView[idx+4] || + glBlock.bufferView.getFloat32(offset+20) !== glUniform.bufferView[idx+5] || + glBlock.bufferView.getFloat32(offset+24) !== glUniform.bufferView[idx+6] || + glBlock.bufferView.getFloat32(offset+28) !== glUniform.bufferView[idx+7] || + glBlock.bufferView.getFloat32(offset+32) !== glUniform.bufferView[idx+8] || + glBlock.bufferView.getFloat32(offset+36) !== glUniform.bufferView[idx+9] || + glBlock.bufferView.getFloat32(offset+40) !== glUniform.bufferView[idx+10] || + glBlock.bufferView.getFloat32(offset+44) !== glUniform.bufferView[idx+11] || + glBlock.bufferView.getFloat32(offset+48) !== glUniform.bufferView[idx+12] || + glBlock.bufferView.getFloat32(offset+52) !== glUniform.bufferView[idx+13] || + glBlock.bufferView.getFloat32(offset+56) !== glUniform.bufferView[idx+14] || + glBlock.bufferView.getFloat32(offset+60) !== glUniform.bufferView[idx+15]) { + gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.bufferView); + break; + } + offset += 64; + } break; } default: ; @@ -1738,7 +1872,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { let cmd = cmdPackage.copyBufferToTextureCmds[copyBufferToTextureCmdIdx++]; - if (cmd.gpuBuffer && cmd.gpuBuffer.buffer && cmd.gpuTexture) { + if (cmd.gpuBuffer && cmd.gpuBuffer.bufferView && cmd.gpuTexture) { switch (cmd.gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { let texUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; @@ -1758,7 +1892,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, region.texOffset[0], region.texOffset[1], w, h, @@ -1779,7 +1913,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, region.texOffset[0], region.texOffset[1], w, h, @@ -1812,7 +1946,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, region.texOffset[0], region.texOffset[1], w, h, @@ -1835,7 +1969,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.buffer.subarray(buffOffset, buffOffset + memSize); + let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, region.texOffset[0], region.texOffset[1], w, h, diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts index 5e68f99cb9..91d752cf48 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts @@ -2,6 +2,7 @@ import { GFXBufferInfo, GFXBuffer, GFXMemoryUsageBit, GFXBufferAccess, GFXBuffer import { GFXDevice } from '../gfx-device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; import { WebGLGFXDevice } from './webgl-gfx-device'; +import { BufferView } from '../gfx-define'; export class WebGLGFXBuffer extends GFXBuffer { @@ -17,12 +18,12 @@ export class WebGLGFXBuffer extends GFXBuffer { this._stride = info.stride? info.stride : 1; if (this._memUsage & GFXMemoryUsageBit.HOST) { - this._arrayBuffer = new ArrayBuffer(this._size); - this._buffer = new Buffer(this._arrayBuffer); + this._buffer = new ArrayBuffer(this._size); + this._bufferView = new Uint8Array(this._buffer); } //this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; - this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); + this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._bufferView); return true; } @@ -33,14 +34,14 @@ export class WebGLGFXBuffer extends GFXBuffer { this._gpuBuffer = null; } - this._arrayBuffer = null; this._buffer = null; + this._bufferView = null; } - public update(buffer: Buffer, offset: number) { + public update(buffer: BufferView, offset: number) { - if (this._buffer) { - this._buffer.set(buffer, offset); + if (this._bufferView) { + this._bufferView.set(buffer, offset); } this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, buffer); diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index 9733cd6d82..c4ff704be8 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -4,7 +4,7 @@ import { WebGLGFXBuffer } from './webgl-gfx-buffer'; import { WebGLGFXQueue } from './webgl-gfx-queue'; import { WebGLStateCache } from './webgl-state-cache'; import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; -import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncDestroyInputAssembler } from './webgl-commands'; +import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember } from './webgl-commands'; import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit, GFXTexture } from '../gfx-texture'; import { GFXTextureViewType, GFXTextureViewInfo, GFXTextureView } from '../gfx-texture-view'; import { GFXRenderPassInfo, GFXRenderPass } from '../gfx-render-pass'; @@ -18,9 +18,9 @@ import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; import { GFXInputAssemblerInfo, GFXInputAssembler } from '../gfx-input-assembler'; import { WebGLGFXShader } from './webgl-gfx-shader'; import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../gfx-command-allocator'; -import { GFXPipelineStateInfo, GFXPipelineState, GFXPrimitiveMode, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from '../gfx-pipeline-state'; +import { GFXPipelineStateInfo, GFXPipelineState } from '../gfx-pipeline-state'; import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; -import { GFXBindingLayoutInfo, GFXBinding, GFXBindingUnit, GFXBindingType } from '../gfx-binding-layout'; +import { GFXBindingLayoutInfo, GFXBindingUnit, GFXBindingType } from '../gfx-binding-layout'; import { WebGLGFXSampler } from './webgl-gfx-sampler'; import { GFXCommandBufferInfo, GFXCommandBuffer } from '../gfx-command-buffer'; import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; @@ -31,6 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-gfx-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; import { GFXWindowInfo, GFXWindow } from '../gfx-window'; import { WebGLGFXWindow } from './webgl-gfx-window'; +import { BufferView } from '../gfx-define'; const WebGLPrimitives: GLenum[] = [ WebGLRenderingContext.POINTS, @@ -115,7 +116,7 @@ export class WebGLGFXDevice extends GFXDevice { this._primaryWindow.destroy(); this._primaryWindow = null; } - + this._canvasElm = null; } @@ -268,7 +269,7 @@ export class WebGLGFXDevice extends GFXDevice { return this._queue; } - public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer: Buffer | null): WebGLGPUBuffer | null { + public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer: BufferView | null): WebGLGPUBuffer | null { let gpuBuffer: WebGLGPUBuffer = { objType: WebGLGPUObjectType.BUFFER, @@ -276,15 +277,15 @@ export class WebGLGFXDevice extends GFXDevice { memUsage: info.memUsage, size: info.size, stride: info.stride ? info.stride : 1, - arrayBuffer: null, buffer: null, + bufferView: null, glTarget: 0, glBuffer: 0, }; if (buffer) { - gpuBuffer.arrayBuffer = buffer.buffer; - gpuBuffer.buffer = buffer; + gpuBuffer.buffer = buffer.buffer; + gpuBuffer.bufferView = buffer; } //let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; @@ -302,7 +303,7 @@ export class WebGLGFXDevice extends GFXDevice { WebGLCmdFuncDestroyBuffer(this, gpuBuffer); } - public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: Buffer) { + public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: BufferView) { // TODO: Async let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; let isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; diff --git a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts index 306b8ca86c..1928335a85 100644 --- a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts @@ -1,7 +1,7 @@ import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from "../gfx-buffer"; import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit } from "../gfx-texture"; import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormat, GFXType } from "../gfx-define"; +import { GFXFormat, GFXType, BufferView } from "../gfx-define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../gfx-render-pass"; import { GFXShaderType, GFXShaderMacro, GFXUniformBlock, GFXUniformSampler } from "../gfx-shader"; import { GFXBinding, GFXBindingType } from "../gfx-binding-layout"; @@ -40,8 +40,8 @@ export class WebGLGPUBuffer extends WebGLGPUObject { glTarget: GLenum = 0; glBuffer: WebGLBuffer = 0; - arrayBuffer: ArrayBuffer | null = null; - buffer: Buffer | null = null; + buffer: ArrayBuffer | null = null; + bufferView: BufferView | null = null; constructor() { super(WebGLGPUObjectType.BUFFER); @@ -158,7 +158,7 @@ export class WebGLGPUUniformBlock { isUniformPackage: boolean = false; // Is a single uniform package? buffer: ArrayBuffer | null = null; // for cache - bufferView: Buffer | null = null; + bufferView: DataView | null = null; } export class WebGLGPUUniformSampler { From d48482ef273e0fc7544e76b1c2597d459efda50e Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 28 Dec 2018 10:49:04 +0800 Subject: [PATCH 007/267] fix gfx crash --- cocos/renderer/gfx/gfx-define.ts | 2 + cocos/renderer/gfx/gfx-device.ts | 9 +- cocos/renderer/gfx/index.js | 32 ++- cocos/renderer/gfx/webgl/webgl-commands.ts | 9 +- cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 186 ++++++++++++++++-- cocos/renderer/gfx/webgl/webgl-gfx-window.ts | 8 + cocos/renderer/gfx/webgl/webgl-state-cache.ts | 31 ++- tsconfig.json | 2 +- 8 files changed, 249 insertions(+), 30 deletions(-) diff --git a/cocos/renderer/gfx/gfx-define.ts b/cocos/renderer/gfx/gfx-define.ts index 9599049256..b19ff66039 100644 --- a/cocos/renderer/gfx/gfx-define.ts +++ b/cocos/renderer/gfx/gfx-define.ts @@ -123,6 +123,7 @@ export const enum GFXFormat { // Depth-Stencil Format D16, + D16S8, D24, D24S8, D32F, @@ -253,6 +254,7 @@ export const GFXFormatInfos : GFXFormatInfo[] = [ { name : "RGB9E5", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, { name : "D16", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, + { name : "D16S8", size : 3, count : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, { name : "D24", size : 3, count : 1, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, { name : "D24S8", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, { name : "D32F", size : 4, count : 1, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index 22f4284486..274f8f0830 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -13,8 +13,13 @@ import { GFXCommandBufferInfo, GFXCommandBuffer } from './gfx-command-buffer'; import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './gfx-command-allocator'; import { GFXWindowInfo, GFXWindow } from './gfx-window'; -export class GFXDeviceInfo { - canvasElm: HTMLElement | null = null; +export const enum GFXFeature { +}; + +export interface GFXDeviceInfo { + canvasElm: HTMLElement; + isAntialias?: boolean; + isPremultipliedAlpha?: boolean; }; export abstract class GFXDevice { diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js index 61fcaa8754..4cd2f5e244 100644 --- a/cocos/renderer/gfx/index.js +++ b/cocos/renderer/gfx/index.js @@ -15,7 +15,21 @@ import TextureCube from './texture-cube'; import RenderBuffer from './render-buffer'; import FrameBuffer from './frame-buffer'; import Device from './device'; -import { WebGLGFXDevice } from '../../../dist/webgl/webgl-gfx-device'; + +import { GFXDevice } from '../../../dist/cocos/renderer/gfx/gfx-device'; +import { GFXBuffer } from '../../../dist/cocos/renderer/gfx/gfx-buffer'; +import { GFXTexture } from '../../../dist/cocos/renderer/gfx/gfx-texture'; +import { GFXTextureView } from '../../../dist/cocos/renderer/gfx/gfx-texture-view'; +import { GFXSampler } from '../../../dist/cocos/renderer/gfx/gfx-sampler'; +import { GFXShader } from '../../../dist/cocos/renderer/gfx/gfx-shader'; +import { GFXInputAssembler } from '../../../dist/cocos/renderer/gfx/gfx-input-assembler'; +import { GFXRenderPass } from '../../../dist/cocos/renderer/gfx/gfx-render-pass'; +import { GFXFramebuffer } from '../../../dist/cocos/renderer/gfx/gfx-framebuffer'; +import { GFXPipelineLayout } from '../../../dist/cocos/renderer/gfx/gfx-pipeline-layout'; +import { GFXPipelineState } from '../../../dist/cocos/renderer/gfx/gfx-pipeline-state'; +import { GFXCommandBuffer } from '../../../dist/cocos/renderer/gfx/gfx-command-buffer'; +import { GFXQueue } from '../../../dist/cocos/renderer/gfx/gfx-queue'; +import { WebGLGFXDevice } from '../../../dist/cocos/renderer/gfx/webgl/webgl-gfx-device'; let gfx = { // classes @@ -29,7 +43,6 @@ let gfx = { RenderBuffer, FrameBuffer, Device, - WebGLGFXDevice, // functions attrTypeBytes, @@ -40,3 +53,18 @@ Object.assign(gfx, enums); export default gfx; cc.gfx = gfx; + +cc.GFXDevice = GFXDevice; +cc.GFXBuffer = GFXBuffer; +cc.GFXTexture = GFXTexture; +cc.GFXTextureView = GFXTextureView; +cc.GFXSampler = GFXSampler; +cc.GFXShader = GFXShader; +cc.GFXInputAssembler = GFXInputAssembler; +cc.GFXRenderPass = GFXRenderPass; +cc.GFXFramebuffer = GFXFramebuffer; +cc.GFXPipelineLayout = GFXPipelineLayout; +cc.GFXPipelineState = GFXPipelineState; +cc.GFXCommandBuffer = GFXCommandBuffer; +cc.GFXQueue = GFXQueue; +cc.WebGLGFXDevice = WebGLGFXDevice; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index cecff14aae..83445367cd 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -12,7 +12,7 @@ import { WebGLTexUnit } from "./webgl-state-cache"; import { GFXBufferTextureCopy } from "../gfx-command-buffer"; import { GFXTextureFlagBit } from "../gfx-texture"; -function GFXFormatToWebGLType(format: GFXFormat): GLenum { +function GFXFormatToWebGLType(format: GFXFormat, device : WebGLGFXDevice): GLenum { switch (format) { case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; @@ -69,8 +69,9 @@ function GFXFormatToWebGLType(format: GFXFormat): GLenum { case GFXFormat.RGB9E5: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.D16: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.D16S8: return WebGLRenderingContext.UNSIGNED_SHORT; case GFXFormat.D24: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.D24S8: return WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.D24S8: return device.WEBGL_depth_texture? device.WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL : WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.D32F: return WebGLRenderingContext.FLOAT; case GFXFormat.D32F_S8: return WebGLRenderingContext.FLOAT; @@ -125,6 +126,7 @@ function GFXFormatToWebGLInternalFormat(format: GFXFormat): GLenum { case GFXFormat.RGB5A1: return WebGLRenderingContext.RGB5_A1; case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA4; case GFXFormat.D16: return WebGLRenderingContext.DEPTH_COMPONENT16; + case GFXFormat.D16S8: return WebGLRenderingContext.DEPTH_STENCIL; case GFXFormat.D24: return WebGLRenderingContext.DEPTH_COMPONENT; case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; @@ -164,6 +166,7 @@ function GFXFormatToWebGLFormat(format: GFXFormat): GLenum { case GFXFormat.RGB5A1: return WebGLRenderingContext.RGBA; case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA; case GFXFormat.D16: return WebGLRenderingContext.DEPTH_COMPONENT; + case GFXFormat.D16S8: return WebGLRenderingContext.DEPTH_STENCIL; case GFXFormat.D24: return WebGLRenderingContext.DEPTH_COMPONENT; case GFXFormat.D24S8: return WebGLRenderingContext.DEPTH_STENCIL; case GFXFormat.D32F: return WebGLRenderingContext.DEPTH_COMPONENT; @@ -590,7 +593,7 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We gpuTexture.glInternelFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format); - gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format); + gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format, device); switch (gpuTexture.viewType) { case GFXTextureViewType.TV2D: { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index c4ff704be8..4e135ad191 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -62,8 +62,7 @@ export class WebGLGFXDevice extends GFXDevice { stateCache: WebGLStateCache = new WebGLStateCache; //webGLCmdAllocator: WebGLGFXCommandAllocator; - constructor(canvasEL: HTMLElement) { - + constructor() { super(); //this.webGLCmdAllocator = new WebGLGFXCommandAllocator(this); @@ -71,21 +70,29 @@ export class WebGLGFXDevice extends GFXDevice { public initialize(info: GFXDeviceInfo): boolean { - this._canvasElm = info.canvasElm; + let canvasElm = info.canvasElm; + + if (info.isAntialias) { + this._isAntialias = info.isAntialias; + } + + if (info.isPremultipliedAlpha) { + this._isPremultipliedAlpha = info.isPremultipliedAlpha; + } try { let webGLCtxAttribs: WebGLContextAttributes = { alpha: true, - antialias: true, + antialias: this._isAntialias, depth: true, stencil: true, - premultipliedAlpha: true, + premultipliedAlpha: this._isPremultipliedAlpha, preserveDrawingBuffer: false, powerPreference: "default", failIfMajorPerformanceCaveat: false, }; - this._webGLRC = this._canvasElm.getContext('webgl', webGLCtxAttribs); + this._webGLRC = canvasElm.getContext('webgl', webGLCtxAttribs); } catch (err) { console.error(err); return false; @@ -95,16 +102,58 @@ export class WebGLGFXDevice extends GFXDevice { // Tested through ios baidu browser 4.14.1 if (!this._webGLRC) { console.error('This device does not support WebGL.'); + return false; } + console.info('WebGL device initialization successed.'); + this._deviceName = "WebGL"; + this._WEBGL_debug_renderer_info = this._webGLRC.getExtension("WEBGL_debug_renderer_info"); + if (this._WEBGL_debug_renderer_info) { + let renderer = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); + console.info("RENDERER: " + renderer); + + let vendor = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); + console.info("VENDOR: " + vendor); + } + + this._extensions = this._webGLRC.getSupportedExtensions(); + /* + if (this._extensions) { + for (let i = 0; i < this._extensions.length; ++i) { + console.info(this._extensions[i]); + } + } + */ + + this._EXT_texture_filter_anisotropic = this._webGLRC.getExtension("EXT_texture_filter_anisotropic"); + this._EXT_frag_depth = this._webGLRC.getExtension("EXT_frag_depth"); + this._EXT_shader_texture_lod = this._webGLRC.getExtension("EXT_shader_texture_lod"); + this._EXT_sRGB = this._webGLRC.getExtension("EXT_sRGB"); + this._OES_vertex_array_object = this._webGLRC.getExtension("OES_vertex_array_object"); + this._WEBGL_color_buffer_float = this._webGLRC.getExtension("WEBGL_color_buffer_float"); + this._WEBGL_compressed_texture_astc = this._webGLRC.getExtension("WEBGL_compressed_texture_astc"); + this._WEBGL_compressed_texture_s3tc = this._webGLRC.getExtension("WEBGL_compressed_texture_s3tc"); + this._WEBGL_compressed_texture_s3tc_srgb = this._webGLRC.getExtension("WEBGL_compressed_texture_s3tc_srgb"); + this._WEBGL_debug_shaders = this._webGLRC.getExtension("WEBGL_debug_shaders"); + this._WEBGL_draw_buffers = this._webGLRC.getExtension("WEBGL_draw_buffers"); + this._WEBGL_lose_context = this._webGLRC.getExtension("WEBGL_lose_context"); + this._WEBGL_depth_texture = this._webGLRC.getExtension("WEBGL_depth_texture"); + this._OES_texture_half_float = this._webGLRC.getExtension("OES_texture_half_float"); + this._OES_texture_half_float_linear = this._webGLRC.getExtension("OES_texture_half_float_linear"); + this._OES_texture_float = this._webGLRC.getExtension("OES_texture_float"); + this._OES_standard_derivatives = this._webGLRC.getExtension("OES_standard_derivatives"); + this._OES_element_index_uint = this._webGLRC.getExtension("OES_element_index_uint"); + this._ANGLE_instanced_arrays = this._webGLRC.getExtension("ANGLE_instanced_arrays"); + + // create primary window this._primaryWindow = this.createWindow({ - title: this._canvasElm.title, - left: this._canvasElm.offsetLeft, - top: this._canvasElm.offsetTop, - width: this._canvasElm.width, - height: this._canvasElm.height, + title: this._webGLRC.canvas.title, + left: this._webGLRC.canvas.offsetLeft, + top: this._webGLRC.canvas.offsetTop, + width: this._webGLRC.drawingBufferWidth, + height: this._webGLRC.drawingBufferHeight, }); return true; @@ -117,7 +166,7 @@ export class WebGLGFXDevice extends GFXDevice { this._primaryWindow = null; } - this._canvasElm = null; + this._webGLRC = null; } public createBuffer(info: GFXBufferInfo): GFXBuffer | null { @@ -697,6 +746,117 @@ export class WebGLGFXDevice extends GFXDevice { // WebGLCmdFuncDestroyInputAssembler(this, gpuInputAssembler); } + public get isAntialias(): boolean { + return this._isAntialias; + } + + public get isPremultipliedAlpha(): boolean { + return this._isPremultipliedAlpha; + } + + public get EXT_texture_filter_anisotropic(): EXT_texture_filter_anisotropic | null { + return this._EXT_texture_filter_anisotropic; + } + + public get EXT_frag_depth(): EXT_frag_depth | null { + return this._EXT_frag_depth; + } + + public get EXT_shader_texture_lod(): EXT_shader_texture_lod | null { + return this._EXT_shader_texture_lod; + } + + public get EXT_sRGB(): EXT_sRGB | null { + return this._EXT_sRGB; + } + + public get OES_vertex_array_object(): OES_vertex_array_object | null { + return this._OES_vertex_array_object; + } + + public get WEBGL_color_buffer_float(): WEBGL_color_buffer_float | null { + return this._WEBGL_color_buffer_float; + } + + public get WEBGL_compressed_texture_astc(): WEBGL_compressed_texture_astc | null { + return this._WEBGL_compressed_texture_astc; + } + + public get WEBGL_compressed_texture_s3tc(): WEBGL_compressed_texture_s3tc | null { + return this._WEBGL_compressed_texture_s3tc; + } + + public get WEBGL_compressed_texture_s3tc_srgb(): WEBGL_compressed_texture_s3tc_srgb | null { + return this._WEBGL_compressed_texture_s3tc_srgb; + } + + public get WEBGL_debug_shaders(): WEBGL_debug_shaders | null { + return this._WEBGL_debug_shaders; + } + + public get WEBGL_draw_buffers(): WEBGL_draw_buffers | null { + return this._WEBGL_draw_buffers; + } + + public get WEBGL_lose_context(): WEBGL_lose_context | null { + return this._WEBGL_lose_context; + } + + public get WEBGL_depth_texture(): WEBGL_depth_texture | null { + return this._WEBGL_depth_texture; + } + + public get WEBGL_debug_renderer_info(): WEBGL_debug_renderer_info | null { + return this._WEBGL_debug_renderer_info; + } + + public get OES_texture_half_float(): OES_texture_half_float | null { + return this._OES_texture_half_float; + } + + public get OES_texture_half_float_linear(): OES_texture_half_float_linear | null { + return this._OES_texture_half_float_linear; + } + + public get OES_texture_float(): OES_texture_float | null { + return this._OES_texture_float; + } + + public get OES_standard_derivatives(): OES_standard_derivatives | null { + return this._OES_standard_derivatives; + } + + public get OES_element_index_uint(): OES_element_index_uint | null { + return this._OES_element_index_uint; + } + + public get ANGLE_instanced_arrays(): ANGLE_instanced_arrays | null { + return this._ANGLE_instanced_arrays; + } + private _webGLRC: WebGLRenderingContext | null = null; - private _canvasElm: HTMLCanvasElement | null = null; + private _isAntialias: boolean = true; + private _isPremultipliedAlpha: boolean = false; + + private _extensions: string[] | null = null; + private _EXT_texture_filter_anisotropic: EXT_texture_filter_anisotropic | null = null; + private _EXT_frag_depth: EXT_frag_depth | null = null; + private _EXT_shader_texture_lod: EXT_shader_texture_lod | null = null; + private _EXT_sRGB: EXT_sRGB | null = null; + private _OES_vertex_array_object: OES_vertex_array_object | null = null; + private _WEBGL_color_buffer_float: WEBGL_color_buffer_float | null = null; + private _WEBGL_compressed_texture_astc: WEBGL_compressed_texture_astc | null = null; + private _WEBGL_compressed_texture_s3tc: WEBGL_compressed_texture_s3tc | null = null; + private _WEBGL_compressed_texture_s3tc_srgb: WEBGL_compressed_texture_s3tc_srgb | null = null; + private _WEBGL_debug_shaders: WEBGL_debug_shaders | null = null; + private _WEBGL_draw_buffers: WEBGL_draw_buffers | null = null; + private _WEBGL_lose_context: WEBGL_lose_context | null = null; + private _WEBGL_depth_texture: WEBGL_depth_texture | null = null; + private _WEBGL_debug_renderer_info: WEBGL_debug_renderer_info | null = null; + private _OES_texture_half_float: OES_texture_half_float | null = null; + private _OES_texture_half_float_linear: OES_texture_half_float_linear | null = null; + private _OES_texture_float: OES_texture_float | null = null; + private _OES_standard_derivatives: OES_standard_derivatives | null = null; + private _OES_element_index_uint: OES_element_index_uint | null = null; + private _ANGLE_instanced_arrays: ANGLE_instanced_arrays | null = null; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-window.ts b/cocos/renderer/gfx/webgl/webgl-gfx-window.ts index 52a70146a4..a1d837a028 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-window.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-window.ts @@ -5,6 +5,7 @@ import { GFXFramebufferInfo } from '../gfx-framebuffer'; import { GFXRenderPassInfo, GFXColorAttachment, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint, GFXDepthStencilAttachment } from '../gfx-render-pass'; import { GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit } from '../gfx-texture'; import { GFXTextureViewType } from '../gfx-texture-view'; +import { GFXFormat } from '../gfx-define'; export class WebGLGFXWindow extends GFXWindow { @@ -28,6 +29,13 @@ export class WebGLGFXWindow extends GFXWindow { this._width = info.width; this._height = info.height; + this._colorFmt = GFXFormat.RGBA8; + + if(this.webGLDevice.WEBGL_depth_texture) { + this._depthStencilFmt = GFXFormat.D24S8; + } else { + this._depthStencilFmt = GFXFormat.D16S8; + } this._renderPass = this._device.createRenderPass({ colorAttachment: [{ diff --git a/cocos/renderer/gfx/webgl/webgl-state-cache.ts b/cocos/renderer/gfx/webgl/webgl-state-cache.ts index 353bec8c35..23f65a6f32 100644 --- a/cocos/renderer/gfx/webgl/webgl-state-cache.ts +++ b/cocos/renderer/gfx/webgl/webgl-state-cache.ts @@ -1,16 +1,16 @@ import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES } from "../gfx-define"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; -export class WebGLTexUnit +export interface WebGLTexUnit { - glTexture : WebGLTexture = 0; - minFilter : GLenum = WebGLRenderingContext.NONE; - magFilter : GLenum = WebGLRenderingContext.NONE; - wrapS : GLenum = WebGLRenderingContext.NONE; - wrapT : GLenum = WebGLRenderingContext.NONE; - wrapR : GLenum = WebGLRenderingContext.NONE; - baseLevel : number = 0; - maxLevel : number = 1000; + glTexture : WebGLTexture; + minFilter : GLenum; + magFilter : GLenum; + wrapS : GLenum; + wrapT : GLenum; + wrapR : GLenum; + baseLevel : number; + maxLevel : number; }; export class WebGLStateCache { @@ -38,6 +38,19 @@ export class WebGLStateCache { this.glEnabledAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); this.glCurrentAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); + for(let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { + this.glTex2DUnits[i] = { + glTexture : 0, + minFilter : WebGLRenderingContext.NONE, + magFilter : WebGLRenderingContext.NONE, + wrapS : WebGLRenderingContext.NONE, + wrapT : WebGLRenderingContext.NONE, + wrapR : WebGLRenderingContext.NONE, + baseLevel : 0, + maxLevel : 1000, + } + } + for(let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { this.glEnabledAttribLocs[i] = false; this.glCurrentAttribLocs[i] = false; diff --git a/tsconfig.json b/tsconfig.json index 6e5dea8439..fa152bcee8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,7 +12,7 @@ "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ "outDir": "./dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ From ea071ffe48f1ffbe35923b6759261aed2c976352 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 28 Dec 2018 16:36:57 +0800 Subject: [PATCH 008/267] minor --- cocos/renderer/gfx/gfx-pipeline-state.ts | 6 ++--- cocos/renderer/gfx/webgl/webgl-commands.ts | 31 ++++++++++++---------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/renderer/gfx/gfx-pipeline-state.ts index 5921edc045..f69bab8611 100644 --- a/cocos/renderer/gfx/gfx-pipeline-state.ts +++ b/cocos/renderer/gfx/gfx-pipeline-state.ts @@ -107,7 +107,7 @@ export class GFXRasterizerState { depthBiasFactor: number = 0.0; isDepthClip: boolean = true; isMultisample: boolean = false; - lineWidth: number = 1.0; + // lineWidth: number = 1.0; public compare(state: GFXRasterizerState): boolean { return (this.isDiscard === state.isDiscard) && @@ -118,8 +118,8 @@ export class GFXRasterizerState { (this.depthBias === state.depthBias) && (this.depthBiasFactor === state.depthBiasFactor) && (this.isDepthClip === state.isDepthClip) && - (this.isMultisample === state.isMultisample) && - (this.lineWidth === state.lineWidth); + // (this.lineWidth === state.lineWidth) && + (this.isMultisample === state.isMultisample); } }; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index 83445367cd..6fdeba7663 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -1243,7 +1243,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gpuShader = cmd.gpuPipelineState.gpuShader; } - // rasterizater state + // rasterizer state let rs = cmd.gpuPipelineState.rs; if (rs) { @@ -1281,10 +1281,13 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG device.stateCache.rs.depthBiasFactor = rs.depthBiasFactor; } + /* no browser actually supports this if (device.stateCache.rs.lineWidth !== rs.lineWidth) { gl.lineWidth(rs.lineWidth); device.stateCache.rs.lineWidth = rs.lineWidth; } + */ + } // rasterizater state // depth-stencil state @@ -1534,7 +1537,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m) { let idx = 3*m; if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2]) { gl.uniform3iv(glUniform.glLoc, glUniform.bufferView); break; @@ -1550,8 +1553,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m) { let idx = 4*m; if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2] || glBlock.bufferView.getInt32(offset+12) !== glUniform.bufferView[idx+3]) { gl.uniform4iv(glUniform.glLoc, glUniform.bufferView); break; @@ -1592,7 +1595,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m) { let idx = 3*m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2]) { gl.uniform3fv(glUniform.glLoc, glUniform.bufferView); break; @@ -1607,8 +1610,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m) { let idx = 4*m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3]) { gl.uniform4fv(glUniform.glLoc, glUniform.bufferView); break; @@ -1623,8 +1626,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m) { let idx = 4*m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3]) { gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); break; @@ -1640,8 +1643,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m) { let idx = 9*m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3] || glBlock.bufferView.getFloat32(offset+16) !== glUniform.bufferView[idx+4] || glBlock.bufferView.getFloat32(offset+20) !== glUniform.bufferView[idx+5] || @@ -1660,10 +1663,10 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 9*m; + let idx = 16*m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || + glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || + glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3] || glBlock.bufferView.getFloat32(offset+16) !== glUniform.bufferView[idx+4] || glBlock.bufferView.getFloat32(offset+20) !== glUniform.bufferView[idx+5] || From a018da88919003ad2e6ec1b9773993687f9240e0 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 28 Dec 2018 18:35:07 +0800 Subject: [PATCH 009/267] make compilation sucess --- cocos/renderer/gfx/gfx-binding-layout.ts | 2 +- cocos/renderer/gfx/gfx-buffer.ts | 6 ++-- cocos/renderer/gfx/gfx-command-buffer.ts | 2 +- cocos/renderer/gfx/gfx-define.ts | 4 +-- cocos/renderer/gfx/gfx-device.ts | 2 +- cocos/renderer/gfx/gfx-pipeline-state.ts | 19 ++++++------- cocos/renderer/gfx/gfx-queue.ts | 2 +- cocos/renderer/gfx/gfx-render-pass.ts | 10 +++---- cocos/renderer/gfx/gfx-sampler.ts | 4 +-- cocos/renderer/gfx/gfx-shader.ts | 2 +- cocos/renderer/gfx/gfx-texture-view.ts | 2 +- cocos/renderer/gfx/gfx-texture.ts | 6 ++-- cocos/renderer/gfx/index.js | 28 +++++++++---------- cocos/renderer/gfx/webgl/webgl-commands.ts | 2 +- cocos/renderer/gfx/webgl/webgl-gpu-objects.ts | 7 ++--- 15 files changed, 48 insertions(+), 50 deletions(-) diff --git a/cocos/renderer/gfx/gfx-binding-layout.ts b/cocos/renderer/gfx/gfx-binding-layout.ts index 41e829c80d..f6278e0a45 100644 --- a/cocos/renderer/gfx/gfx-binding-layout.ts +++ b/cocos/renderer/gfx/gfx-binding-layout.ts @@ -3,7 +3,7 @@ import { GFXBuffer } from './gfx-buffer'; import { GFXTextureView } from './gfx-texture-view'; import { GFXSampler } from './gfx-sampler'; -export const enum GFXBindingType { +export enum GFXBindingType { UNKNOWN, UNIFORM_BUFFER, SAMPLER, diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/renderer/gfx/gfx-buffer.ts index 2c52b15217..9fc9f8c68e 100644 --- a/cocos/renderer/gfx/gfx-buffer.ts +++ b/cocos/renderer/gfx/gfx-buffer.ts @@ -1,7 +1,7 @@ import { GFXDevice } from './gfx-device'; import { BufferView } from './gfx-define'; -export const enum GFXBufferUsageBit { +export enum GFXBufferUsageBit { NONE = 0, TRANSFER_SRC = 0x1, TRANSFER_DST = 0x2, @@ -13,7 +13,7 @@ export const enum GFXBufferUsageBit { export type GFXBufferUsage = GFXBufferUsageBit; -export const enum GFXMemoryUsageBit { +export enum GFXMemoryUsageBit { NONE = 0, DEVICE = 0x1, HOST = 0x2, @@ -21,7 +21,7 @@ export const enum GFXMemoryUsageBit { export type GFXMemoryUsage = GFXMemoryUsageBit; -export const enum GFXBufferAccessBit { +export enum GFXBufferAccessBit { NONE = 0, READ = 0x1, WRITE = 0x2, diff --git a/cocos/renderer/gfx/gfx-command-buffer.ts b/cocos/renderer/gfx/gfx-command-buffer.ts index 462515969d..09804ea0c1 100644 --- a/cocos/renderer/gfx/gfx-command-buffer.ts +++ b/cocos/renderer/gfx/gfx-command-buffer.ts @@ -33,7 +33,7 @@ export class GFXBufferTextureCopy { texSubres: GFXTextureSubres = new GFXTextureSubres; }; -export const enum GFXCommandBufferType { +export enum GFXCommandBufferType { PRIMARY, SECONDARY, }; diff --git a/cocos/renderer/gfx/gfx-define.ts b/cocos/renderer/gfx/gfx-define.ts index b19ff66039..e41a1fb44f 100644 --- a/cocos/renderer/gfx/gfx-define.ts +++ b/cocos/renderer/gfx/gfx-define.ts @@ -1,5 +1,5 @@ // Extensions -export const enum WebGLEXT { +export enum WebGLEXT { COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1, COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2, @@ -58,7 +58,7 @@ export enum GFXType { COUNT, }; -export const enum GFXFormat { +export enum GFXFormat { UNKNOWN, diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index 274f8f0830..b91eee2266 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -13,7 +13,7 @@ import { GFXCommandBufferInfo, GFXCommandBuffer } from './gfx-command-buffer'; import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './gfx-command-allocator'; import { GFXWindowInfo, GFXWindow } from './gfx-window'; -export const enum GFXFeature { +export enum GFXFeature { }; export interface GFXDeviceInfo { diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/renderer/gfx/gfx-pipeline-state.ts index f69bab8611..aafec1e3e7 100644 --- a/cocos/renderer/gfx/gfx-pipeline-state.ts +++ b/cocos/renderer/gfx/gfx-pipeline-state.ts @@ -1,11 +1,10 @@ import { GFXDevice } from './gfx-device'; -import { GFX_MAX_VERTEX_ATTRIBUTES, GFXFormat } from './gfx-define'; import { GFXShader } from './gfx-shader'; import { GFXRenderPass } from './gfx-render-pass'; import { GFXPipelineLayout } from './gfx-pipeline-layout'; import { GFXInputAttribute } from './gfx-input-assembler'; -export const enum GFXPrimitiveMode { +export enum GFXPrimitiveMode { POINT_LIST, LINE_LIST, LINE_STRIP, @@ -22,24 +21,24 @@ export const enum GFXPrimitiveMode { ISO_LINE_LIST, }; -export const enum GFXPolygonMode { +export enum GFXPolygonMode { FILL, LINE, POINT, }; -export const enum GFXShadeModel { +export enum GFXShadeModel { GOURAND, FLAT, }; -export const enum GFXCullMode { +export enum GFXCullMode { NONE, FRONT, BACK, }; -export const enum GFXComparisonFunc { +export enum GFXComparisonFunc { NEVER, LESS, EQUAL, @@ -50,7 +49,7 @@ export const enum GFXComparisonFunc { ALWAYS, }; -export const enum GFXStencilOp { +export enum GFXStencilOp { KEEP, ZERO, REPLACE, @@ -61,7 +60,7 @@ export const enum GFXStencilOp { DECR_WRAP, }; -export const enum GFXBlendOp { +export enum GFXBlendOp { ADD, SUB, REV_SUB, @@ -69,7 +68,7 @@ export const enum GFXBlendOp { MAX, }; -export const enum GFXBlendFactor { +export enum GFXBlendFactor { ZERO, ONE, SRC_ALPHA, @@ -87,7 +86,7 @@ export const enum GFXBlendFactor { ONE_MINUS_CONSTANT_ALPHA, }; -export const enum GFXColorMask { +export enum GFXColorMask { NONE = 0x0, R = 0x1, G = 0x2, diff --git a/cocos/renderer/gfx/gfx-queue.ts b/cocos/renderer/gfx/gfx-queue.ts index c380de58bc..5546eecef3 100644 --- a/cocos/renderer/gfx/gfx-queue.ts +++ b/cocos/renderer/gfx/gfx-queue.ts @@ -1,6 +1,6 @@ import { GFXDevice } from './gfx-device'; -export const enum GFXQueueType { +export enum GFXQueueType { GRAPHICS, COMPUTE, TRANSFER, diff --git a/cocos/renderer/gfx/gfx-render-pass.ts b/cocos/renderer/gfx/gfx-render-pass.ts index 4127456b34..ebf94e5594 100644 --- a/cocos/renderer/gfx/gfx-render-pass.ts +++ b/cocos/renderer/gfx/gfx-render-pass.ts @@ -2,7 +2,7 @@ import { GFXFormat, GFXFormatInfo } from './gfx-define'; import { GFXDevice } from './gfx-device'; // Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. -export const enum GFXLoadOp +export enum GFXLoadOp { LOAD, // Load the contents from the fbo from previous CLEAR, // Clear the fbo @@ -10,13 +10,13 @@ export const enum GFXLoadOp }; // Enumerates all possible values of operations to be performed when Storing to a Framebuffer Object. -export const enum GFXStoreOp +export enum GFXStoreOp { STORE, // Write the source to the destination DISCARD, // Don't write the source to the destination }; -export const enum GFXTextureLayout +export enum GFXTextureLayout { UNDEFINED, GENERAL, @@ -40,7 +40,7 @@ export class GFXColorAttachment endLayout : GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; }; -export class GFXDepthStencilAttachment +export class GFXDepthStencilAttachment { format : GFXFormat = GFXFormat.UNKNOWN; depthLoadOp : GFXLoadOp = GFXLoadOp.CLEAR; @@ -52,7 +52,7 @@ export class GFXDepthStencilAttachment endLayout : GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; }; -export const enum GFXPipelineBindPoint +export enum GFXPipelineBindPoint { GRAPHICS, COMPUTE, diff --git a/cocos/renderer/gfx/gfx-sampler.ts b/cocos/renderer/gfx/gfx-sampler.ts index 36fb915b45..33f4557c9e 100644 --- a/cocos/renderer/gfx/gfx-sampler.ts +++ b/cocos/renderer/gfx/gfx-sampler.ts @@ -1,14 +1,14 @@ import { GFXDevice } from './gfx-device'; import { GFXComparisonFunc } from './gfx-pipeline-state'; -export const enum GFXFilter { +export enum GFXFilter { NONE, POINT, LINEAR, ANISOTROPIC, }; -export const enum GFXAddress { +export enum GFXAddress { WRAP, MIRROR, CLAMP, diff --git a/cocos/renderer/gfx/gfx-shader.ts b/cocos/renderer/gfx/gfx-shader.ts index 0ef1078db1..feff85709a 100644 --- a/cocos/renderer/gfx/gfx-shader.ts +++ b/cocos/renderer/gfx/gfx-shader.ts @@ -2,7 +2,7 @@ import { GFXDevice } from './gfx-device'; import { GFXBinding } from './gfx-binding-layout'; import { GFXType } from './gfx-define'; -export const enum GFXShaderType { +export enum GFXShaderType { VERTEX, HULL, DOMAIN, diff --git a/cocos/renderer/gfx/gfx-texture-view.ts b/cocos/renderer/gfx/gfx-texture-view.ts index 9078b00520..4d56e1c12b 100644 --- a/cocos/renderer/gfx/gfx-texture-view.ts +++ b/cocos/renderer/gfx/gfx-texture-view.ts @@ -2,7 +2,7 @@ import { GFXFormat, GFXFormatInfo } from './gfx-define'; import { GFXDevice } from './gfx-device'; import { GFXTexture } from './gfx-texture'; -export const enum GFXTextureViewType { +export enum GFXTextureViewType { TV1D, TV2D, TV3D, diff --git a/cocos/renderer/gfx/gfx-texture.ts b/cocos/renderer/gfx/gfx-texture.ts index ee998e0c32..ba650cc2cc 100644 --- a/cocos/renderer/gfx/gfx-texture.ts +++ b/cocos/renderer/gfx/gfx-texture.ts @@ -1,13 +1,13 @@ import { GFXFormat, GFXFormatInfo } from './gfx-define'; import { GFXDevice } from './gfx-device'; -export const enum GFXTextureType { +export enum GFXTextureType { TEX1D, TEX2D, TEX3D, }; -export const enum GFXTextureUsageBit { +export enum GFXTextureUsageBit { NONE = 0, TRANSFER_SRC = 0x1, TRANSFER_DST = 0x2, @@ -21,7 +21,7 @@ export const enum GFXTextureUsageBit { export type GFXTextureUsage = GFXTextureUsageBit; -export const enum GFXTextureFlagBit { +export enum GFXTextureFlagBit { NONE = 0, GEN_MIPMAP = 0x1, CUBEMAP = 0x2, diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js index 4cd2f5e244..56f53282fc 100644 --- a/cocos/renderer/gfx/index.js +++ b/cocos/renderer/gfx/index.js @@ -16,20 +16,20 @@ import RenderBuffer from './render-buffer'; import FrameBuffer from './frame-buffer'; import Device from './device'; -import { GFXDevice } from '../../../dist/cocos/renderer/gfx/gfx-device'; -import { GFXBuffer } from '../../../dist/cocos/renderer/gfx/gfx-buffer'; -import { GFXTexture } from '../../../dist/cocos/renderer/gfx/gfx-texture'; -import { GFXTextureView } from '../../../dist/cocos/renderer/gfx/gfx-texture-view'; -import { GFXSampler } from '../../../dist/cocos/renderer/gfx/gfx-sampler'; -import { GFXShader } from '../../../dist/cocos/renderer/gfx/gfx-shader'; -import { GFXInputAssembler } from '../../../dist/cocos/renderer/gfx/gfx-input-assembler'; -import { GFXRenderPass } from '../../../dist/cocos/renderer/gfx/gfx-render-pass'; -import { GFXFramebuffer } from '../../../dist/cocos/renderer/gfx/gfx-framebuffer'; -import { GFXPipelineLayout } from '../../../dist/cocos/renderer/gfx/gfx-pipeline-layout'; -import { GFXPipelineState } from '../../../dist/cocos/renderer/gfx/gfx-pipeline-state'; -import { GFXCommandBuffer } from '../../../dist/cocos/renderer/gfx/gfx-command-buffer'; -import { GFXQueue } from '../../../dist/cocos/renderer/gfx/gfx-queue'; -import { WebGLGFXDevice } from '../../../dist/cocos/renderer/gfx/webgl/webgl-gfx-device'; +import { GFXDevice } from './gfx-device'; +import { GFXBuffer } from './gfx-buffer'; +import { GFXTexture } from './gfx-texture'; +import { GFXTextureView } from './gfx-texture-view'; +import { GFXSampler } from './gfx-sampler'; +import { GFXShader } from './gfx-shader'; +import { GFXInputAssembler } from './gfx-input-assembler'; +import { GFXRenderPass } from './gfx-render-pass'; +import { GFXFramebuffer } from './gfx-framebuffer'; +import { GFXPipelineLayout } from './gfx-pipeline-layout'; +import { GFXPipelineState } from './gfx-pipeline-state'; +import { GFXCommandBuffer } from './gfx-command-buffer'; +import { GFXQueue } from './gfx-queue'; +import { WebGLGFXDevice } from './webgl/webgl-gfx-device'; let gfx = { // classes diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index 6fdeba7663..988869172c 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -334,7 +334,7 @@ const WebGLBlendFactors: GLenum[] = [ WebGLRenderingContext.ONE_MINUS_CONSTANT_ALPHA, ]; -export const enum WebGLCmd { +export enum WebGLCmd { BEGIN_RENDER_PASS, END_RENDER_PASS, BIND_PIPELINE_STATE, diff --git a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts index 1928335a85..62d8e9e1b3 100644 --- a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts @@ -4,12 +4,11 @@ import { GFXTextureViewType } from "../gfx-texture-view"; import { GFXFormat, GFXType, BufferView } from "../gfx-define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../gfx-render-pass"; import { GFXShaderType, GFXShaderMacro, GFXUniformBlock, GFXUniformSampler } from "../gfx-shader"; -import { GFXBinding, GFXBindingType } from "../gfx-binding-layout"; -import { GFXFilter, GFXAddress } from "../gfx-sampler"; -import { GFXComparisonFunc, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; +import { GFXBindingType } from "../gfx-binding-layout"; +import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; import { GFXInputAttribute } from "../gfx-input-assembler"; -export const enum WebGLGPUObjectType { +export enum WebGLGPUObjectType { UNKNOWN, BUFFER, TEXTURE, From 0dc824f748483d44ca2400541382faec2d861ff4 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Sat, 29 Dec 2018 13:00:12 +0800 Subject: [PATCH 010/267] add createBindingLayout() to GFXDevice --- cocos/renderer/gfx/gfx-device.ts | 5 +++-- cocos/renderer/gfx/webgl/webgl-commands.ts | 10 +-------- cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 22 ++++++++++++++------ 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index b91eee2266..fef0883783 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -12,6 +12,7 @@ import { GFXInputAssemblerInfo, GFXInputAssembler } from './gfx-input-assembler' import { GFXCommandBufferInfo, GFXCommandBuffer } from './gfx-command-buffer'; import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './gfx-command-allocator'; import { GFXWindowInfo, GFXWindow } from './gfx-window'; +import { GFXBindingLayoutInfo, GFXBindingLayout } from './gfx-binding-layout'; export enum GFXFeature { }; @@ -30,6 +31,7 @@ export abstract class GFXDevice { public abstract createTexture(info: GFXTextureInfo) : GFXTexture | null; public abstract createTextureView(info: GFXTextureViewInfo) : GFXTextureView | null; public abstract createSampler(info: GFXSamplerInfo) : GFXSampler | null; + public abstract createBindingLayout(info: GFXBindingLayoutInfo) : GFXBindingLayout | null; public abstract createShader(info: GFXShaderInfo) : GFXShader | null; public abstract createInputAssembler(info: GFXInputAssemblerInfo) : GFXInputAssembler | null; public abstract createRenderPass(info: GFXRenderPassInfo) : GFXRenderPass | null; @@ -51,8 +53,7 @@ export abstract class GFXDevice { protected _deviceName : string = ""; protected _queue : GFXQueue | null = null; - protected _primaryWindow : GFXWindow | null = null; - protected _windows : GFXWindow[] = []; + protected _curWindow : GFXWindow | null = null; protected _maxVertexAttributes : number = 0; }; diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/renderer/gfx/webgl/webgl-commands.ts index 988869172c..e3fd4097f9 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/renderer/gfx/webgl/webgl-commands.ts @@ -1505,7 +1505,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG switch (glUniform.glType) { case WebGLRenderingContext.BOOL: case WebGLRenderingContext.INT: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[m]) { @@ -1514,6 +1513,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } offset += 4; } + break; } case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { @@ -1532,7 +1532,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { let idx = 3*m; @@ -1590,7 +1589,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLRenderingContext.FLOAT_VEC3: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { let idx = 3*m; @@ -1605,7 +1603,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLRenderingContext.FLOAT_VEC4: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { let idx = 4*m; @@ -1621,7 +1618,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLRenderingContext.FLOAT_MAT2: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { let idx = 4*m; @@ -1634,11 +1630,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } offset += 16; } - break; } case WebGLRenderingContext.FLOAT_MAT3: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { let idx = 9*m; @@ -1656,11 +1650,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } offset += 36; } - break; } case WebGLRenderingContext.FLOAT_MAT4: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { let idx = 16*m; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index 4e135ad191..7d8965e3a9 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -20,7 +20,7 @@ import { WebGLGFXShader } from './webgl-gfx-shader'; import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../gfx-command-allocator'; import { GFXPipelineStateInfo, GFXPipelineState } from '../gfx-pipeline-state'; import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; -import { GFXBindingLayoutInfo, GFXBindingUnit, GFXBindingType } from '../gfx-binding-layout'; +import { GFXBindingLayoutInfo, GFXBindingUnit, GFXBindingType, GFXBindingLayout } from '../gfx-binding-layout'; import { WebGLGFXSampler } from './webgl-gfx-sampler'; import { GFXCommandBufferInfo, GFXCommandBuffer } from '../gfx-command-buffer'; import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; @@ -32,6 +32,7 @@ import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; import { GFXWindowInfo, GFXWindow } from '../gfx-window'; import { WebGLGFXWindow } from './webgl-gfx-window'; import { BufferView } from '../gfx-define'; +import { WebGLGFXBindingLayout } from './webgl-gfx-binding-layout'; const WebGLPrimitives: GLenum[] = [ WebGLRenderingContext.POINTS, @@ -148,7 +149,7 @@ export class WebGLGFXDevice extends GFXDevice { this._ANGLE_instanced_arrays = this._webGLRC.getExtension("ANGLE_instanced_arrays"); // create primary window - this._primaryWindow = this.createWindow({ + this._curWindow = this.createWindow({ title: this._webGLRC.canvas.title, left: this._webGLRC.canvas.offsetLeft, top: this._webGLRC.canvas.offsetTop, @@ -161,9 +162,9 @@ export class WebGLGFXDevice extends GFXDevice { public destroy(): void { - if (this._primaryWindow) { - this._primaryWindow.destroy(); - this._primaryWindow = null; + if (this._curWindow) { + this._curWindow.destroy(); + this._curWindow = null; } this._webGLRC = null; @@ -209,6 +210,16 @@ export class WebGLGFXDevice extends GFXDevice { } } + public createBindingLayout(info: GFXBindingLayoutInfo): GFXBindingLayout | null { + let bindingLayout = new WebGLGFXBindingLayout(this); + if (bindingLayout.initialize(info)) { + return bindingLayout; + } else { + bindingLayout.destroy(); + return null; + } + } + public createShader(info: GFXShaderInfo): GFXShader | null { let shader = new WebGLGFXShader(this); if (shader.initialize(info)) { @@ -302,7 +313,6 @@ export class WebGLGFXDevice extends GFXDevice { public createWindow(info: GFXWindowInfo): GFXWindow | null { let window = new WebGLGFXWindow(this); if (window.initialize(info)) { - this._windows.push(window); return window; } else { window.destroy(); From 7740474a804c71a52a9992e29530fc4dde7f64e6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Sat, 29 Dec 2018 14:38:11 +0800 Subject: [PATCH 011/267] add pipeline module --- cocos/core/CCGame.js | 12 ++ cocos/core/root.ts | 145 ++++++++++++++++++ cocos/renderer/gfx/gfx-device.ts | 1 + cocos/renderer/gfx/gfx-pipeline-state.ts | 3 - cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 3 + .../renderer/pipeline/forward/forward-flow.ts | 19 +++ .../pipeline/forward/forward-pipeline.ts | 13 ++ .../pipeline/forward/forward-stage.ts | 16 ++ cocos/renderer/pipeline/render-flow.ts | 52 +++++++ cocos/renderer/pipeline/render-pipeline.ts | 45 ++++++ cocos/renderer/pipeline/render-stage.ts | 28 ++++ cocos/renderer/pipeline/render-view.ts | 77 ++++++++++ 12 files changed, 411 insertions(+), 3 deletions(-) create mode 100644 cocos/core/root.ts create mode 100644 cocos/renderer/pipeline/forward/forward-flow.ts create mode 100644 cocos/renderer/pipeline/forward/forward-pipeline.ts create mode 100644 cocos/renderer/pipeline/forward/forward-stage.ts create mode 100644 cocos/renderer/pipeline/render-flow.ts create mode 100644 cocos/renderer/pipeline/render-pipeline.ts create mode 100644 cocos/renderer/pipeline/render-stage.ts create mode 100644 cocos/renderer/pipeline/render-view.ts diff --git a/cocos/core/CCGame.js b/cocos/core/CCGame.js index 201a0dbe0e..c8a7bc56a7 100644 --- a/cocos/core/CCGame.js +++ b/cocos/core/CCGame.js @@ -127,6 +127,8 @@ var game = { _renderContext: null, + _gfxDevice: null, + _intervalId: null,//interval target of main _lastTime: null, @@ -765,11 +767,21 @@ var game = { { // todo, adjust opts here + let device = this._renderContext = new gfx.Device(localCanvas, {}); + + /* + this._gfxDevice = new WebGLGFXDevice; + this._gfxDevice.initialize({ + canvasElm : localCanvas, + }); + */ + renderer.addStage('opaque'); renderer.addStage('transparent'); renderer.addStage('ui'); renderer.addStage('shadowcast'); + this._renderer = new renderer.ForwardRenderer(device); } // renderer.initWebGL(localCanvas, opts); diff --git a/cocos/core/root.ts b/cocos/core/root.ts new file mode 100644 index 0000000000..8118d6dee7 --- /dev/null +++ b/cocos/core/root.ts @@ -0,0 +1,145 @@ +import { Scene } from "../renderer/scene/scene"; +import { RenderView, RenderViewInfo } from "../renderer/pipeline/render-view"; +import { GFXDevice } from "../renderer/gfx/gfx-device"; +import { GFXWindow, GFXWindowInfo } from "../renderer/gfx/gfx-window"; +import { RenderPipeline } from "../renderer/pipeline/render-pipeline"; +import { ForwardPipeline } from "../renderer/pipeline/forward/forward-pipeline"; + +export interface RootInfo { +}; + +export class Root { + + constructor() { + } + + public initialize(info: RootInfo): boolean { + + let pipeline = new ForwardPipeline; + if (!pipeline.initialize()) { + return false; + } + + this._pipeline = pipeline; + + return true; + } + + public destroy() { + this.destroyViews(); + this.destroyScenes(); + + if (this._pipeline) { + this._pipeline.destroy(); + this._pipeline = null; + } + } + + public frameMove(deltaTime: number) { + + if (this._pipeline) { + for (let i = 0; i < this._views.length; ++i) { + this._pipeline.render(this._views[i]); + } + } + + if (this._device) { + this._device.present(); + } + } + + public createWindow(info: GFXWindowInfo): GFXWindow | null { + if (this._device) { + let window = this._device.createWindow(info); + if (window) { + this._windows.push(window); + return window; + } + } + + return null; + } + + public destroyWindow(window: GFXWindow) { + for (let i = 0; i < this._windows.length; ++i) { + if (this._windows[i] === window) { + window.destroy(); + this._windows.splice(i); + return; + } + } + } + + public destroyWindows() { + for (let i = 0; i < this._windows.length; ++i) { + this._windows[i].destroy(); + } + this._windows = []; + } + + public createScene(): Scene | null { + let scene = new Scene; + this._scenes.push(scene); + return scene; + } + + public destroyScene(scene: Scene) { + for (let i = 0; i < this._scenes.length; ++i) { + if (this._scenes[i] === scene) { + this._scenes.splice(i); + return; + } + } + } + + public destroyScenes() { + this._scenes = []; + } + + public createView(info: RenderViewInfo): RenderView | null { + let view = new RenderView; + if (view.initialize(info)) { + this._views.push(view); + this._views.sort((a: RenderView, b: RenderView) => { + return a.priority - b.priority; + }); + return view; + } else { + return null; + } + } + + public destroyView(view: RenderView) { + for (let i = 0; i < this._views.length; ++i) { + if (this._views[i] === view) { + this._views.splice(i); + return; + } + } + } + + public destroyViews() { + for (let i = 0; i < this._views.length; ++i) { + this._views[i].destroy(); + } + this._views = []; + } + + public get pipeline(): RenderPipeline | null { + return this._pipeline; + } + + public get scenes(): Scene[] { + return this._scenes; + } + + public get views(): RenderView[] { + return this._views; + } + + private _device: GFXDevice | null = null; + private _windows: GFXWindow[] = []; + private _pipeline: RenderPipeline | null = null; + private _scenes: Scene[] = []; + private _views: RenderView[] = []; +}; diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index fef0883783..81aeccc495 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -42,6 +42,7 @@ export abstract class GFXDevice { public abstract createCommandBuffer(info: GFXCommandBufferInfo) : GFXCommandBuffer | null; public abstract createQueue(info: GFXQueueInfo) : GFXQueue | null; public abstract createWindow(info: GFXWindowInfo) : GFXWindow | null; + public abstract present(); public get queue(): GFXQueue { return this._queue; diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/renderer/gfx/gfx-pipeline-state.ts index aafec1e3e7..aa7af9addd 100644 --- a/cocos/renderer/gfx/gfx-pipeline-state.ts +++ b/cocos/renderer/gfx/gfx-pipeline-state.ts @@ -96,7 +96,6 @@ export enum GFXColorMask { }; export class GFXRasterizerState { - name: string = ""; isDiscard: boolean = false; polygonMode: GFXPolygonMode = GFXPolygonMode.FILL; shadeModel: GFXShadeModel = GFXShadeModel.GOURAND; @@ -123,7 +122,6 @@ export class GFXRasterizerState { }; export class GFXDepthStencilState { - name: string = ""; isDepthTest: boolean = true; isWriteDepth: boolean = true; depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; @@ -190,7 +188,6 @@ export class GFXBlendTarget { }; export class GFXBlendState { - name: string = ""; isA2C: boolean = false; isIndepend: boolean = false; factor: number[] = [0, 0, 0, 0]; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index 7d8965e3a9..a2ea99b647 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -320,6 +320,9 @@ export class WebGLGFXDevice extends GFXDevice { } } + public present() { + } + public get gl(): WebGLRenderingContext { return this._webGLRC; } diff --git a/cocos/renderer/pipeline/forward/forward-flow.ts b/cocos/renderer/pipeline/forward/forward-flow.ts new file mode 100644 index 0000000000..643cc8c202 --- /dev/null +++ b/cocos/renderer/pipeline/forward/forward-flow.ts @@ -0,0 +1,19 @@ +import { RenderFlow, RenderFlowInfo } from "../render-flow"; + +export class ForwardFlow extends RenderFlow { + + public initialize(info: RenderFlowInfo): boolean { + + if(info.name) { + this._name = info.name; + } + + this._priority = info.priority; + + return true; + } + + public destroy(): void { + this.destroyStages(); + } +}; diff --git a/cocos/renderer/pipeline/forward/forward-pipeline.ts b/cocos/renderer/pipeline/forward/forward-pipeline.ts new file mode 100644 index 0000000000..cd541a99df --- /dev/null +++ b/cocos/renderer/pipeline/forward/forward-pipeline.ts @@ -0,0 +1,13 @@ +import { RenderPipeline } from "../render-pipeline"; + +export class ForwardPipeline extends RenderPipeline { + + public initialize(): boolean { + + return true; + } + + public destroy(): void { + this.destroyFlows(); + } +}; diff --git a/cocos/renderer/pipeline/forward/forward-stage.ts b/cocos/renderer/pipeline/forward/forward-stage.ts new file mode 100644 index 0000000000..dc2cc64ada --- /dev/null +++ b/cocos/renderer/pipeline/forward/forward-stage.ts @@ -0,0 +1,16 @@ +import { RenderStage, RenderStageInfo } from "../render-stage"; + +export class ForwardStage extends RenderStage { + + public initialize(info: RenderStageInfo): boolean { + return true; + } + + public destroy() { + + } + + public render() { + + } +}; diff --git a/cocos/renderer/pipeline/render-flow.ts b/cocos/renderer/pipeline/render-flow.ts new file mode 100644 index 0000000000..3bc363c87d --- /dev/null +++ b/cocos/renderer/pipeline/render-flow.ts @@ -0,0 +1,52 @@ +import { RenderStage, RenderStageInfo } from "./render-stage"; +import { RenderView } from "./render-view"; + +export interface RenderFlowInfo { + name?: string; + priority: number; +}; + +export abstract class RenderFlow { + + public abstract initialize(info: RenderFlowInfo): boolean; + public abstract destroy(); + + public render(view: RenderView) { + for(let i = 0; i < this._stages.length; ++i) { + this._stages[i].render(view); + } + } + + public resize(width, height) { + + } + + public createStage(clazz: new(flow: RenderFlow) => T, info : RenderStageInfo): RenderStage | null { + let stage: RenderStage = new clazz(this); + if(stage.initialize(info)) { + this._stages.push(stage); + this._stages.sort((a, b) => { + return a.priority - b.priority; + }); + + return stage; + } else { + return null; + } + } + + public destroyStages() { + for(let i = 0; i < this._stages.length; ++i) { + this._stages[i].destroy(); + } + this._stages = []; + } + + public get priority(): number { + return this._priority; + } + + protected _name: string = ""; + protected _priority: number = 0; + protected _stages: RenderStage[] = []; +}; diff --git a/cocos/renderer/pipeline/render-pipeline.ts b/cocos/renderer/pipeline/render-pipeline.ts new file mode 100644 index 0000000000..3de6d466ed --- /dev/null +++ b/cocos/renderer/pipeline/render-pipeline.ts @@ -0,0 +1,45 @@ +import { RenderView } from "./render-view"; +import { RenderFlow, RenderFlowInfo } from "./render-flow"; + +export abstract class RenderPipeline { + + public abstract initialize(): boolean; + public abstract destroy(); + + public render(view: RenderView) { + for(let i = 0; i < this._flows.length; ++i) { + this._flows[i].render(view); + } + } + + public resize(width, height) { + + } + + public createFlow(clazz: new(pipeline: RenderPipeline) => T, info : RenderFlowInfo): RenderFlow | null { + let flow: RenderFlow = new clazz(this); + if(flow.initialize(info)) { + this._flows.push(flow); + this._flows.sort((a: RenderFlow, b: RenderFlow) => { + return a.priority - b.priority; + }); + + return flow; + } else { + return null; + } + } + + public destroyFlows() { + for(let i = 0; i < this._flows.length; ++i) { + this._flows[i].destroy(); + } + this._flows = []; + } + + public get flows(): RenderFlow[] { + return this._flows; + } + + protected _flows: RenderFlow[] = []; +}; diff --git a/cocos/renderer/pipeline/render-stage.ts b/cocos/renderer/pipeline/render-stage.ts new file mode 100644 index 0000000000..231cd95866 --- /dev/null +++ b/cocos/renderer/pipeline/render-stage.ts @@ -0,0 +1,28 @@ +import { GFXRenderPass } from "../gfx/gfx-render-pass"; +import { GFXFramebuffer } from "../gfx/gfx-framebuffer"; +import { RenderView } from "./render-view"; + +export interface RenderStageInfo { + name?: string; + priority: number; + renderPass: GFXRenderPass; + framebuffer: GFXFramebuffer; +}; + +export abstract class RenderStage { + + public abstract initialize(info: RenderStageInfo): boolean; + public abstract destroy(); + public abstract render(view: RenderView); + + public resize(width, height) { + + } + + public get priority(): number { + return this._priority; + } + + protected _name: string = ""; + protected _priority: number = 0; +}; diff --git a/cocos/renderer/pipeline/render-view.ts b/cocos/renderer/pipeline/render-view.ts new file mode 100644 index 0000000000..849d500612 --- /dev/null +++ b/cocos/renderer/pipeline/render-view.ts @@ -0,0 +1,77 @@ +import { Scene } from "../scene/scene"; +import { Camera } from "../scene/camera"; +import { GFXWindow } from "../gfx/gfx-window"; + +export interface RenderViewInfo { + window: GFXWindow; + priority: number; + width: number; + height: number; +}; + +export class RenderView { + + public initialize(info: RenderViewInfo): boolean { + + if (!info.window) { + console.error("RenderViewInfo.window is null."); + return false; + } + + if (info.width <= 0 || info.height <= 0) { + console.error("RenderView size is an error size."); + return false; + } + + this._window = info.window; + this._priority = info.priority; + this._width = info.width; + this._height = info.height; + + return true; + } + + public destroy() { + this._window = null; + this._priority = 0; + this._width = 0; + this._height = 0; + } + + public resize(width, height) { + + } + + public attach(scene: Scene, camera: Camera) { + this._scene = scene; + this._camera = camera; + } + + public detach() { + this._scene = null; + this._camera = null; + } + + public get window(): GFXWindow | null { + return this._window; + } + + public get priority(): number { + return this._priority; + } + + public get width(): number { + return this._width; + } + + public get height(): number { + return this._height; + } + + protected _window: GFXWindow | null = null; + protected _priority: number = 0; + protected _width: number = 0; + protected _height: number = 0; + protected _scene: Scene | null = null; + protected _camera: Camera | null = null; +}; From d9c271ee00ed73c482f3d45c2caa50f4cf02c6fa Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Sat, 29 Dec 2018 18:28:35 +0800 Subject: [PATCH 012/267] structure --- .../binding-layout.ts} | 8 +- .../gfx/gfx-buffer.ts => gfx/buffer.ts} | 4 +- .../command-allocator.ts} | 6 +- .../command-buffer.ts} | 18 +-- .../gfx/gfx-define.ts => gfx/define.ts} | 0 .../gfx/gfx-device.ts => gfx/device.ts} | 30 ++--- .../gfx-framebuffer.ts => gfx/framebuffer.ts} | 6 +- cocos/gfx/index.ts | 29 ++++ .../input-assembler.ts} | 8 +- .../pipeline-layout.ts} | 6 +- .../pipeline-state.ts} | 10 +- .../gfx/gfx-queue.ts => gfx/queue.ts} | 2 +- .../gfx-render-pass.ts => gfx/render-pass.ts} | 4 +- .../gfx/gfx-sampler.ts => gfx/sampler.ts} | 26 ++-- .../gfx/gfx-shader.ts => gfx/shader.ts} | 6 +- .../texture-view.ts} | 6 +- .../gfx/gfx-texture.ts => gfx/texture.ts} | 4 +- .../webgl/webgl-binding-layout.ts} | 6 +- .../webgl/webgl-buffer.ts} | 8 +- .../webgl/webgl-command-allocator.ts} | 8 +- .../webgl/webgl-command-buffer.ts} | 38 +++--- .../gfx/webgl/webgl-commands.ts | 22 +-- .../webgl/webgl-device.ts} | 64 ++++----- .../webgl/webgl-framebuffer.ts} | 8 +- .../gfx/webgl/webgl-gpu-objects.ts | 20 +-- .../webgl/webgl-input-assembler.ts} | 6 +- .../webgl/webgl-pipeline-layout.ts} | 6 +- .../webgl/webgl-pipeline-state.ts} | 6 +- .../webgl/webgl-queue.ts} | 10 +- .../webgl/webgl-render-pass.ts} | 10 +- .../webgl/webgl-sampler.ts} | 6 +- .../webgl/webgl-shader.ts} | 6 +- .../gfx/webgl/webgl-state-cache.ts | 6 +- .../webgl/webgl-texture-view.ts} | 6 +- .../webgl/webgl-texture.ts} | 8 +- .../webgl/webgl-window.ts} | 16 +-- .../gfx/gfx-window.ts => gfx/window.ts} | 12 +- cocos/renderer/core/constants.js | 13 -- cocos/renderer/core/constants.ts | 11 ++ cocos/renderer/core/pass.js | 126 ------------------ cocos/renderer/core/pass.ts | 52 ++++++++ cocos/renderer/gfx/index.js | 30 ----- index.js | 1 + 43 files changed, 301 insertions(+), 377 deletions(-) rename cocos/{renderer/gfx/gfx-binding-layout.ts => gfx/binding-layout.ts} (92%) rename cocos/{renderer/gfx/gfx-buffer.ts => gfx/buffer.ts} (94%) rename cocos/{renderer/gfx/gfx-command-allocator.ts => gfx/command-allocator.ts} (86%) rename cocos/{renderer/gfx/gfx-command-buffer.ts => gfx/command-buffer.ts} (81%) rename cocos/{renderer/gfx/gfx-define.ts => gfx/define.ts} (100%) rename cocos/{renderer/gfx/gfx-device.ts => gfx/device.ts} (67%) rename cocos/{renderer/gfx/gfx-framebuffer.ts => gfx/framebuffer.ts} (80%) create mode 100644 cocos/gfx/index.ts rename cocos/{renderer/gfx/gfx-input-assembler.ts => gfx/input-assembler.ts} (94%) rename cocos/{renderer/gfx/gfx-pipeline-layout.ts => gfx/pipeline-layout.ts} (81%) rename cocos/{renderer/gfx/gfx-pipeline-state.ts => gfx/pipeline-state.ts} (96%) rename cocos/{renderer/gfx/gfx-queue.ts => gfx/queue.ts} (92%) rename cocos/{renderer/gfx/gfx-render-pass.ts => gfx/render-pass.ts} (96%) rename cocos/{renderer/gfx/gfx-sampler.ts => gfx/sampler.ts} (63%) rename cocos/{renderer/gfx/gfx-shader.ts => gfx/shader.ts} (91%) rename cocos/{renderer/gfx/gfx-texture-view.ts => gfx/texture-view.ts} (91%) rename cocos/{renderer/gfx/gfx-texture.ts => gfx/texture.ts} (95%) rename cocos/{renderer/gfx/webgl/webgl-gfx-binding-layout.ts => gfx/webgl/webgl-binding-layout.ts} (92%) rename cocos/{renderer/gfx/webgl/webgl-gfx-buffer.ts => gfx/webgl/webgl-buffer.ts} (88%) rename cocos/{renderer/gfx/webgl/webgl-gfx-command-allocator.ts => gfx/webgl/webgl-command-allocator.ts} (97%) rename cocos/{renderer/gfx/webgl/webgl-gfx-command-buffer.ts => gfx/webgl/webgl-command-buffer.ts} (87%) rename cocos/{renderer => }/gfx/webgl/webgl-commands.ts (99%) rename cocos/{renderer/gfx/webgl/webgl-gfx-device.ts => gfx/webgl/webgl-device.ts} (94%) rename cocos/{renderer/gfx/webgl/webgl-gfx-framebuffer.ts => gfx/webgl/webgl-framebuffer.ts} (85%) rename cocos/{renderer => }/gfx/webgl/webgl-gpu-objects.ts (93%) rename cocos/{renderer/gfx/webgl/webgl-gfx-input-assembler.ts => gfx/webgl/webgl-input-assembler.ts} (86%) rename cocos/{renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts => gfx/webgl/webgl-pipeline-layout.ts} (80%) rename cocos/{renderer/gfx/webgl/webgl-gfx-pipeline-state.ts => gfx/webgl/webgl-pipeline-state.ts} (86%) rename cocos/{renderer/gfx/webgl/webgl-gfx-queue.ts => gfx/webgl/webgl-queue.ts} (72%) rename cocos/{renderer/gfx/webgl/webgl-gfx-render-pass.ts => gfx/webgl/webgl-render-pass.ts} (81%) rename cocos/{renderer/gfx/webgl/webgl-gfx-sampler.ts => gfx/webgl/webgl-sampler.ts} (83%) rename cocos/{renderer/gfx/webgl/webgl-gfx-shader.ts => gfx/webgl/webgl-shader.ts} (85%) rename cocos/{renderer => }/gfx/webgl/webgl-state-cache.ts (96%) rename cocos/{renderer/gfx/webgl/webgl-gfx-texture-view.ts => gfx/webgl/webgl-texture-view.ts} (87%) rename cocos/{renderer/gfx/webgl/webgl-gfx-texture.ts => gfx/webgl/webgl-texture.ts} (90%) rename cocos/{renderer/gfx/webgl/webgl-gfx-window.ts => gfx/webgl/webgl-window.ts} (92%) rename cocos/{renderer/gfx/gfx-window.ts => gfx/window.ts} (84%) delete mode 100644 cocos/renderer/core/constants.js create mode 100644 cocos/renderer/core/constants.ts delete mode 100644 cocos/renderer/core/pass.js create mode 100644 cocos/renderer/core/pass.ts diff --git a/cocos/renderer/gfx/gfx-binding-layout.ts b/cocos/gfx/binding-layout.ts similarity index 92% rename from cocos/renderer/gfx/gfx-binding-layout.ts rename to cocos/gfx/binding-layout.ts index f6278e0a45..9ff0a7e3e1 100644 --- a/cocos/renderer/gfx/gfx-binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -1,7 +1,7 @@ -import { GFXDevice } from './gfx-device'; -import { GFXBuffer } from './gfx-buffer'; -import { GFXTextureView } from './gfx-texture-view'; -import { GFXSampler } from './gfx-sampler'; +import { GFXDevice } from './device'; +import { GFXBuffer } from './buffer'; +import { GFXTextureView } from './texture-view'; +import { GFXSampler } from './sampler'; export enum GFXBindingType { UNKNOWN, diff --git a/cocos/renderer/gfx/gfx-buffer.ts b/cocos/gfx/buffer.ts similarity index 94% rename from cocos/renderer/gfx/gfx-buffer.ts rename to cocos/gfx/buffer.ts index 9fc9f8c68e..e7335869c0 100644 --- a/cocos/renderer/gfx/gfx-buffer.ts +++ b/cocos/gfx/buffer.ts @@ -1,5 +1,5 @@ -import { GFXDevice } from './gfx-device'; -import { BufferView } from './gfx-define'; +import { GFXDevice } from './device'; +import { BufferView } from './define'; export enum GFXBufferUsageBit { NONE = 0, diff --git a/cocos/renderer/gfx/gfx-command-allocator.ts b/cocos/gfx/command-allocator.ts similarity index 86% rename from cocos/renderer/gfx/gfx-command-allocator.ts rename to cocos/gfx/command-allocator.ts index e4e9bd5fc2..5ac927da20 100644 --- a/cocos/renderer/gfx/gfx-command-allocator.ts +++ b/cocos/gfx/command-allocator.ts @@ -1,10 +1,10 @@ -import { GFXDevice } from './gfx-device'; +import { GFXDevice } from './device'; export interface GFXCommandAllocatorInfo { }; export abstract class GFXCommandAllocator { - + constructor(device : GFXDevice) { this._device = device; } @@ -13,4 +13,4 @@ export abstract class GFXCommandAllocator { public abstract destroy(); protected _device : GFXDevice; -} \ No newline at end of file +} diff --git a/cocos/renderer/gfx/gfx-command-buffer.ts b/cocos/gfx/command-buffer.ts similarity index 81% rename from cocos/renderer/gfx/gfx-command-buffer.ts rename to cocos/gfx/command-buffer.ts index 09804ea0c1..154a8d2ba6 100644 --- a/cocos/renderer/gfx/gfx-command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -1,12 +1,12 @@ -import { GFXDevice } from './gfx-device'; -import { GFXCommandAllocator } from './gfx-command-allocator'; -import { GFXBuffer } from './gfx-buffer'; -import { GFXInputAssembler } from './gfx-input-assembler'; -import { GFXPipelineState } from './gfx-pipeline-state'; -import { GFXBindingLayout } from './gfx-binding-layout'; -import { GFXTextureLayout } from './gfx-render-pass'; -import { GFXTexture } from './gfx-texture'; -import { GFXFramebuffer } from './gfx-framebuffer'; +import { GFXDevice } from './device'; +import { GFXCommandAllocator } from './command-allocator'; +import { GFXBuffer } from './buffer'; +import { GFXInputAssembler } from './input-assembler'; +import { GFXPipelineState } from './pipeline-state'; +import { GFXBindingLayout } from './binding-layout'; +import { GFXTextureLayout } from './render-pass'; +import { GFXTexture } from './texture'; +import { GFXFramebuffer } from './framebuffer'; export class GFXTextureSubres { diff --git a/cocos/renderer/gfx/gfx-define.ts b/cocos/gfx/define.ts similarity index 100% rename from cocos/renderer/gfx/gfx-define.ts rename to cocos/gfx/define.ts diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/gfx/device.ts similarity index 67% rename from cocos/renderer/gfx/gfx-device.ts rename to cocos/gfx/device.ts index 81aeccc495..cb18c3efa5 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/gfx/device.ts @@ -1,18 +1,18 @@ -import { GFXBuffer, GFXBufferInfo } from './gfx-buffer'; -import { GFXQueue, GFXQueueInfo } from './gfx-queue'; -import { GFXTexture, GFXTextureInfo } from './gfx-texture'; -import { GFXTextureViewInfo, GFXTextureView } from './gfx-texture-view'; -import { GFXFramebufferInfo, GFXFramebuffer } from './gfx-framebuffer'; -import { GFXRenderPassInfo, GFXRenderPass } from './gfx-render-pass'; -import { GFXPipelineStateInfo, GFXPipelineState } from './gfx-pipeline-state'; -import { GFXPipelineLayoutInfo, GFXPipelineLayout } from './gfx-pipeline-layout'; -import { GFXSamplerInfo, GFXSampler } from './gfx-sampler'; -import { GFXShaderInfo, GFXShader } from './gfx-shader'; -import { GFXInputAssemblerInfo, GFXInputAssembler } from './gfx-input-assembler'; -import { GFXCommandBufferInfo, GFXCommandBuffer } from './gfx-command-buffer'; -import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './gfx-command-allocator'; -import { GFXWindowInfo, GFXWindow } from './gfx-window'; -import { GFXBindingLayoutInfo, GFXBindingLayout } from './gfx-binding-layout'; +import { GFXBuffer, GFXBufferInfo } from './buffer'; +import { GFXQueue, GFXQueueInfo } from './queue'; +import { GFXTexture, GFXTextureInfo } from './texture'; +import { GFXTextureViewInfo, GFXTextureView } from './texture-view'; +import { GFXFramebufferInfo, GFXFramebuffer } from './framebuffer'; +import { GFXRenderPassInfo, GFXRenderPass } from './render-pass'; +import { GFXPipelineStateInfo, GFXPipelineState } from './pipeline-state'; +import { GFXPipelineLayoutInfo, GFXPipelineLayout } from './pipeline-layout'; +import { GFXSamplerInfo, GFXSampler } from './sampler'; +import { GFXShaderInfo, GFXShader } from './shader'; +import { GFXInputAssemblerInfo, GFXInputAssembler } from './input-assembler'; +import { GFXCommandBufferInfo, GFXCommandBuffer } from './command-buffer'; +import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './command-allocator'; +import { GFXWindowInfo, GFXWindow } from './window'; +import { GFXBindingLayoutInfo, GFXBindingLayout } from './binding-layout'; export enum GFXFeature { }; diff --git a/cocos/renderer/gfx/gfx-framebuffer.ts b/cocos/gfx/framebuffer.ts similarity index 80% rename from cocos/renderer/gfx/gfx-framebuffer.ts rename to cocos/gfx/framebuffer.ts index ed394a182f..2be7c4b41c 100644 --- a/cocos/renderer/gfx/gfx-framebuffer.ts +++ b/cocos/gfx/framebuffer.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from './gfx-device'; -import { GFXTextureView } from './gfx-texture-view'; -import { GFXRenderPass } from './gfx-render-pass'; +import { GFXDevice } from './device'; +import { GFXTextureView } from './texture-view'; +import { GFXRenderPass } from './render-pass'; export interface GFXFramebufferInfo { renderPass: GFXRenderPass; diff --git a/cocos/gfx/index.ts b/cocos/gfx/index.ts new file mode 100644 index 0000000000..7ddb6bb1fa --- /dev/null +++ b/cocos/gfx/index.ts @@ -0,0 +1,29 @@ +import { GFXDevice } from './device'; +import { GFXBuffer } from './buffer'; +import { GFXTexture } from './texture'; +import { GFXTextureView } from './texture-view'; +import { GFXSampler } from './sampler'; +import { GFXShader } from './shader'; +import { GFXInputAssembler } from './input-assembler'; +import { GFXRenderPass } from './render-pass'; +import { GFXFramebuffer } from './framebuffer'; +import { GFXPipelineLayout } from './pipeline-layout'; +import { GFXPipelineState } from './pipeline-state'; +import { GFXCommandBuffer } from './command-buffer'; +import { GFXQueue } from './queue'; +import { WebGLGFXDevice } from './webgl/webgl-device'; + +cc.GFXDevice = GFXDevice; +cc.GFXBuffer = GFXBuffer; +cc.GFXTexture = GFXTexture; +cc.GFXTextureView = GFXTextureView; +cc.GFXSampler = GFXSampler; +cc.GFXShader = GFXShader; +cc.GFXInputAssembler = GFXInputAssembler; +cc.GFXRenderPass = GFXRenderPass; +cc.GFXFramebuffer = GFXFramebuffer; +cc.GFXPipelineLayout = GFXPipelineLayout; +cc.GFXPipelineState = GFXPipelineState; +cc.GFXCommandBuffer = GFXCommandBuffer; +cc.GFXQueue = GFXQueue; +cc.WebGLGFXDevice = WebGLGFXDevice; diff --git a/cocos/renderer/gfx/gfx-input-assembler.ts b/cocos/gfx/input-assembler.ts similarity index 94% rename from cocos/renderer/gfx/gfx-input-assembler.ts rename to cocos/gfx/input-assembler.ts index ba4f5adcdb..4d6c87ae50 100644 --- a/cocos/renderer/gfx/gfx-input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,7 +1,7 @@ -import { GFXDevice } from './gfx-device'; -import { GFXFormat } from './gfx-define'; -import { GFXBuffer } from './gfx-buffer'; -import { GFXShader } from './gfx-shader'; +import { GFXDevice } from './device'; +import { GFXFormat } from './define'; +import { GFXBuffer } from './buffer'; +import { GFXShader } from './shader'; export interface GFXInputAttribute { name: string; diff --git a/cocos/renderer/gfx/gfx-pipeline-layout.ts b/cocos/gfx/pipeline-layout.ts similarity index 81% rename from cocos/renderer/gfx/gfx-pipeline-layout.ts rename to cocos/gfx/pipeline-layout.ts index 811d3e4afd..e669d95f93 100644 --- a/cocos/renderer/gfx/gfx-pipeline-layout.ts +++ b/cocos/gfx/pipeline-layout.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from './gfx-device'; -import { GFXBindingLayout } from './gfx-binding-layout'; -import { GFXShaderType } from './gfx-shader'; +import { GFXDevice } from './device'; +import { GFXBindingLayout } from './binding-layout'; +import { GFXShaderType } from './shader'; export class GFXPushConstantRange { shaderType : GFXShaderType = GFXShaderType.VERTEX; diff --git a/cocos/renderer/gfx/gfx-pipeline-state.ts b/cocos/gfx/pipeline-state.ts similarity index 96% rename from cocos/renderer/gfx/gfx-pipeline-state.ts rename to cocos/gfx/pipeline-state.ts index aa7af9addd..babe08015c 100644 --- a/cocos/renderer/gfx/gfx-pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -1,8 +1,8 @@ -import { GFXDevice } from './gfx-device'; -import { GFXShader } from './gfx-shader'; -import { GFXRenderPass } from './gfx-render-pass'; -import { GFXPipelineLayout } from './gfx-pipeline-layout'; -import { GFXInputAttribute } from './gfx-input-assembler'; +import { GFXDevice } from './device'; +import { GFXShader } from './shader'; +import { GFXRenderPass } from './render-pass'; +import { GFXPipelineLayout } from './pipeline-layout'; +import { GFXInputAttribute } from './input-assembler'; export enum GFXPrimitiveMode { POINT_LIST, diff --git a/cocos/renderer/gfx/gfx-queue.ts b/cocos/gfx/queue.ts similarity index 92% rename from cocos/renderer/gfx/gfx-queue.ts rename to cocos/gfx/queue.ts index 5546eecef3..6ebf7fc77e 100644 --- a/cocos/renderer/gfx/gfx-queue.ts +++ b/cocos/gfx/queue.ts @@ -1,4 +1,4 @@ -import { GFXDevice } from './gfx-device'; +import { GFXDevice } from './device'; export enum GFXQueueType { GRAPHICS, diff --git a/cocos/renderer/gfx/gfx-render-pass.ts b/cocos/gfx/render-pass.ts similarity index 96% rename from cocos/renderer/gfx/gfx-render-pass.ts rename to cocos/gfx/render-pass.ts index ebf94e5594..8dc6b7cd84 100644 --- a/cocos/renderer/gfx/gfx-render-pass.ts +++ b/cocos/gfx/render-pass.ts @@ -1,5 +1,5 @@ -import { GFXFormat, GFXFormatInfo } from './gfx-define'; -import { GFXDevice } from './gfx-device'; +import { GFXFormat, GFXFormatInfo } from './define'; +import { GFXDevice } from './device'; // Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. export enum GFXLoadOp diff --git a/cocos/renderer/gfx/gfx-sampler.ts b/cocos/gfx/sampler.ts similarity index 63% rename from cocos/renderer/gfx/gfx-sampler.ts rename to cocos/gfx/sampler.ts index 33f4557c9e..1258adf23c 100644 --- a/cocos/renderer/gfx/gfx-sampler.ts +++ b/cocos/gfx/sampler.ts @@ -1,5 +1,5 @@ -import { GFXDevice } from './gfx-device'; -import { GFXComparisonFunc } from './gfx-pipeline-state'; +import { GFXDevice } from './device'; +import { GFXComparisonFunc } from './pipeline-state'; export enum GFXFilter { NONE, @@ -31,17 +31,17 @@ export class GFXSamplerInfo { mipLODBias : number = 0.0; public compare(state : GFXSamplerInfo) : boolean { - return (this.minFilter === state.minFilter) && - (this.magFilter === state.magFilter) && - (this.mipFilter === state.mipFilter) && - (this.addressU === state.addressU) && - (this.addressV === state.addressV) && - (this.addressW === state.addressW) && - (this.maxAnisotropy === state.maxAnisotropy) && - (this.cmpFunc === state.cmpFunc) && - (this.borderColor === state.borderColor) && - (this.minLOD === state.minLOD) && - (this.maxLOD === state.maxLOD) && + return (this.minFilter === state.minFilter) && + (this.magFilter === state.magFilter) && + (this.mipFilter === state.mipFilter) && + (this.addressU === state.addressU) && + (this.addressV === state.addressV) && + (this.addressW === state.addressW) && + (this.maxAnisotropy === state.maxAnisotropy) && + (this.cmpFunc === state.cmpFunc) && + (this.borderColor === state.borderColor) && + (this.minLOD === state.minLOD) && + (this.maxLOD === state.maxLOD) && (this.mipLODBias === state.mipLODBias); } }; diff --git a/cocos/renderer/gfx/gfx-shader.ts b/cocos/gfx/shader.ts similarity index 91% rename from cocos/renderer/gfx/gfx-shader.ts rename to cocos/gfx/shader.ts index feff85709a..afd54e3ad8 100644 --- a/cocos/renderer/gfx/gfx-shader.ts +++ b/cocos/gfx/shader.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from './gfx-device'; -import { GFXBinding } from './gfx-binding-layout'; -import { GFXType } from './gfx-define'; +import { GFXDevice } from './device'; +import { GFXBinding } from './binding-layout'; +import { GFXType } from './define'; export enum GFXShaderType { VERTEX, diff --git a/cocos/renderer/gfx/gfx-texture-view.ts b/cocos/gfx/texture-view.ts similarity index 91% rename from cocos/renderer/gfx/gfx-texture-view.ts rename to cocos/gfx/texture-view.ts index 4d56e1c12b..bd5dec1cc6 100644 --- a/cocos/renderer/gfx/gfx-texture-view.ts +++ b/cocos/gfx/texture-view.ts @@ -1,6 +1,6 @@ -import { GFXFormat, GFXFormatInfo } from './gfx-define'; -import { GFXDevice } from './gfx-device'; -import { GFXTexture } from './gfx-texture'; +import { GFXFormat, GFXFormatInfo } from './define'; +import { GFXDevice } from './device'; +import { GFXTexture } from './texture'; export enum GFXTextureViewType { TV1D, diff --git a/cocos/renderer/gfx/gfx-texture.ts b/cocos/gfx/texture.ts similarity index 95% rename from cocos/renderer/gfx/gfx-texture.ts rename to cocos/gfx/texture.ts index ba650cc2cc..5d36e5d00c 100644 --- a/cocos/renderer/gfx/gfx-texture.ts +++ b/cocos/gfx/texture.ts @@ -1,5 +1,5 @@ -import { GFXFormat, GFXFormatInfo } from './gfx-define'; -import { GFXDevice } from './gfx-device'; +import { GFXFormat, GFXFormatInfo } from './define'; +import { GFXDevice } from './device'; export enum GFXTextureType { TEX1D, diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts b/cocos/gfx/webgl/webgl-binding-layout.ts similarity index 92% rename from cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts rename to cocos/gfx/webgl/webgl-binding-layout.ts index 8a484b6712..9e67558ca8 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-binding-layout.ts +++ b/cocos/gfx/webgl/webgl-binding-layout.ts @@ -1,7 +1,7 @@ -import { GFXDevice } from '../gfx-device'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBindingLayout } from './webgl-gpu-objects'; -import { GFXBindingLayout, GFXBindingLayoutInfo, GFXBindingUnit } from '../gfx-binding-layout'; +import { GFXBindingLayout, GFXBindingLayoutInfo, GFXBindingUnit } from '../binding-layout'; export class WebGLGFXBindingLayout extends GFXBindingLayout { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts similarity index 88% rename from cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts rename to cocos/gfx/webgl/webgl-buffer.ts index 91d752cf48..604e56ed5c 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,8 +1,8 @@ -import { GFXBufferInfo, GFXBuffer, GFXMemoryUsageBit, GFXBufferAccess, GFXBufferAccessBit, GFXBufferUsageBit } from '../gfx-buffer'; -import { GFXDevice } from '../gfx-device'; +import { GFXBufferInfo, GFXBuffer, GFXMemoryUsageBit, GFXBufferAccess, GFXBufferAccessBit, GFXBufferUsageBit } from '../buffer'; +import { GFXDevice } from '../device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { BufferView } from '../gfx-define'; +import { WebGLGFXDevice } from './webgl-device'; +import { BufferView } from '../define'; export class WebGLGFXBuffer extends GFXBuffer { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts similarity index 97% rename from cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts rename to cocos/gfx/webgl/webgl-command-allocator.ts index 4c6ba5256b..8d54f06868 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -1,9 +1,9 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../gfx-command-allocator'; +import { GFXDevice } from '../device'; +import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../command-allocator'; import { WebGLCmdUpdateBuffer, WebGLCmdBeginRenderPass, WebGLCmdBindInputAssembler, WebGLCmdDraw, WebGLCmdBindPipelineState, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; export class WebGLGFXCommandPool { - + constructor(count: number, increase : number) { this._frees = new Array(count); this._freeIdx = count - 1; @@ -11,7 +11,7 @@ export class WebGLGFXCommandPool { } alloc(clazz: new() => T) : T | null { - + if (this._freeIdx <= 0) { let size = this._frees.length + this._increase; let temp = this._frees; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts similarity index 87% rename from cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts rename to cocos/gfx/webgl/webgl-command-buffer.ts index 8ad6fc47dc..71a1e3bc91 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,21 +1,21 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXCommandBuffer, GFXCommandBufferInfo, GFXBufferTextureCopy } from '../gfx-command-buffer'; -import { GFXBuffer } from '../gfx-buffer'; +import { GFXDevice } from '../device'; +import { GFXCommandBuffer, GFXCommandBufferInfo, GFXBufferTextureCopy } from '../command-buffer'; +import { GFXBuffer } from '../buffer'; import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; -import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { WebGLGFXBuffer } from './webgl-gfx-buffer'; -import { GFXFramebuffer } from '../gfx-framebuffer'; -import { WebGLGFXFramebuffer } from './webgl-gfx-framebuffer'; -import { GFXInputAssembler } from '../gfx-input-assembler'; -import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; -import { GFXPipelineState } from '../gfx-pipeline-state'; -import { WebGLGFXPipelineState } from './webgl-gfx-pipeline-state'; -import { GFXBindingLayout } from '../gfx-binding-layout'; -import { WebGLGFXBindingLayout } from './webgl-gfx-binding-layout'; -import { GFXTexture } from '../gfx-texture'; -import { GFXTextureLayout } from '../gfx-render-pass'; -import { WebGLGFXTexture } from './webgl-gfx-texture'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { GFXFramebuffer } from '../framebuffer'; +import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { GFXInputAssembler } from '../input-assembler'; +import { WebGLGFXInputAssembler } from './webgl-input-assembler'; +import { GFXPipelineState } from '../pipeline-state'; +import { WebGLGFXPipelineState } from './webgl-pipeline-state'; +import { GFXBindingLayout } from '../binding-layout'; +import { WebGLGFXBindingLayout } from './webgl-binding-layout'; +import { GFXTexture } from '../texture'; +import { GFXTextureLayout } from '../render-pass'; +import { WebGLGFXTexture } from './webgl-texture'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { @@ -116,7 +116,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { this.cmdPackage.cmds.push(WebGLCmd.DRAW); } } - + public updateBuffer(buffer : GFXBuffer, data : Buffer, offset : number) { let gpuBuffer = (buffer).gpuBuffer; if(gpuBuffer) { @@ -126,7 +126,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { cmd.buffer = data.slice(0); cmd.offset = offset; this.cmdPackage.updateBufferCmds.push(cmd); - + this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); } } diff --git a/cocos/renderer/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts similarity index 99% rename from cocos/renderer/gfx/webgl/webgl-commands.ts rename to cocos/gfx/webgl/webgl-commands.ts index e3fd4097f9..6ee4ffd7a7 100644 --- a/cocos/renderer/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,16 +1,16 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; -import { WebGLGFXDevice } from "./webgl-gfx-device"; -import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../gfx-buffer"; -import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, BufferView } from "../gfx-define"; -import { GFXShaderType } from "../gfx-shader"; -import { GFXLoadOp, GFXTextureLayout } from "../gfx-render-pass"; -import { GFXColorMask, GFXCullMode } from "../gfx-pipeline-state"; -import { WebGLGFXCommandAllocator } from "./webgl-gfx-command-allocator"; -import { GFXBindingType } from "../gfx-binding-layout"; +import { WebGLGFXDevice } from "./webgl-device"; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../buffer"; +import { GFXTextureViewType } from "../texture-view"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, BufferView } from "../define"; +import { GFXShaderType } from "../shader"; +import { GFXLoadOp, GFXTextureLayout } from "../render-pass"; +import { GFXColorMask, GFXCullMode } from "../pipeline-state"; +import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; +import { GFXBindingType } from "../binding-layout"; import { WebGLTexUnit } from "./webgl-state-cache"; -import { GFXBufferTextureCopy } from "../gfx-command-buffer"; -import { GFXTextureFlagBit } from "../gfx-texture"; +import { GFXBufferTextureCopy } from "../command-buffer"; +import { GFXTextureFlagBit } from "../texture"; function GFXFormatToWebGLType(format: GFXFormat, device : WebGLGFXDevice): GLenum { switch (format) { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/gfx/webgl/webgl-device.ts similarity index 94% rename from cocos/renderer/gfx/webgl/webgl-gfx-device.ts rename to cocos/gfx/webgl/webgl-device.ts index a2ea99b647..cf15f055df 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,38 +1,38 @@ -import { GFXDeviceInfo, GFXDevice } from '../gfx-device'; -import { GFXBuffer, GFXBufferInfo, GFXBufferUsageBit } from '../gfx-buffer'; -import { WebGLGFXBuffer } from './webgl-gfx-buffer'; -import { WebGLGFXQueue } from './webgl-gfx-queue'; +import { GFXDeviceInfo, GFXDevice } from '../device'; +import { GFXBuffer, GFXBufferInfo, GFXBufferUsageBit } from '../buffer'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLGFXQueue } from './webgl-queue'; import { WebGLStateCache } from './webgl-state-cache'; import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember } from './webgl-commands'; -import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit, GFXTexture } from '../gfx-texture'; -import { GFXTextureViewType, GFXTextureViewInfo, GFXTextureView } from '../gfx-texture-view'; -import { GFXRenderPassInfo, GFXRenderPass } from '../gfx-render-pass'; -import { GFXFramebufferInfo, GFXFramebuffer } from '../gfx-framebuffer'; -import { WebGLGFXRenderPass } from './webgl-gfx-render-pass'; -import { WebGLGFXTextureView } from './webgl-gfx-texture-view'; -import { WebGLGFXTexture } from './webgl-gfx-texture'; -import { GFXShaderInfo, GFXShader } from '../gfx-shader'; -import { GFXSamplerInfo, GFXFilter, GFXSampler, GFXAddress } from '../gfx-sampler'; -import { WebGLGFXCommandAllocator } from './webgl-gfx-command-allocator'; -import { GFXInputAssemblerInfo, GFXInputAssembler } from '../gfx-input-assembler'; -import { WebGLGFXShader } from './webgl-gfx-shader'; -import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../gfx-command-allocator'; -import { GFXPipelineStateInfo, GFXPipelineState } from '../gfx-pipeline-state'; -import { WebGLGFXPipelineLayout } from './webgl-gfx-pipeline-layout'; -import { GFXBindingLayoutInfo, GFXBindingUnit, GFXBindingType, GFXBindingLayout } from '../gfx-binding-layout'; -import { WebGLGFXSampler } from './webgl-gfx-sampler'; -import { GFXCommandBufferInfo, GFXCommandBuffer } from '../gfx-command-buffer'; -import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; -import { WebGLGFXCommandBuffer } from './webgl-gfx-command-buffer'; -import { WebGLGFXPipelineState } from './webgl-gfx-pipeline-state'; -import { GFXPipelineLayoutInfo, GFXPipelineLayout } from '../gfx-pipeline-layout'; -import { WebGLGFXFramebuffer } from './webgl-gfx-framebuffer'; -import { WebGLGFXInputAssembler } from './webgl-gfx-input-assembler'; -import { GFXWindowInfo, GFXWindow } from '../gfx-window'; -import { WebGLGFXWindow } from './webgl-gfx-window'; -import { BufferView } from '../gfx-define'; -import { WebGLGFXBindingLayout } from './webgl-gfx-binding-layout'; +import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit, GFXTexture } from '../texture'; +import { GFXTextureViewType, GFXTextureViewInfo, GFXTextureView } from '../texture-view'; +import { GFXRenderPassInfo, GFXRenderPass } from '../render-pass'; +import { GFXFramebufferInfo, GFXFramebuffer } from '../framebuffer'; +import { WebGLGFXRenderPass } from './webgl-render-pass'; +import { WebGLGFXTextureView } from './webgl-texture-view'; +import { WebGLGFXTexture } from './webgl-texture'; +import { GFXShaderInfo, GFXShader } from '../shader'; +import { GFXSamplerInfo, GFXFilter, GFXSampler, GFXAddress } from '../sampler'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { GFXInputAssemblerInfo, GFXInputAssembler } from '../input-assembler'; +import { WebGLGFXShader } from './webgl-shader'; +import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../command-allocator'; +import { GFXPipelineStateInfo, GFXPipelineState } from '../pipeline-state'; +import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; +import { GFXBindingLayoutInfo, GFXBindingUnit, GFXBindingType, GFXBindingLayout } from '../binding-layout'; +import { WebGLGFXSampler } from './webgl-sampler'; +import { GFXCommandBufferInfo, GFXCommandBuffer } from '../command-buffer'; +import { GFXQueueInfo, GFXQueue } from '../queue'; +import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; +import { WebGLGFXPipelineState } from './webgl-pipeline-state'; +import { GFXPipelineLayoutInfo, GFXPipelineLayout } from '../pipeline-layout'; +import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { WebGLGFXInputAssembler } from './webgl-input-assembler'; +import { GFXWindowInfo, GFXWindow } from '../window'; +import { WebGLGFXWindow } from './webgl-window'; +import { BufferView } from '../define'; +import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ WebGLRenderingContext.POINTS, diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts similarity index 85% rename from cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts rename to cocos/gfx/webgl/webgl-framebuffer.ts index e4cff04ace..08b306d902 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from '../gfx-device'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { GFXFramebuffer, GFXFramebufferInfo } from '../gfx-framebuffer'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; +import { GFXFramebuffer, GFXFramebufferInfo } from '../framebuffer'; import { WebGLGPUFramebuffer } from './webgl-gpu-objects'; export class WebGLGFXFramebuffer extends GFXFramebuffer { @@ -14,7 +14,7 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { if(info.colorViews) { this._colorViews = info.colorViews; } - + this._depthStencilView = info.depthStencilView? info.depthStencilView : null; this._isOffscreen = info.isOffscreen? info.isOffscreen : true; diff --git a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts similarity index 93% rename from cocos/renderer/gfx/webgl/webgl-gpu-objects.ts rename to cocos/gfx/webgl/webgl-gpu-objects.ts index 62d8e9e1b3..29a29dcdc6 100644 --- a/cocos/renderer/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,12 +1,12 @@ -import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from "../gfx-buffer"; -import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit } from "../gfx-texture"; -import { GFXTextureViewType } from "../gfx-texture-view"; -import { GFXFormat, GFXType, BufferView } from "../gfx-define"; -import { GFXColorAttachment, GFXDepthStencilAttachment } from "../gfx-render-pass"; -import { GFXShaderType, GFXShaderMacro, GFXUniformBlock, GFXUniformSampler } from "../gfx-shader"; -import { GFXBindingType } from "../gfx-binding-layout"; -import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; -import { GFXInputAttribute } from "../gfx-input-assembler"; +import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from "../buffer"; +import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit } from "../texture"; +import { GFXTextureViewType } from "../texture-view"; +import { GFXFormat, GFXType, BufferView } from "../define"; +import { GFXColorAttachment, GFXDepthStencilAttachment } from "../render-pass"; +import { GFXShaderType, GFXShaderMacro, GFXUniformBlock, GFXUniformSampler } from "../shader"; +import { GFXBindingType } from "../binding-layout"; +import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; +import { GFXInputAttribute } from "../input-assembler"; export enum WebGLGPUObjectType { UNKNOWN, @@ -155,7 +155,7 @@ export class WebGLGPUUniformBlock { size: number = 0; glUniforms: WebGLGPUUniform[] = []; - isUniformPackage: boolean = false; // Is a single uniform package? + isUniformPackage: boolean = false; // Is a single uniform package? buffer: ArrayBuffer | null = null; // for cache bufferView: DataView | null = null; } diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts similarity index 86% rename from cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts rename to cocos/gfx/webgl/webgl-input-assembler.ts index 21c8382099..bda7373d77 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXInputAssembler, GFXInputAssemblerInfo } from '../gfx-input-assembler'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXDevice } from '../device'; +import { GFXInputAssembler, GFXInputAssemblerInfo } from '../input-assembler'; +import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUInputAssembler } from './webgl-gpu-objects'; export class WebGLGFXInputAssembler extends GFXInputAssembler { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts similarity index 80% rename from cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts rename to cocos/gfx/webgl/webgl-pipeline-layout.ts index 6f94a12493..e35e1090ce 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../gfx-pipeline-layout'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXDevice } from '../device'; +import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../pipeline-layout'; +import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUPipelineLayout } from './webgl-gpu-objects'; export class WebGLGFXPipelineLayout extends GFXPipelineLayout { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts similarity index 86% rename from cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts rename to cocos/gfx/webgl/webgl-pipeline-state.ts index 72f7118013..79d379121e 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-pipeline-state.ts +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXPipelineState, GFXPipelineStateInfo } from '../gfx-pipeline-state'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXDevice } from '../device'; +import { GFXPipelineState, GFXPipelineStateInfo } from '../pipeline-state'; +import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUPipelineState } from './webgl-gpu-objects'; export class WebGLGFXPipelineState extends GFXPipelineState { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts b/cocos/gfx/webgl/webgl-queue.ts similarity index 72% rename from cocos/renderer/gfx/webgl/webgl-gfx-queue.ts rename to cocos/gfx/webgl/webgl-queue.ts index 542eb4b375..3e7be907f4 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-queue.ts +++ b/cocos/gfx/webgl/webgl-queue.ts @@ -1,9 +1,9 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXQueueInfo, GFXQueue } from '../gfx-queue'; -import { GFXCommandBuffer } from '../gfx-command-buffer'; -import { WebGLGFXCommandBuffer } from './webgl-gfx-command-buffer'; +import { GFXDevice } from '../device'; +import { GFXQueueInfo, GFXQueue } from '../queue'; +import { GFXCommandBuffer } from '../command-buffer'; +import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; import { WebGLCmdFuncExecuteCmds } from './webgl-commands'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGFXDevice } from './webgl-device'; export class WebGLGFXQueue extends GFXQueue { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts similarity index 81% rename from cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts rename to cocos/gfx/webgl/webgl-render-pass.ts index 7276d3d523..46fe4be4c4 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -1,9 +1,9 @@ -import { GFXDevice } from '../gfx-device'; +import { GFXDevice } from '../device'; import { WebGLGPUTexture, WebGLGPURenderPass } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../gfx-texture'; -import { GFXFormatSurfaceSize } from '../gfx-define'; -import { GFXRenderPass, GFXRenderPassInfo } from '../gfx-render-pass'; +import { WebGLGFXDevice } from './webgl-device'; +import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../texture'; +import { GFXFormatSurfaceSize } from '../define'; +import { GFXRenderPass, GFXRenderPassInfo } from '../render-pass'; export class WebGLGFXRenderPass extends GFXRenderPass { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts similarity index 83% rename from cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts rename to cocos/gfx/webgl/webgl-sampler.ts index 9f98edded1..d4bb5d4484 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXSampler, GFXSamplerInfo } from '../gfx-sampler'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { GFXDevice } from '../device'; +import { GFXSampler, GFXSamplerInfo } from '../sampler'; +import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUSampler } from './webgl-gpu-objects'; export class WebGLGFXSampler extends GFXSampler { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts b/cocos/gfx/webgl/webgl-shader.ts similarity index 85% rename from cocos/renderer/gfx/webgl/webgl-gfx-shader.ts rename to cocos/gfx/webgl/webgl-shader.ts index 4d6a752c38..990b574022 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -1,6 +1,6 @@ -import { GFXDevice } from '../gfx-device'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { GFXShader, GFXShaderInfo } from '../gfx-shader'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; +import { GFXShader, GFXShaderInfo } from '../shader'; import { WebGLGPUShader } from './webgl-gpu-objects'; export class WebGLGFXShader extends GFXShader { diff --git a/cocos/renderer/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts similarity index 96% rename from cocos/renderer/gfx/webgl/webgl-state-cache.ts rename to cocos/gfx/webgl/webgl-state-cache.ts index 23f65a6f32..dde193308f 100644 --- a/cocos/renderer/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -1,5 +1,5 @@ -import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES } from "../gfx-define"; -import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../gfx-pipeline-state"; +import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES } from "../define"; +import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; export interface WebGLTexUnit { @@ -16,7 +16,7 @@ export interface WebGLTexUnit export class WebGLStateCache { glArrayBuffer : WebGLBuffer = 0; glElementArrayBuffer : WebGLBuffer = 0; - texUnit : number = 0; + texUnit : number = 0; glTex2DUnits : WebGLTexUnit[]; glTexCubeUnits : WebGLTexUnit[]; glFramebuffer : WebGLFramebuffer = 0; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts similarity index 87% rename from cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts rename to cocos/gfx/webgl/webgl-texture-view.ts index 1877a3593f..51debcfc44 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-texture-view.ts +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -1,7 +1,7 @@ -import { GFXDevice } from '../gfx-device'; -import { GFXTextureView, GFXTextureViewInfo } from '../gfx-texture-view'; +import { GFXDevice } from '../device'; +import { GFXTextureView, GFXTextureViewInfo } from '../texture-view'; import { WebGLGPUTextureView } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-gfx-device'; +import { WebGLGFXDevice } from './webgl-device'; export class WebGLGFXTextureView extends GFXTextureView { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts b/cocos/gfx/webgl/webgl-texture.ts similarity index 90% rename from cocos/renderer/gfx/webgl/webgl-gfx-texture.ts rename to cocos/gfx/webgl/webgl-texture.ts index 47d3b53bab..b2133a8c22 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -1,8 +1,8 @@ -import { GFXDevice } from '../gfx-device'; +import { GFXDevice } from '../device'; import { WebGLGPUTexture } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../gfx-texture'; -import { GFXFormatSurfaceSize } from '../gfx-define'; +import { WebGLGFXDevice } from './webgl-device'; +import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../texture'; +import { GFXFormatSurfaceSize } from '../define'; export class WebGLGFXTexture extends GFXTexture { diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-window.ts b/cocos/gfx/webgl/webgl-window.ts similarity index 92% rename from cocos/renderer/gfx/webgl/webgl-gfx-window.ts rename to cocos/gfx/webgl/webgl-window.ts index a1d837a028..e4d0349622 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -1,11 +1,11 @@ -import { GFXDevice } from '../gfx-device'; -import { WebGLGFXDevice } from './webgl-gfx-device'; -import { GFXWindow, GFXWindowInfo } from '../gfx-window'; -import { GFXFramebufferInfo } from '../gfx-framebuffer'; -import { GFXRenderPassInfo, GFXColorAttachment, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint, GFXDepthStencilAttachment } from '../gfx-render-pass'; -import { GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit } from '../gfx-texture'; -import { GFXTextureViewType } from '../gfx-texture-view'; -import { GFXFormat } from '../gfx-define'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; +import { GFXWindow, GFXWindowInfo } from '../window'; +import { GFXFramebufferInfo } from '../framebuffer'; +import { GFXRenderPassInfo, GFXColorAttachment, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint, GFXDepthStencilAttachment } from '../render-pass'; +import { GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit } from '../texture'; +import { GFXTextureViewType } from '../texture-view'; +import { GFXFormat } from '../define'; export class WebGLGFXWindow extends GFXWindow { diff --git a/cocos/renderer/gfx/gfx-window.ts b/cocos/gfx/window.ts similarity index 84% rename from cocos/renderer/gfx/gfx-window.ts rename to cocos/gfx/window.ts index d949f769ec..f4f60e6ee3 100644 --- a/cocos/renderer/gfx/gfx-window.ts +++ b/cocos/gfx/window.ts @@ -1,9 +1,9 @@ -import { GFXDevice } from './gfx-device'; -import { GFXFramebuffer } from './gfx-framebuffer'; -import { GFXTexture } from './gfx-texture'; -import { GFXTextureView } from './gfx-texture-view'; -import { GFXFormat } from './gfx-define'; -import { GFXRenderPass } from './gfx-render-pass'; +import { GFXDevice } from './device'; +import { GFXFramebuffer } from './framebuffer'; +import { GFXTexture } from './texture'; +import { GFXTextureView } from './texture-view'; +import { GFXFormat } from './define'; +import { GFXRenderPass } from './render-pass'; export interface GFXWindowInfo { title?: string; diff --git a/cocos/renderer/core/constants.js b/cocos/renderer/core/constants.js deleted file mode 100644 index 59e6ca8938..0000000000 --- a/cocos/renderer/core/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -let RenderQueue = { - OPAQUE: 0, - TRANSPARENT: 1, - OVERLAY: 2 -}; - -let PassStage = { - DEFAULT: 1, - FORWARD: 2, - SHADOWCAST: 4 -}; - -export { RenderQueue, PassStage }; diff --git a/cocos/renderer/core/constants.ts b/cocos/renderer/core/constants.ts new file mode 100644 index 0000000000..9001458f58 --- /dev/null +++ b/cocos/renderer/core/constants.ts @@ -0,0 +1,11 @@ +export enum RenderQueue { + OPAQUE = 0, + TRANSPARENT = 1, + OVERLAY = 2 +}; + +export enum PassStage { + DEFAULT = 1, + FORWARD = 2, + SHADOWCAST = 4 +}; diff --git a/cocos/renderer/core/pass.js b/cocos/renderer/core/pass.js deleted file mode 100644 index d1bd128b0b..0000000000 --- a/cocos/renderer/core/pass.js +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; -import { PassStage } from './constants'; - -export default class Pass { - constructor(name) { - this._programName = name; - this._stage = PassStage.DEFAULT; - - // cullmode - this._cullMode = gfx.CULL_BACK; - - // blending - this._blend = false; - this._blendEq = gfx.BLEND_FUNC_ADD; - this._blendAlphaEq = gfx.BLEND_FUNC_ADD; - this._blendSrc = gfx.BLEND_SRC_ALPHA; - this._blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA; - this._blendSrcAlpha = gfx.BLEND_ONE; - this._blendDstAlpha = gfx.BLEND_ZERO; - this._blendColor = 0xffffffff; - - // depth - this._depthTest = false; - this._depthWrite = false; - this._depthFunc = gfx.DS_FUNC_LESS, - - // stencil - this._stencilTest = false; - // front - this._stencilFuncFront = gfx.DS_FUNC_ALWAYS; - this._stencilRefFront = 0; - this._stencilMaskFront = 0xff; - this._stencilFailOpFront = gfx.STENCIL_OP_KEEP; - this._stencilZFailOpFront = gfx.STENCIL_OP_KEEP; - this._stencilZPassOpFront = gfx.STENCIL_OP_KEEP; - this._stencilWriteMaskFront = 0xff; - // back - this._stencilFuncBack = gfx.DS_FUNC_ALWAYS; - this._stencilRefBack = 0; - this._stencilMaskBack = 0xff; - this._stencilFailOpBack = gfx.STENCIL_OP_KEEP; - this._stencilZFailOpBack = gfx.STENCIL_OP_KEEP; - this._stencilZPassOpBack = gfx.STENCIL_OP_KEEP; - this._stencilWriteMaskBack = 0xff; - } - - setStage(stage = PassStage.DEFAULT) { - this._stage = stage; - } - - setCullMode(cullMode = gfx.CULL_BACK) { - this._cullMode = cullMode; - } - - setBlend( - enabled = false, - blendEq = gfx.BLEND_FUNC_ADD, - blendSrc = gfx.BLEND_SRC_ALPHA, - blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA, - blendAlphaEq = gfx.BLEND_FUNC_ADD, - blendSrcAlpha = gfx.BLEND_SRC_ALPHA, - blendDstAlpha = gfx.BLEND_ONE_MINUS_SRC_ALPHA, - blendColor = 0xffffffff - ) { - this._blend = enabled; - this._blendEq = blendEq; - this._blendSrc = blendSrc; - this._blendDst = blendDst; - this._blendAlphaEq = blendAlphaEq; - this._blendSrcAlpha = blendSrcAlpha; - this._blendDstAlpha = blendDstAlpha; - this._blendColor = blendColor; - } - - setDepth( - depthTest = false, - depthWrite = false, - depthFunc = gfx.DS_FUNC_LESS - ) { - this._depthTest = depthTest; - this._depthWrite = depthWrite; - this._depthFunc = depthFunc; - } - - setStencilFront( - enabled = false, - stencilFunc = gfx.DS_FUNC_ALWAYS, - stencilRef = 0, - stencilMask = 0xff, - stencilFailOp = gfx.STENCIL_OP_KEEP, - stencilZFailOp = gfx.STENCIL_OP_KEEP, - stencilZPassOp = gfx.STENCIL_OP_KEEP, - stencilWriteMask = 0xff - ) { - this._stencilTest = enabled; - this._stencilFuncFront = stencilFunc; - this._stencilRefFront = stencilRef; - this._stencilMaskFront = stencilMask; - this._stencilFailOpFront = stencilFailOp; - this._stencilZFailOpFront = stencilZFailOp; - this._stencilZPassOpFront = stencilZPassOp; - this._stencilWriteMaskFront = stencilWriteMask; - } - - setStencilBack( - enabled = false, - stencilFunc = gfx.DS_FUNC_ALWAYS, - stencilRef = 0, - stencilMask = 0xff, - stencilFailOp = gfx.STENCIL_OP_KEEP, - stencilZFailOp = gfx.STENCIL_OP_KEEP, - stencilZPassOp = gfx.STENCIL_OP_KEEP, - stencilWriteMask = 0xff - ) { - this._stencilTest = enabled; - this._stencilFuncBack = stencilFunc; - this._stencilRefBack = stencilRef; - this._stencilMaskBack = stencilMask; - this._stencilFailOpBack = stencilFailOp; - this._stencilZFailOpBack = stencilZFailOp; - this._stencilZPassOpBack = stencilZPassOp; - this._stencilWriteMaskBack = stencilWriteMask; - } -} diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts new file mode 100644 index 0000000000..833363baea --- /dev/null +++ b/cocos/renderer/core/pass.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { PassStage } from './constants'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXSampler } from '../../gfx/sampler'; +import { GFXDevice } from '../../gfx/device'; +import { GFXDepthStencilAttachment, GFXColorAttachment } from '../../gfx/render-pass'; +import { GFXPipelineState, GFXPrimitiveMode, GFXRasterizerState, GFXDepthStencilState, GFXBlendState, GFXInputState } from '../../gfx/pipeline-state'; +import { GFXBindingLayoutInfo } from '../../gfx/binding-layout'; + +interface PassInfo { + programName?: string; + primitive?: GFXPrimitiveMode; + stage?: PassStage; + inputState?: GFXInputState; + rasterizerState?: GFXRasterizerState; + depthStencilState?: GFXDepthStencilState; + blendState?: GFXBlendState; + bindingLayoutInfo?: GFXBindingLayoutInfo; +} + +export default class Pass { + static create(info: PassInfo) { + let pass = new Pass(); + let device = pass._device = cc.game._renderContext; + pass._programName = info.programName || ''; + pass._stage = info.stage || PassStage.DEFAULT; + // pipeline state + pass._pipelineState = device.createPipelineState({ + primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, + shader: null, + is: Object.assign(new GFXInputState, info.inputState), + rs: Object.assign(new GFXRasterizerState, info.rasterizerState), + dss: Object.assign(new GFXDepthStencilState, info.depthStencilState), + bs: Object.assign(new GFXBlendState, info.blendState), + layout: device.createPipelineLayout({ + layouts: [device.createBindingLayout(info.bindingLayoutInfo || { bindings: [] })] + }), + renderPass: device.createRenderPass({ + colorAttachments: [new GFXColorAttachment], + depthStencilAttachment: new GFXDepthStencilAttachment + }) + }); + } + + protected _device: GFXDevice | null = null; + protected _programName: string = ''; + protected _stage: PassStage = PassStage.DEFAULT; + protected _pipelineState: GFXPipelineState | null = null; + protected _buffers: GFXBuffer[] = []; + protected _samplers: GFXSampler[] = []; +} diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js index 56f53282fc..7687de6774 100644 --- a/cocos/renderer/gfx/index.js +++ b/cocos/renderer/gfx/index.js @@ -16,21 +16,6 @@ import RenderBuffer from './render-buffer'; import FrameBuffer from './frame-buffer'; import Device from './device'; -import { GFXDevice } from './gfx-device'; -import { GFXBuffer } from './gfx-buffer'; -import { GFXTexture } from './gfx-texture'; -import { GFXTextureView } from './gfx-texture-view'; -import { GFXSampler } from './gfx-sampler'; -import { GFXShader } from './gfx-shader'; -import { GFXInputAssembler } from './gfx-input-assembler'; -import { GFXRenderPass } from './gfx-render-pass'; -import { GFXFramebuffer } from './gfx-framebuffer'; -import { GFXPipelineLayout } from './gfx-pipeline-layout'; -import { GFXPipelineState } from './gfx-pipeline-state'; -import { GFXCommandBuffer } from './gfx-command-buffer'; -import { GFXQueue } from './gfx-queue'; -import { WebGLGFXDevice } from './webgl/webgl-gfx-device'; - let gfx = { // classes VertexFormat, @@ -53,18 +38,3 @@ Object.assign(gfx, enums); export default gfx; cc.gfx = gfx; - -cc.GFXDevice = GFXDevice; -cc.GFXBuffer = GFXBuffer; -cc.GFXTexture = GFXTexture; -cc.GFXTextureView = GFXTextureView; -cc.GFXSampler = GFXSampler; -cc.GFXShader = GFXShader; -cc.GFXInputAssembler = GFXInputAssembler; -cc.GFXRenderPass = GFXRenderPass; -cc.GFXFramebuffer = GFXFramebuffer; -cc.GFXPipelineLayout = GFXPipelineLayout; -cc.GFXPipelineState = GFXPipelineState; -cc.GFXCommandBuffer = GFXCommandBuffer; -cc.GFXQueue = GFXQueue; -cc.WebGLGFXDevice = WebGLGFXDevice; diff --git a/index.js b/index.js index 6ad1ab6eb3..2543c70a40 100644 --- a/index.js +++ b/index.js @@ -32,6 +32,7 @@ import cc from './predefine'; import './cocos/core'; import './cocos/scene-graph'; import './cocos/renderer'; +import './cocos/gfx'; import './cocos/assets'; import './cocos/load-pipeline'; From ee936231cf332f9ede95cda0b12d6f9b98b86347 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Sat, 29 Dec 2018 18:37:24 +0800 Subject: [PATCH 013/267] update pipeline code --- cocos/core/root.ts | 19 +++++++++++++- cocos/renderer/gfx/gfx-device.ts | 6 ++++- cocos/renderer/gfx/webgl/webgl-gfx-device.ts | 8 +++--- .../renderer/pipeline/forward/forward-flow.ts | 16 ++++++++++++ .../pipeline/forward/forward-pipeline.ts | 5 ++++ cocos/renderer/pipeline/render-flow.ts | 7 ++++++ cocos/renderer/pipeline/render-pipeline.ts | 25 +++++++++++++------ 7 files changed, 73 insertions(+), 13 deletions(-) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 8118d6dee7..7841551e9c 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -6,6 +6,7 @@ import { RenderPipeline } from "../renderer/pipeline/render-pipeline"; import { ForwardPipeline } from "../renderer/pipeline/forward/forward-pipeline"; export interface RootInfo { + device: GFXDevice; }; export class Root { @@ -15,7 +16,14 @@ export class Root { public initialize(info: RootInfo): boolean { - let pipeline = new ForwardPipeline; + if(!info.device) { + console.error("RootInfo.device is null."); + return false; + } + this._device = info.device; + this._mainWindow = this._device.mainWindow; + + let pipeline = new ForwardPipeline(this); if (!pipeline.initialize()) { return false; } @@ -125,6 +133,14 @@ export class Root { this._views = []; } + public get device(): GFXDevice | null { + return this._device; + } + + public get mainWindow(): GFXWindow | null { + return this._mainWindow; + } + public get pipeline(): RenderPipeline | null { return this._pipeline; } @@ -138,6 +154,7 @@ export class Root { } private _device: GFXDevice | null = null; + private _mainWindow: GFXWindow | null = null; private _windows: GFXWindow[] = []; private _pipeline: RenderPipeline | null = null; private _scenes: Scene[] = []; diff --git a/cocos/renderer/gfx/gfx-device.ts b/cocos/renderer/gfx/gfx-device.ts index 81aeccc495..8e2874368a 100644 --- a/cocos/renderer/gfx/gfx-device.ts +++ b/cocos/renderer/gfx/gfx-device.ts @@ -48,13 +48,17 @@ export abstract class GFXDevice { return this._queue; } + public get mainWindow(): GFXWindow | null { + return this._mainWindow; + } + public get maxVertexAttributes(): number { return this._maxVertexAttributes; } protected _deviceName : string = ""; protected _queue : GFXQueue | null = null; - protected _curWindow : GFXWindow | null = null; + protected _mainWindow : GFXWindow | null = null; protected _maxVertexAttributes : number = 0; }; diff --git a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts index a2ea99b647..93a6fb155b 100644 --- a/cocos/renderer/gfx/webgl/webgl-gfx-device.ts +++ b/cocos/renderer/gfx/webgl/webgl-gfx-device.ts @@ -149,7 +149,7 @@ export class WebGLGFXDevice extends GFXDevice { this._ANGLE_instanced_arrays = this._webGLRC.getExtension("ANGLE_instanced_arrays"); // create primary window - this._curWindow = this.createWindow({ + this._mainWindow = this.createWindow({ title: this._webGLRC.canvas.title, left: this._webGLRC.canvas.offsetLeft, top: this._webGLRC.canvas.offsetTop, @@ -162,9 +162,9 @@ export class WebGLGFXDevice extends GFXDevice { public destroy(): void { - if (this._curWindow) { - this._curWindow.destroy(); - this._curWindow = null; + if (this._mainWindow) { + this._mainWindow.destroy(); + this._mainWindow = null; } this._webGLRC = null; diff --git a/cocos/renderer/pipeline/forward/forward-flow.ts b/cocos/renderer/pipeline/forward/forward-flow.ts index 643cc8c202..24db73d32c 100644 --- a/cocos/renderer/pipeline/forward/forward-flow.ts +++ b/cocos/renderer/pipeline/forward/forward-flow.ts @@ -1,7 +1,13 @@ import { RenderFlow, RenderFlowInfo } from "../render-flow"; +import { GFXRenderPass } from "../../gfx/gfx-render-pass"; +import { RenderPipeline } from "../render-pipeline"; export class ForwardFlow extends RenderFlow { + constructor(pipeline: RenderPipeline) { + super(pipeline); + } + public initialize(info: RenderFlowInfo): boolean { if(info.name) { @@ -9,6 +15,14 @@ export class ForwardFlow extends RenderFlow { } this._priority = info.priority; + + let device = this._pipeline.root.device; + if(!device) { + return false; + } + + //this._pipeline.root.mainWindow; + //this._renderPass = return true; } @@ -16,4 +30,6 @@ export class ForwardFlow extends RenderFlow { public destroy(): void { this.destroyStages(); } + + private _renderPass: GFXRenderPass | null = null; }; diff --git a/cocos/renderer/pipeline/forward/forward-pipeline.ts b/cocos/renderer/pipeline/forward/forward-pipeline.ts index cd541a99df..a0f88066d9 100644 --- a/cocos/renderer/pipeline/forward/forward-pipeline.ts +++ b/cocos/renderer/pipeline/forward/forward-pipeline.ts @@ -1,7 +1,12 @@ import { RenderPipeline } from "../render-pipeline"; +import { Root } from "../../../core/root"; export class ForwardPipeline extends RenderPipeline { + constructor(root: Root) { + super(root); + } + public initialize(): boolean { return true; diff --git a/cocos/renderer/pipeline/render-flow.ts b/cocos/renderer/pipeline/render-flow.ts index 3bc363c87d..2e83e6062d 100644 --- a/cocos/renderer/pipeline/render-flow.ts +++ b/cocos/renderer/pipeline/render-flow.ts @@ -1,5 +1,6 @@ import { RenderStage, RenderStageInfo } from "./render-stage"; import { RenderView } from "./render-view"; +import { RenderPipeline } from "./render-pipeline"; export interface RenderFlowInfo { name?: string; @@ -8,6 +9,10 @@ export interface RenderFlowInfo { export abstract class RenderFlow { + constructor(pipeline: RenderPipeline) { + this._pipeline = pipeline; + } + public abstract initialize(info: RenderFlowInfo): boolean; public abstract destroy(); @@ -46,7 +51,9 @@ export abstract class RenderFlow { return this._priority; } + protected _pipeline: RenderPipeline; protected _name: string = ""; protected _priority: number = 0; protected _stages: RenderStage[] = []; + protected _material: null = null; // TODO }; diff --git a/cocos/renderer/pipeline/render-pipeline.ts b/cocos/renderer/pipeline/render-pipeline.ts index 3de6d466ed..3915757ddb 100644 --- a/cocos/renderer/pipeline/render-pipeline.ts +++ b/cocos/renderer/pipeline/render-pipeline.ts @@ -1,29 +1,35 @@ import { RenderView } from "./render-view"; import { RenderFlow, RenderFlowInfo } from "./render-flow"; +import { GFXDevice } from "../gfx/gfx-device"; +import { Root } from "../../core/root"; export abstract class RenderPipeline { + constructor(root: Root) { + this._root = root; + } + public abstract initialize(): boolean; public abstract destroy(); public render(view: RenderView) { - for(let i = 0; i < this._flows.length; ++i) { + for (let i = 0; i < this._flows.length; ++i) { this._flows[i].render(view); } } - + public resize(width, height) { - + } - public createFlow(clazz: new(pipeline: RenderPipeline) => T, info : RenderFlowInfo): RenderFlow | null { + public createFlow(clazz: new (pipeline: RenderPipeline) => T, info: RenderFlowInfo): RenderFlow | null { let flow: RenderFlow = new clazz(this); - if(flow.initialize(info)) { + if (flow.initialize(info)) { this._flows.push(flow); this._flows.sort((a: RenderFlow, b: RenderFlow) => { return a.priority - b.priority; }); - + return flow; } else { return null; @@ -31,15 +37,20 @@ export abstract class RenderPipeline { } public destroyFlows() { - for(let i = 0; i < this._flows.length; ++i) { + for (let i = 0; i < this._flows.length; ++i) { this._flows[i].destroy(); } this._flows = []; } + public get root(): Root { + return this._root; + } + public get flows(): RenderFlow[] { return this._flows; } + protected _root: Root; protected _flows: RenderFlow[] = []; }; From 5744fff652404bb941271dbad9ff5bad5eb5c41f Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Sat, 29 Dec 2018 18:53:08 +0800 Subject: [PATCH 014/267] move cocos/renderer/pipeline to cocos/pipeline --- cocos/core/root.ts | 8 ++--- cocos/pipeline/forward/forward-flow.ts | 35 +++++++++++++++++++ cocos/pipeline/forward/forward-pipeline.ts | 18 ++++++++++ .../pipeline/forward/forward-stage.ts | 0 cocos/{renderer => }/pipeline/render-flow.ts | 0 .../pipeline/render-pipeline.ts | 0 cocos/{renderer => }/pipeline/render-stage.ts | 4 +-- cocos/{renderer => }/pipeline/render-view.ts | 0 .../renderer/pipeline/forward/forward-flow.ts | 6 ++-- .../pipeline/forward/forward-pipeline.ts | 2 +- 10 files changed, 63 insertions(+), 10 deletions(-) create mode 100644 cocos/pipeline/forward/forward-flow.ts create mode 100644 cocos/pipeline/forward/forward-pipeline.ts rename cocos/{renderer => }/pipeline/forward/forward-stage.ts (100%) rename cocos/{renderer => }/pipeline/render-flow.ts (100%) rename cocos/{renderer => }/pipeline/render-pipeline.ts (100%) rename cocos/{renderer => }/pipeline/render-stage.ts (83%) rename cocos/{renderer => }/pipeline/render-view.ts (100%) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 7841551e9c..e4705a6c28 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,9 +1,9 @@ import { Scene } from "../renderer/scene/scene"; -import { RenderView, RenderViewInfo } from "../renderer/pipeline/render-view"; -import { GFXDevice } from "../renderer/gfx/gfx-device"; -import { GFXWindow, GFXWindowInfo } from "../renderer/gfx/gfx-window"; -import { RenderPipeline } from "../renderer/pipeline/render-pipeline"; import { ForwardPipeline } from "../renderer/pipeline/forward/forward-pipeline"; +import { GFXWindowInfo, GFXWindow } from "../gfx/window"; +import { GFXDevice } from "../gfx/device"; +import { RenderView, RenderViewInfo } from "../pipeline/render-view"; +import { RenderPipeline } from "../pipeline/render-pipeline"; export interface RootInfo { device: GFXDevice; diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts new file mode 100644 index 0000000000..24db73d32c --- /dev/null +++ b/cocos/pipeline/forward/forward-flow.ts @@ -0,0 +1,35 @@ +import { RenderFlow, RenderFlowInfo } from "../render-flow"; +import { GFXRenderPass } from "../../gfx/gfx-render-pass"; +import { RenderPipeline } from "../render-pipeline"; + +export class ForwardFlow extends RenderFlow { + + constructor(pipeline: RenderPipeline) { + super(pipeline); + } + + public initialize(info: RenderFlowInfo): boolean { + + if(info.name) { + this._name = info.name; + } + + this._priority = info.priority; + + let device = this._pipeline.root.device; + if(!device) { + return false; + } + + //this._pipeline.root.mainWindow; + //this._renderPass = + + return true; + } + + public destroy(): void { + this.destroyStages(); + } + + private _renderPass: GFXRenderPass | null = null; +}; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts new file mode 100644 index 0000000000..a0f88066d9 --- /dev/null +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -0,0 +1,18 @@ +import { RenderPipeline } from "../render-pipeline"; +import { Root } from "../../../core/root"; + +export class ForwardPipeline extends RenderPipeline { + + constructor(root: Root) { + super(root); + } + + public initialize(): boolean { + + return true; + } + + public destroy(): void { + this.destroyFlows(); + } +}; diff --git a/cocos/renderer/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts similarity index 100% rename from cocos/renderer/pipeline/forward/forward-stage.ts rename to cocos/pipeline/forward/forward-stage.ts diff --git a/cocos/renderer/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts similarity index 100% rename from cocos/renderer/pipeline/render-flow.ts rename to cocos/pipeline/render-flow.ts diff --git a/cocos/renderer/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts similarity index 100% rename from cocos/renderer/pipeline/render-pipeline.ts rename to cocos/pipeline/render-pipeline.ts diff --git a/cocos/renderer/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts similarity index 83% rename from cocos/renderer/pipeline/render-stage.ts rename to cocos/pipeline/render-stage.ts index 231cd95866..10e907787d 100644 --- a/cocos/renderer/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -1,6 +1,6 @@ -import { GFXRenderPass } from "../gfx/gfx-render-pass"; -import { GFXFramebuffer } from "../gfx/gfx-framebuffer"; import { RenderView } from "./render-view"; +import { GFXRenderPass } from "../../gfx/render-pass"; +import { GFXFramebuffer } from "../../gfx/framebuffer"; export interface RenderStageInfo { name?: string; diff --git a/cocos/renderer/pipeline/render-view.ts b/cocos/pipeline/render-view.ts similarity index 100% rename from cocos/renderer/pipeline/render-view.ts rename to cocos/pipeline/render-view.ts diff --git a/cocos/renderer/pipeline/forward/forward-flow.ts b/cocos/renderer/pipeline/forward/forward-flow.ts index 24db73d32c..fcc8cb7dfb 100644 --- a/cocos/renderer/pipeline/forward/forward-flow.ts +++ b/cocos/renderer/pipeline/forward/forward-flow.ts @@ -1,6 +1,6 @@ -import { RenderFlow, RenderFlowInfo } from "../render-flow"; -import { GFXRenderPass } from "../../gfx/gfx-render-pass"; -import { RenderPipeline } from "../render-pipeline"; +import { RenderPipeline } from "../../../pipeline/render-pipeline"; +import { RenderFlow, RenderFlowInfo } from "../../../pipeline/render-flow"; +import { GFXRenderPass } from "../../../gfx/render-pass"; export class ForwardFlow extends RenderFlow { diff --git a/cocos/renderer/pipeline/forward/forward-pipeline.ts b/cocos/renderer/pipeline/forward/forward-pipeline.ts index a0f88066d9..0bcf0e3b88 100644 --- a/cocos/renderer/pipeline/forward/forward-pipeline.ts +++ b/cocos/renderer/pipeline/forward/forward-pipeline.ts @@ -1,5 +1,5 @@ -import { RenderPipeline } from "../render-pipeline"; import { Root } from "../../../core/root"; +import { RenderPipeline } from "../../../pipeline/render-pipeline"; export class ForwardPipeline extends RenderPipeline { From d9a9add5f5feae9a9a656c7bac8f2df92b68aaa0 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 02:41:52 +0800 Subject: [PATCH 015/267] fix crashes --- cocos/core/CCDirector.js | 20 +- cocos/core/CCGame.js | 27 +- cocos/core/root.ts | 20 +- cocos/gfx/binding-layout.ts | 20 +- cocos/gfx/buffer.ts | 34 +- cocos/gfx/command-buffer.ts | 34 +- cocos/gfx/define.ts | 407 ---------- cocos/gfx/device.ts | 8 +- cocos/gfx/framebuffer.ts | 13 + cocos/gfx/gfx-define.ts | 710 ++++++++++++++++++ cocos/gfx/input-assembler.ts | 9 +- cocos/gfx/pipeline-layout.ts | 10 +- cocos/gfx/pipeline-state.ts | 92 +-- cocos/gfx/queue.ts | 9 +- cocos/gfx/render-pass.ts | 60 +- cocos/gfx/sampler.ts | 39 +- cocos/gfx/shader.ts | 27 +- cocos/gfx/texture-view.ts | 11 +- cocos/gfx/texture.ts | 31 +- cocos/gfx/webgl/webgl-buffer.ts | 12 +- cocos/gfx/webgl/webgl-command-buffer.ts | 13 +- cocos/gfx/webgl/webgl-commands.ts | 206 ++--- cocos/gfx/webgl/webgl-device.ts | 60 +- cocos/gfx/webgl/webgl-framebuffer.ts | 2 + cocos/gfx/webgl/webgl-gpu-objects.ts | 11 +- cocos/gfx/webgl/webgl-pipeline-layout.ts | 3 +- cocos/gfx/webgl/webgl-queue.ts | 2 +- cocos/gfx/webgl/webgl-render-pass.ts | 13 +- cocos/gfx/webgl/webgl-sampler.ts | 57 +- cocos/gfx/webgl/webgl-shader.ts | 5 +- cocos/gfx/webgl/webgl-state-cache.ts | 8 +- cocos/gfx/webgl/webgl-texture.ts | 4 +- cocos/gfx/webgl/webgl-window.ts | 6 +- cocos/gfx/window.ts | 2 +- cocos/pipeline/forward/forward-flow.ts | 33 +- cocos/pipeline/forward/forward-pipeline.ts | 37 +- cocos/pipeline/forward/forward-stage.ts | 39 +- cocos/pipeline/forward/test-stage.ts | 156 ++++ cocos/pipeline/render-flow.ts | 12 + cocos/pipeline/render-pipeline.ts | 135 +++- cocos/pipeline/render-stage.ts | 70 +- cocos/pipeline/render-view.ts | 6 +- cocos/renderer/core/pass.ts | 3 +- .../renderer/pipeline/forward/forward-flow.ts | 35 - .../pipeline/forward/forward-pipeline.ts | 18 - 45 files changed, 1550 insertions(+), 979 deletions(-) delete mode 100644 cocos/gfx/define.ts create mode 100644 cocos/gfx/gfx-define.ts create mode 100644 cocos/pipeline/forward/test-stage.ts delete mode 100644 cocos/renderer/pipeline/forward/forward-flow.ts delete mode 100644 cocos/renderer/pipeline/forward/forward-pipeline.ts diff --git a/cocos/core/CCDirector.js b/cocos/core/CCDirector.js index 9fd24790a6..8f2b92ceb1 100644 --- a/cocos/core/CCDirector.js +++ b/cocos/core/CCDirector.js @@ -38,6 +38,7 @@ import NodeActivator from '../scene-graph/node-activator'; import RenderSystem from '../3d/framework/render-system'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; +import { Root } from './root'; // const ComponentScheduler = require('./component-scheduler'); // const NodeActivator = require('./node-activator'); @@ -122,6 +123,9 @@ class Director extends EventTarget { // purge? this._purgeDirectorInNextLoop = false; + // root + this._root = null; + // scenes this._loadingScene = ''; this._scene = null; @@ -156,6 +160,13 @@ class Director extends EventTarget { } init () { + + this._root = new Root(game._gfxDevice); + let rootInfo = {}; + if(!this._root.initialize(rootInfo)) { + return false; + } + this._totalFrames = 0; this._lastUpdate = performance.now(); this._paused = false; @@ -349,6 +360,9 @@ class Director extends EventTarget { this.stopAnimation(); + this._root.destroy(); + this._root = null; + // Clear all caches cc.loader.releaseAll(); } @@ -902,7 +916,11 @@ class Director extends EventTarget { // Render this._physicsSystem.update(this._deltaTime); this.emit(cc.Director.EVENT_BEFORE_DRAW); - this._renderSystem.update(this._deltaTime); + //this._renderSystem.update(this._deltaTime); + + + this._root.frameMove(this._deltaTime); + // After draw this.emit(cc.Director.EVENT_AFTER_DRAW); diff --git a/cocos/core/CCGame.js b/cocos/core/CCGame.js index c8a7bc56a7..b45b6bf6da 100644 --- a/cocos/core/CCGame.js +++ b/cocos/core/CCGame.js @@ -30,7 +30,7 @@ import debug from './platform/CCDebug'; import { addon } from './utils/js'; import renderer from '../renderer'; -import gfx from '../renderer/gfx'; +import '../gfx'; import builtinResMgr from '../3d/builtin/init'; /** @@ -343,6 +343,12 @@ var game = { * @method end */ end: function () { + + if(this._gfxDevice) { + this._gfxDevice.destroy(); + this._gfxDevice = null; + } + close(); }, @@ -366,7 +372,7 @@ var game = { // Init engine this._initEngine(); - this._initBuiltins(); + //this._initBuiltins(); // Log engine version console.log('Cocos3D v' + cc.ENGINE_VERSION); @@ -768,26 +774,29 @@ var game = { { // todo, adjust opts here - let device = this._renderContext = new gfx.Device(localCanvas, {}); - - /* - this._gfxDevice = new WebGLGFXDevice; + this._gfxDevice = new cc.WebGLGFXDevice; this._gfxDevice.initialize({ canvasElm : localCanvas, }); - */ + //let device = this._renderContext = new gfx.Device(localCanvas, {}); + + /* renderer.addStage('opaque'); renderer.addStage('transparent'); renderer.addStage('ui'); renderer.addStage('shadowcast'); + */ - this._renderer = new renderer.ForwardRenderer(device); + //this._renderer = new renderer.ForwardRenderer(device); } // renderer.initWebGL(localCanvas, opts); // this._renderContext = renderer.device._gl; } - if (!this._renderContext) { + + if (!this._gfxDevice) { + //if (!this._renderContext) { + // todo fix here for wechat game console.error('can not support canvas rendering in 3D'); this._renderer = null; diff --git a/cocos/core/root.ts b/cocos/core/root.ts index e4705a6c28..2ca0b18756 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,26 +1,20 @@ -import { Scene } from "../renderer/scene/scene"; -import { ForwardPipeline } from "../renderer/pipeline/forward/forward-pipeline"; -import { GFXWindowInfo, GFXWindow } from "../gfx/window"; +import Scene from "../renderer/scene/scene"; +import { GFXWindow, GFXWindowInfo } from "../gfx/window"; import { GFXDevice } from "../gfx/device"; import { RenderView, RenderViewInfo } from "../pipeline/render-view"; import { RenderPipeline } from "../pipeline/render-pipeline"; +import { ForwardPipeline } from "../pipeline/forward/forward-pipeline"; export interface RootInfo { - device: GFXDevice; }; export class Root { - constructor() { + constructor(device: GFXDevice) { + this._device = device; } public initialize(info: RootInfo): boolean { - - if(!info.device) { - console.error("RootInfo.device is null."); - return false; - } - this._device = info.device; this._mainWindow = this._device.mainWindow; let pipeline = new ForwardPipeline(this); @@ -133,7 +127,7 @@ export class Root { this._views = []; } - public get device(): GFXDevice | null { + public get device(): GFXDevice { return this._device; } @@ -153,7 +147,7 @@ export class Root { return this._views; } - private _device: GFXDevice | null = null; + private _device: GFXDevice; private _mainWindow: GFXWindow | null = null; private _windows: GFXWindow[] = []; private _pipeline: RenderPipeline | null = null; diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index 9ff0a7e3e1..59f535981a 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -2,22 +2,16 @@ import { GFXDevice } from './device'; import { GFXBuffer } from './buffer'; import { GFXTextureView } from './texture-view'; import { GFXSampler } from './sampler'; +import { GFXBindingType } from './gfx-define'; -export enum GFXBindingType { - UNKNOWN, - UNIFORM_BUFFER, - SAMPLER, - STORAGE_BUFFER, +export interface GFXBinding { + binding : number; + type : GFXBindingType; + name : string; }; -export class GFXBinding { - binding : number = 0; - type : GFXBindingType = GFXBindingType.UNKNOWN; - name : string = ""; -}; - -export class GFXBindingLayoutInfo { - bindings : GFXBinding[] = []; +export interface GFXBindingLayoutInfo { + bindings : GFXBinding[]; }; export class GFXBindingUnit { diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index e7335869c0..54b2c7da0b 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -1,33 +1,5 @@ import { GFXDevice } from './device'; -import { BufferView } from './define'; - -export enum GFXBufferUsageBit { - NONE = 0, - TRANSFER_SRC = 0x1, - TRANSFER_DST = 0x2, - INDEX = 0x4, - VERTEX = 0x8, - UNIFORM = 0x10, - STORAGE = 0x20, -}; - -export type GFXBufferUsage = GFXBufferUsageBit; - -export enum GFXMemoryUsageBit { - NONE = 0, - DEVICE = 0x1, - HOST = 0x2, -}; - -export type GFXMemoryUsage = GFXMemoryUsageBit; - -export enum GFXBufferAccessBit { - NONE = 0, - READ = 0x1, - WRITE = 0x2, -}; - -export type GFXBufferAccess = GFXBufferAccessBit; +import { GFXBufferUsage, GFXMemoryUsage, GFXBufferUsageBit, GFXMemoryUsageBit } from './gfx-define'; export interface GFXBufferInfo { usage: GFXBufferUsage; @@ -44,7 +16,7 @@ export abstract class GFXBuffer { public abstract initialize(info: GFXBufferInfo): boolean; public abstract destroy(): void; - public abstract update(buffer: Buffer, offset: number); + public abstract update(buffer: ArrayBuffer, offset?: number); public get usage(): GFXBufferUsage { return this._usage; @@ -72,5 +44,5 @@ export abstract class GFXBuffer { protected _size: number = 0; protected _stride: number = 1; protected _buffer: ArrayBuffer | null = null; - protected _bufferView: BufferView | null = null; + protected _bufferView: Uint8Array | null = null; }; diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index 154a8d2ba6..4b2eb5b6b9 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -4,39 +4,9 @@ import { GFXBuffer } from './buffer'; import { GFXInputAssembler } from './input-assembler'; import { GFXPipelineState } from './pipeline-state'; import { GFXBindingLayout } from './binding-layout'; -import { GFXTextureLayout } from './render-pass'; import { GFXTexture } from './texture'; import { GFXFramebuffer } from './framebuffer'; - -export class GFXTextureSubres -{ - baseMipLevel: number = 0; - levelCount: number = 1; - baseArrayLayer: number = 0; - layerCount: number = 1; -}; - -export class GFXTextureCopy { - srcSubres: GFXTextureSubres = new GFXTextureSubres; - srcOffset: number[] = [0, 0, 0]; - dstSubres: GFXTextureSubres = new GFXTextureSubres; - dstOffset: number[] = [0, 0, 0]; - extent: number[] = [0, 0, 0]; -}; - -export class GFXBufferTextureCopy { - buffOffset: number = 0; - buffStride: number = 0; - buffTexHeight: number = 0; - texOffset: number[] = [0, 0, 0]; - texExtent: number[] = [0, 0, 0]; - texSubres: GFXTextureSubres = new GFXTextureSubres; -}; - -export enum GFXCommandBufferType { - PRIMARY, - SECONDARY, -}; +import { GFXColor, GFXRect, GFXCommandBufferType, GFXBufferTextureCopy, GFXTextureLayout } from './gfx-define'; export interface GFXCommandBufferInfo { allocator : GFXCommandAllocator; @@ -54,7 +24,7 @@ export abstract class GFXCommandBuffer { public abstract begin(); public abstract end(); - public abstract beginRenderPass(framebuffer : GFXFramebuffer, viewport : number[], numClearColors : number, clearColors : number[], clearStencil : number); + public abstract beginRenderPass(framebuffer : GFXFramebuffer, renderArea : GFXRect, clearColors : GFXColor[], clearDepth: number, clearStencil : number); public abstract endRenderPass(); public abstract bindPipelineState(pipelineState : GFXPipelineState); public abstract bindBindingLayout(bindingLayout : GFXBindingLayout); diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts deleted file mode 100644 index e41a1fb44f..0000000000 --- a/cocos/gfx/define.ts +++ /dev/null @@ -1,407 +0,0 @@ -// Extensions -export enum WebGLEXT { - COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, - COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1, - COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2, - COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3, - - COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C, - COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D, - COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E, - COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F, - - COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00, - COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01, - COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02, - COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03, - - COMPRESSED_RGB_ETC1_WEBGL = 0x8D64, -}; - -export const GFX_MAX_VERTEX_ATTRIBUTES : number = 8; -export const GFX_MAX_TEXTURE_UNITS : number = 16; -export const GFX_MAX_ATTACHMENTS : number = 4; - -export enum GFXType { - UNKNOWN, - BOOL, - BOOL2, - BOOL3, - BOOL4, - INT, - INT2, - INT3, - INT4, - UINT, - UINT2, - UINT3, - UINT4, - FLOAT, - FLOAT2, - FLOAT3, - FLOAT4, - MAT2, - MAT2X3, - MAT2X4, - MAT3X2, - MAT3, - MAT3X4, - MAT4X2, - MAT4X3, - MAT4, - SAMPLER1D, - SAMPLER1D_ARRAY, - SAMPLER2D, - SAMPLER2D_ARRAY, - SAMPLER3D, - SAMPLER_CUBE, - COUNT, -}; - -export enum GFXFormat { - - UNKNOWN, - - A8, - L8, - LA8, - - R8, - R8SN, - R8UI, - R8I, - R16F, - R16UI, - R16I, - R32F, - R32UI, - R32I, - - RG8, - RG8SN, - RG8UI, - RG8I, - RG16F, - RG16UI, - RG16I, - RG32F, - RG32UI, - RG32I, - - RGB8, - SRGB8, - RGB8SN, - RGB8UI, - RGB8I, - RGB16F, - RGB16UI, - RGB16I, - RGB32F, - RGB32UI, - RGB32I, - - RGBA8, - SRGB8_A8, - RGBA8SN, - RGBA8UI, - RGBA8I, - RGBA16F, - RGBA16UI, - RGBA16I, - RGBA32F, - RGBA32UI, - RGBA32I, - - // Special Format - R5G6B5, - R11G11B10F, - RGB5A1, - RGBA4, - RGB10A2, - RGB10A2UI, - RGB9E5, - - // Depth-Stencil Format - D16, - D16S8, - D24, - D24S8, - D32F, - D32F_S8, - - // Compressed Format - - // Block Compression Format, DDS (DirectDraw Surface) - // DXT1: 3 channels (5:6:5), 1/8 origianl size, with 0 or 1 bit of alpha - BC1, - BC1_ALPHA, - BC1_SRGB, - BC1_SRGB_ALPHA, - // DXT3: 4 channels (5:6:5), 1/4 origianl size, with 4 bits of alpha - BC2, - BC2_SRGB, - // DXT5: 4 channels (5:6:5), 1/4 origianl size, with 8 bits of alpha - BC3, - BC3_SRGB, - // 1 channel (8), 1/4 origianl size - BC4, - BC4_SNORM, - // 2 channels (8:8), 1/2 origianl size - BC5, - BC5_SNORM, - // 3 channels (16:16:16), half-floating point, 1/6 origianl size - // UF16: unsigned float, 5 exponent bits + 11 mantissa bits - // SF16: signed float, 1 signed bit + 5 exponent bits + 10 mantissa bits - BC6H_UF16, - BC6H_SF16, - // 4 channels (4~7 bits per channel) with 0 to 8 bits of alpha, 1/3 original size - BC7, - BC7_SRGB, - - // Ericsson Texture Compression Format - ETC_RGB8, - ETC2_RGB8, - ETC2_SRGB8, - ETC2_RGB8_A1, - ETC2_SRGB8_A1, - ETC2_RGBA8, - ETC2_SRGB8_A8, - EAC_R11, - EAC_R11SN, - EAC_RG11, - EAC_RG11SN, - - // PVRTC (PowerVR) - PVRTC_RGB2, - PVRTC_RGBA2, - PVRTC_RGB4, - PVRTC_RGBA4, - PVRTC2_2BPP, - PVRTC2_4BPP, -}; - -export class GFXFormatInfo { - readonly name : string = "UNKNOWN"; - readonly size : number = 0; - readonly count : number = 0; - readonly isFloating : boolean = false; - readonly hasAlpha : boolean = false; - readonly hasDepth : boolean = false; - readonly hasStencil : boolean = false; - readonly isCompressed : boolean = false; -}; - -export const GFXFormatInfos : GFXFormatInfo[] = [ - - { name : "UNKNOWN", size : 0, count : 0, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "A8", size : 1, count : 1, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "L8", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "LA8", size : 1, count : 2, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "R8", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8SN", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8UI", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R8I", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R16F", size : 2, count : 1, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R16UI", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R16I", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R32F", size : 4, count : 1, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R32UI", size : 4, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R32I", size : 4, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "RG8", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8SN", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8UI", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG8I", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG16F", size : 4, count : 2, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG16UI", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG16I", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG32F", size : 8, count : 2, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG32UI", size : 8, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RG32I", size : 8, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "RGB8", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "SRGB8", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8SN", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8UI", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB8I", size : 3, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB16F", size : 6, count : 3, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB16UI", size : 6, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB16I", size : 6, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB32F", size : 12, count : 3, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB32UI", size : 12, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB32I", size : 12, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "RGBA8", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "SRGB8_A8", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8SN", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8UI", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA8I", size : 4, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA16F", size : 8, count : 4, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA16UI", size : 8, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA16I", size : 8, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA32F", size : 16, count : 4, isFloating : true, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA32UI", size : 16, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA32I", size : 16, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "R5G6B5", size : 2, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "R11G11B10F", size : 4, count : 3, isFloating : true, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB5A1", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGBA4", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB10A2", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB10A2UI", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - { name : "RGB9E5", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : false }, - - { name : "D16", size : 2, count : 1, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, - { name : "D16S8", size : 3, count : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, - { name : "D24", size : 3, count : 1, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, - { name : "D24S8", size : 4, count : 2, isFloating : false, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, - { name : "D32F", size : 4, count : 1, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : false, isCompressed : false }, - { name : "D32FS8", size : 5, count : 2, isFloating : true, hasAlpha : false, hasDepth : true, hasStencil : true, isCompressed : false }, - - { name : "BC1", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC1_ALPHA", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC1_SRGB", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC1_SRGB_ALPHA", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC2", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC2_SRGB", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC3", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC3_SRGB", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC4", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC4_SNORM", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC5", size : 1, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC5_SNORM", size : 1, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC6H_UF16", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC6H_SF16", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC7", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "BC7_SRGB", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - - { name : "ETC_RGB8", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_RGB8", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_SRGB8", size : 1, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_RGB8_A1", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_SRGB8_A1", size : 1, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_RGBA8", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "ETC2_SRGB8_A8", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_R11", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_R11SN", size : 1, count : 1, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_RG11", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "EAC_RG11SN", size : 2, count : 2, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - - { name : "PVRTC_RGB2", size : 2, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGBA2", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGB4", size : 2, count : 3, isFloating : false, hasAlpha : false, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC_RGBA4", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC2_2BPP", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, - { name : "PVRTC2_4BPP", size : 2, count : 4, isFloating : false, hasAlpha : true, hasDepth : false, hasStencil : false, isCompressed : true }, -]; - -export function GFXFormatSize(format : GFXFormat, width : number, height : number, depth : number) : number { - - if(!GFXFormatInfos[format].isCompressed) { - return (width * height * depth * GFXFormatInfos[format].size); - } else { - switch(format) { - case GFXFormat.BC1: - case GFXFormat.BC1_ALPHA: - case GFXFormat.BC1_SRGB: - case GFXFormat.BC1_SRGB_ALPHA: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case GFXFormat.BC2: - case GFXFormat.BC2_SRGB: - case GFXFormat.BC3: - case GFXFormat.BC3_SRGB: - case GFXFormat.BC4: - case GFXFormat.BC4_SNORM: - case GFXFormat.BC6H_SF16: - case GFXFormat.BC6H_UF16: - case GFXFormat.BC7: - case GFXFormat.BC7_SRGB: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case GFXFormat.BC5: - case GFXFormat.BC5_SNORM: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; - - case GFXFormat.ETC_RGB8: - case GFXFormat.ETC2_RGB8: - case GFXFormat.ETC2_SRGB8: - case GFXFormat.ETC2_RGB8_A1: - case GFXFormat.ETC2_SRGB8_A1: - case GFXFormat.EAC_R11: - case GFXFormat.EAC_R11SN: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case GFXFormat.EAC_RG11: - case GFXFormat.EAC_RG11SN: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - - case GFXFormat.PVRTC_RGB2: - case GFXFormat.PVRTC_RGBA2: - case GFXFormat.PVRTC2_2BPP: - return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 4) * depth; - case GFXFormat.PVRTC_RGB4: - case GFXFormat.PVRTC_RGBA4: - case GFXFormat.PVRTC2_4BPP: - return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 2) * depth; - - default: { - return 0; - } - } - } -} - -export function GFXFormatSurfaceSize(format : GFXFormat, width : number, height : number, depth : number, mips : number) : number { - - let size = 0; - - for(let i = 0; i < mips; ++i) { - size += GFXFormatSize(format, width, height, depth); - width = Math.max(width >> 1, 1); - height = Math.max(height >> 1, 1); - depth = Math.max(depth >> 1, 1); - } - - return size; -} - -export function GFXGetTypeSize(type : GFXType) : number { - switch(type) { - case GFXType.BOOL: - case GFXType.INT: - case GFXType.UINT: - case GFXType.FLOAT: return 4; - case GFXType.BOOL2: - case GFXType.INT2: - case GFXType.UINT2: - case GFXType.FLOAT2: return 8; - case GFXType.BOOL3: - case GFXType.INT3: - case GFXType.UINT3: - case GFXType.FLOAT3: return 12; - case GFXType.BOOL4: - case GFXType.INT4: - case GFXType.UINT4: - case GFXType.FLOAT4: - case GFXType.MAT2: return 16; - case GFXType.MAT2X3: return 24; - case GFXType.MAT2X4: return 32; - case GFXType.MAT3X2: return 24; - case GFXType.MAT3: return 36; - case GFXType.MAT3X4: return 48; - case GFXType.MAT4X2: return 32; - case GFXType.MAT4X2: return 32; - case GFXType.MAT4: return 64; - case GFXType.SAMPLER1D: - case GFXType.SAMPLER1D_ARRAY: - case GFXType.SAMPLER2D: - case GFXType.SAMPLER2D_ARRAY: - case GFXType.SAMPLER3D: - case GFXType.SAMPLER_CUBE: return 4; - default: { - return 0; - } - } -} - -export type BufferView = Uint8Array; diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 8bc2540250..05ddb6e098 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -43,7 +43,7 @@ export abstract class GFXDevice { public abstract createQueue(info: GFXQueueInfo) : GFXQueue | null; public abstract createWindow(info: GFXWindowInfo) : GFXWindow | null; public abstract present(); - + public get queue(): GFXQueue { return this._queue; } @@ -52,6 +52,10 @@ export abstract class GFXDevice { return this._mainWindow; } + public get commandAllocator(): GFXCommandAllocator { + return this._cmdAllocator; + } + public get maxVertexAttributes(): number { return this._maxVertexAttributes; } @@ -59,6 +63,6 @@ export abstract class GFXDevice { protected _deviceName : string = ""; protected _queue : GFXQueue | null = null; protected _mainWindow : GFXWindow | null = null; - + protected _cmdAllocator: GFXCommandAllocator | null = null; protected _maxVertexAttributes : number = 0; }; diff --git a/cocos/gfx/framebuffer.ts b/cocos/gfx/framebuffer.ts index 2be7c4b41c..580d033097 100644 --- a/cocos/gfx/framebuffer.ts +++ b/cocos/gfx/framebuffer.ts @@ -18,7 +18,20 @@ export abstract class GFXFramebuffer { public abstract initialize(info: GFXFramebufferInfo): boolean; public abstract destroy(): void; + public get renderPass(): GFXRenderPass | null { + return this._renderPass; + } + + public get colorViews(): GFXTextureView[] { + return this._colorViews; + } + + public get depthStencilView(): GFXTextureView | null { + return this._depthStencilView; + } + protected _device: GFXDevice; + protected _renderPass: GFXRenderPass | null = null; protected _colorViews: GFXTextureView[] = []; protected _depthStencilView: GFXTextureView | null = null; protected _isOffscreen: boolean = true; diff --git a/cocos/gfx/gfx-define.ts b/cocos/gfx/gfx-define.ts new file mode 100644 index 0000000000..10c5688270 --- /dev/null +++ b/cocos/gfx/gfx-define.ts @@ -0,0 +1,710 @@ +// Extensions +export enum WebGLEXT { + COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0, + COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1, + COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2, + COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3, + + COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8C4C, + COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8C4D, + COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8C4E, + COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8C4F, + + COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00, + COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01, + COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02, + COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03, + + COMPRESSED_RGB_ETC1_WEBGL = 0x8D64, +}; + +export const GFX_MAX_VERTEX_ATTRIBUTES: number = 8; +export const GFX_MAX_TEXTURE_UNITS: number = 16; +export const GFX_MAX_ATTACHMENTS: number = 4; + +export enum GFXType { + UNKNOWN, + BOOL, + BOOL2, + BOOL3, + BOOL4, + INT, + INT2, + INT3, + INT4, + UINT, + UINT2, + UINT3, + UINT4, + FLOAT, + FLOAT2, + FLOAT3, + FLOAT4, + MAT2, + MAT2X3, + MAT2X4, + MAT3X2, + MAT3, + MAT3X4, + MAT4X2, + MAT4X3, + MAT4, + SAMPLER1D, + SAMPLER1D_ARRAY, + SAMPLER2D, + SAMPLER2D_ARRAY, + SAMPLER3D, + SAMPLER_CUBE, + COUNT, +}; + +export enum GFXFormat { + + UNKNOWN, + + A8, + L8, + LA8, + + R8, + R8SN, + R8UI, + R8I, + R16F, + R16UI, + R16I, + R32F, + R32UI, + R32I, + + RG8, + RG8SN, + RG8UI, + RG8I, + RG16F, + RG16UI, + RG16I, + RG32F, + RG32UI, + RG32I, + + RGB8, + SRGB8, + RGB8SN, + RGB8UI, + RGB8I, + RGB16F, + RGB16UI, + RGB16I, + RGB32F, + RGB32UI, + RGB32I, + + RGBA8, + SRGB8_A8, + RGBA8SN, + RGBA8UI, + RGBA8I, + RGBA16F, + RGBA16UI, + RGBA16I, + RGBA32F, + RGBA32UI, + RGBA32I, + + // Special Format + R5G6B5, + R11G11B10F, + RGB5A1, + RGBA4, + RGB10A2, + RGB10A2UI, + RGB9E5, + + // Depth-Stencil Format + D16, + D16S8, + D24, + D24S8, + D32F, + D32F_S8, + + // Compressed Format + + // Block Compression Format, DDS (DirectDraw Surface) + // DXT1: 3 channels (5:6:5), 1/8 origianl size, with 0 or 1 bit of alpha + BC1, + BC1_ALPHA, + BC1_SRGB, + BC1_SRGB_ALPHA, + // DXT3: 4 channels (5:6:5), 1/4 origianl size, with 4 bits of alpha + BC2, + BC2_SRGB, + // DXT5: 4 channels (5:6:5), 1/4 origianl size, with 8 bits of alpha + BC3, + BC3_SRGB, + // 1 channel (8), 1/4 origianl size + BC4, + BC4_SNORM, + // 2 channels (8:8), 1/2 origianl size + BC5, + BC5_SNORM, + // 3 channels (16:16:16), half-floating point, 1/6 origianl size + // UF16: unsigned float, 5 exponent bits + 11 mantissa bits + // SF16: signed float, 1 signed bit + 5 exponent bits + 10 mantissa bits + BC6H_UF16, + BC6H_SF16, + // 4 channels (4~7 bits per channel) with 0 to 8 bits of alpha, 1/3 original size + BC7, + BC7_SRGB, + + // Ericsson Texture Compression Format + ETC_RGB8, + ETC2_RGB8, + ETC2_SRGB8, + ETC2_RGB8_A1, + ETC2_SRGB8_A1, + ETC2_RGBA8, + ETC2_SRGB8_A8, + EAC_R11, + EAC_R11SN, + EAC_RG11, + EAC_RG11SN, + + // PVRTC (PowerVR) + PVRTC_RGB2, + PVRTC_RGBA2, + PVRTC_RGB4, + PVRTC_RGBA4, + PVRTC2_2BPP, + PVRTC2_4BPP, +}; + +export enum GFXVertexSemantic { + UNKNOWN, + POSITION, + POSITION1, + POSITION2, + POSITION3, + COLOR, + COLOR1, + COLOR2, + COLOR3, + NORMAL, + NORMAL1, + NORMAL2, + NORMAL3, + TANGENT, + BINORMAL, + TEXCOORD, + TEXCOORD1, + TEXCOORD2, + TEXCOORD3, + JOINTS, + WEIGHTS, + SV_INSTANCE_ID, +}; + +export enum GFXBufferUsageBit { + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + INDEX = 0x4, + VERTEX = 0x8, + UNIFORM = 0x10, + STORAGE = 0x20, +}; + +export type GFXBufferUsage = GFXBufferUsageBit; + +export enum GFXMemoryUsageBit { + NONE = 0, + DEVICE = 0x1, + HOST = 0x2, +}; + +export type GFXMemoryUsage = GFXMemoryUsageBit; + +export enum GFXBufferAccessBit { + NONE = 0, + READ = 0x1, + WRITE = 0x2, +}; + +export type GFXBufferAccess = GFXBufferAccessBit; + +export enum GFXPrimitiveMode { + POINT_LIST, + LINE_LIST, + LINE_STRIP, + LINE_LOOP, + TRIANGLE_LIST, + TRIANGLE_STRIP, + TRIANGLE_FAN, + LINE_LIST_ADJACENCY, + LINE_STRIP_ADJACENCY, + TRIANGLE_LIST_ADJACENCY, + TRIANGLE_STRIP_ADJACENCY, + TRIANGLE_PATCH_ADJACENCY, + QUAD_PATCH_LIST, + ISO_LINE_LIST, +}; + +export enum GFXPolygonMode { + FILL, + LINE, + POINT, +}; + +export enum GFXShadeModel { + GOURAND, + FLAT, +}; + +export enum GFXCullMode { + NONE, + FRONT, + BACK, +}; + +export enum GFXComparisonFunc { + NEVER, + LESS, + EQUAL, + LESS_EQUAL, + GREATER, + NOT_EQUAL, + GREATER_EQUAL, + ALWAYS, +}; + +export enum GFXStencilOp { + KEEP, + ZERO, + REPLACE, + INCR, + DECR, + INVERT, + INCR_WRAP, + DECR_WRAP, +}; + +export enum GFXBlendOp { + ADD, + SUB, + REV_SUB, + MIN, + MAX, +}; + +export enum GFXBlendFactor { + ZERO, + ONE, + SRC_ALPHA, + DST_ALPHA, + ONE_MINUS_SRC_ALPHA, + ONE_MINUS_DST_ALPHA, + SRC_COLOR, + DST_COLOR, + ONE_MINUS_SRC_COLOR, + ONE_MINUS_DST_COLOR, + SRC_ALPHA_SATURATE, + CONSTANT_COLOR, + ONE_MINUS_CONSTANT_COLOR, + CONSTANT_ALPHA, + ONE_MINUS_CONSTANT_ALPHA, +}; + +export enum GFXColorMask { + NONE = 0x0, + R = 0x1, + G = 0x2, + B = 0x4, + A = 0x8, + ALL = R | G | B | A, +}; + +export enum GFXFilter { + NONE, + POINT, + LINEAR, + ANISOTROPIC, +}; + +export enum GFXAddress { + WRAP, + MIRROR, + CLAMP, + BORDER, +}; + +export enum GFXTextureType { + TEX1D, + TEX2D, + TEX3D, +}; + +export enum GFXTextureUsageBit { + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + SAMPLED = 0x4, + STORAGE = 0x8, + COLOR_ATTACHMENT = 0x10, + DEPTH_STENCIL_ATTACHMENT = 0x20, + TRANSIENT_ATTACHMENT = 0x40, + INPUT_ATTACHMENT = 0x80, +}; + +export type GFXTextureUsage = GFXTextureUsageBit; + +export enum GFXTextureFlagBit { + NONE = 0, + GEN_MIPMAP = 0x1, + CUBEMAP = 0x2, + BAKUP_BUFFER = 0x4, +}; + +export type GFXTextureFlags = GFXTextureFlagBit; + +export enum GFXTextureViewType { + TV1D, + TV2D, + TV3D, + CUBE, + TV1D_ARRAY, + TV2D_ARRAY, +}; + +export enum GFXShaderType { + VERTEX, + HULL, + DOMAIN, + GEOMETRY, + FRAGMENT, + COMPUTE, + COUNT, +}; + +export enum GFXBindingType { + UNKNOWN, + UNIFORM_BUFFER, + SAMPLER, + STORAGE_BUFFER, +}; + +export enum GFXCommandBufferType { + PRIMARY, + SECONDARY, +}; + +// Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. +export enum GFXLoadOp { + LOAD, // Load the contents from the fbo from previous + CLEAR, // Clear the fbo + DISCARD, // Ignore writing to the fbo and keep old data +}; + +// Enumerates all possible values of operations to be performed when Storing to a Framebuffer Object. +export enum GFXStoreOp { + STORE, // Write the source to the destination + DISCARD, // Don't write the source to the destination +}; + +export enum GFXTextureLayout { + UNDEFINED, + GENERAL, + COLOR_ATTACHMENT_OPTIMAL, + DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + DEPTH_STENCIL_READONLY_OPTIMAL, + SHADER_READONLY_OPTIMAL, + TRANSFER_SRC_OPTIMAL, + TRANSFER_DST_OPTIMAL, + PREINITIALIZED, + PRESENT_SRC, +}; + +export enum GFXPipelineBindPoint { + GRAPHICS, + COMPUTE, + RAY_TRACING, +}; + +export enum GFXQueueType { + GRAPHICS, + COMPUTE, + TRANSFER, +}; + +// Interfaces + +export interface GFXRect { + left: number; + top: number; + width: number; + height: number; +}; + +export interface GFXViewport { + left: number; + top: number; + width: number; + height: number; + minDepth: number; + maxDepth: number; +}; + +export interface GFXColor { + r: number; + g: number; + b: number; + a: number; +}; + +export interface GFXTextureSubres { + baseMipLevel: number; + levelCount: number; + baseArrayLayer: number; + layerCount: number; +}; + +export interface GFXTextureCopy { + srcSubres: GFXTextureSubres; + srcOffset: number[]; + dstSubres: GFXTextureSubres; + dstOffset: number[]; + extent: number[]; +}; + +export interface GFXBufferTextureCopy { + buffOffset: number; + buffStride: number; + buffTexHeight: number; + texOffset: number[]; + texExtent: number[]; + texSubres: GFXTextureSubres; +}; + +export interface GFXFormatInfo { + readonly name: string; + readonly size: number; + readonly count: number; + readonly isFloating: boolean; + readonly hasAlpha: boolean; + readonly hasDepth: boolean; + readonly hasStencil: boolean; + readonly isCompressed: boolean; +}; + +export const GFXFormatInfos: GFXFormatInfo[] = [ + + { name: "UNKNOWN", size: 0, count: 0, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "A8", size: 1, count: 1, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "L8", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "LA8", size: 1, count: 2, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "R8", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R8SN", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R8UI", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R8I", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R16F", size: 2, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R16UI", size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R16I", size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R32F", size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R32UI", size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R32I", size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "RG8", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG8SN", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG8UI", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG8I", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG16F", size: 4, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG16UI", size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG16I", size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG32F", size: 8, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG32UI", size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RG32I", size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "RGB8", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "SRGB8", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB8SN", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB8UI", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB8I", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB16F", size: 6, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB16UI", size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB16I", size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB32F", size: 12, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB32UI", size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB32I", size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "RGBA8", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "SRGB8_A8", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA8SN", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA8UI", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA8I", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA16F", size: 8, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA16UI", size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA16I", size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA32F", size: 16, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA32UI", size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA32I", size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "R5G6B5", size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "R11G11B10F", size: 4, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB5A1", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGBA4", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB10A2", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB10A2UI", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: "RGB9E5", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + + { name: "D16", size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: "D16S8", size: 3, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: "D24", size: 3, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: "D24S8", size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: "D32F", size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: "D32FS8", size: 5, count: 2, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + + { name: "BC1", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC1_ALPHA", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC1_SRGB", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC1_SRGB_ALPHA", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC2", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC2_SRGB", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC3", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC3_SRGB", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC4", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC4_SNORM", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC5", size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC5_SNORM", size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC6H_UF16", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC6H_SF16", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC7", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "BC7_SRGB", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + + { name: "ETC_RGB8", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "ETC2_RGB8", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "ETC2_SRGB8", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "ETC2_RGB8_A1", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "ETC2_SRGB8_A1", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "ETC2_RGBA8", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "ETC2_SRGB8_A8", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "EAC_R11", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "EAC_R11SN", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "EAC_RG11", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "EAC_RG11SN", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + + { name: "PVRTC_RGB2", size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "PVRTC_RGBA2", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "PVRTC_RGB4", size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "PVRTC_RGBA4", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "PVRTC2_2BPP", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: "PVRTC2_4BPP", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, +]; + +export function GFXFormatSize(format: GFXFormat, width: number, height: number, depth: number): number { + + if (!GFXFormatInfos[format].isCompressed) { + return (width * height * depth * GFXFormatInfos[format].size); + } else { + switch (format) { + case GFXFormat.BC1: + case GFXFormat.BC1_ALPHA: + case GFXFormat.BC1_SRGB: + case GFXFormat.BC1_SRGB_ALPHA: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.BC2: + case GFXFormat.BC2_SRGB: + case GFXFormat.BC3: + case GFXFormat.BC3_SRGB: + case GFXFormat.BC4: + case GFXFormat.BC4_SNORM: + case GFXFormat.BC6H_SF16: + case GFXFormat.BC6H_UF16: + case GFXFormat.BC7: + case GFXFormat.BC7_SRGB: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case GFXFormat.BC5: + case GFXFormat.BC5_SNORM: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; + + case GFXFormat.ETC_RGB8: + case GFXFormat.ETC2_RGB8: + case GFXFormat.ETC2_SRGB8: + case GFXFormat.ETC2_RGB8_A1: + case GFXFormat.ETC2_SRGB8_A1: + case GFXFormat.EAC_R11: + case GFXFormat.EAC_R11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.EAC_RG11: + case GFXFormat.EAC_RG11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + + case GFXFormat.PVRTC_RGB2: + case GFXFormat.PVRTC_RGBA2: + case GFXFormat.PVRTC2_2BPP: + return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 4) * depth; + case GFXFormat.PVRTC_RGB4: + case GFXFormat.PVRTC_RGBA4: + case GFXFormat.PVRTC2_4BPP: + return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 2) * depth; + + default: { + return 0; + } + } + } +} + +export function GFXFormatSurfaceSize(format: GFXFormat, width: number, height: number, depth: number, mips: number): number { + + let size = 0; + + for (let i = 0; i < mips; ++i) { + size += GFXFormatSize(format, width, height, depth); + width = Math.max(width >> 1, 1); + height = Math.max(height >> 1, 1); + depth = Math.max(depth >> 1, 1); + } + + return size; +} + +export function GFXGetTypeSize(type: GFXType): number { + switch (type) { + case GFXType.BOOL: + case GFXType.INT: + case GFXType.UINT: + case GFXType.FLOAT: return 4; + case GFXType.BOOL2: + case GFXType.INT2: + case GFXType.UINT2: + case GFXType.FLOAT2: return 8; + case GFXType.BOOL3: + case GFXType.INT3: + case GFXType.UINT3: + case GFXType.FLOAT3: return 12; + case GFXType.BOOL4: + case GFXType.INT4: + case GFXType.UINT4: + case GFXType.FLOAT4: + case GFXType.MAT2: return 16; + case GFXType.MAT2X3: return 24; + case GFXType.MAT2X4: return 32; + case GFXType.MAT3X2: return 24; + case GFXType.MAT3: return 36; + case GFXType.MAT3X4: return 48; + case GFXType.MAT4X2: return 32; + case GFXType.MAT4X2: return 32; + case GFXType.MAT4: return 64; + case GFXType.SAMPLER1D: + case GFXType.SAMPLER1D_ARRAY: + case GFXType.SAMPLER2D: + case GFXType.SAMPLER2D_ARRAY: + case GFXType.SAMPLER3D: + case GFXType.SAMPLER_CUBE: return 4; + default: { + return 0; + } + } +} diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 4d6c87ae50..7ad9707570 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,10 +1,10 @@ import { GFXDevice } from './device'; -import { GFXFormat } from './define'; +import { GFXFormat, GFXVertexSemantic } from './gfx-define'; import { GFXBuffer } from './buffer'; -import { GFXShader } from './shader'; export interface GFXInputAttribute { name: string; + semantic: GFXVertexSemantic; format: GFXFormat; stream?: number; isInstanced?: boolean; @@ -12,7 +12,6 @@ export interface GFXInputAttribute { export interface GFXInputAssemblerInfo { attributes: GFXInputAttribute[]; - shader: GFXShader; vertexBuffers: GFXBuffer[]; indexBuffer?: GFXBuffer; isIndirect?: boolean; @@ -43,6 +42,10 @@ export abstract class GFXInputAssembler { } } + public get attributes(): GFXInputAttribute[] { + return this._attributes; + } + public get vertexCount(): number { return this._vertexCount; } diff --git a/cocos/gfx/pipeline-layout.ts b/cocos/gfx/pipeline-layout.ts index e669d95f93..00b0a34c54 100644 --- a/cocos/gfx/pipeline-layout.ts +++ b/cocos/gfx/pipeline-layout.ts @@ -1,11 +1,11 @@ import { GFXDevice } from './device'; import { GFXBindingLayout } from './binding-layout'; -import { GFXShaderType } from './shader'; +import { GFXShaderType } from './gfx-define'; -export class GFXPushConstantRange { - shaderType : GFXShaderType = GFXShaderType.VERTEX; - offset : number = 0; - count : number = 0; +export interface GFXPushConstantRange { + shaderType : GFXShaderType; + offset : number; + count : number; }; export interface GFXPipelineLayoutInfo { diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index babe08015c..410c20a5be 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -3,97 +3,7 @@ import { GFXShader } from './shader'; import { GFXRenderPass } from './render-pass'; import { GFXPipelineLayout } from './pipeline-layout'; import { GFXInputAttribute } from './input-assembler'; - -export enum GFXPrimitiveMode { - POINT_LIST, - LINE_LIST, - LINE_STRIP, - LINE_LOOP, - TRIANGLE_LIST, - TRIANGLE_STRIP, - TRIANGLE_FAN, - LINE_LIST_ADJACENCY, - LINE_STRIP_ADJACENCY, - TRIANGLE_LIST_ADJACENCY, - TRIANGLE_STRIP_ADJACENCY, - TRIANGLE_PATCH_ADJACENCY, - QUAD_PATCH_LIST, - ISO_LINE_LIST, -}; - -export enum GFXPolygonMode { - FILL, - LINE, - POINT, -}; - -export enum GFXShadeModel { - GOURAND, - FLAT, -}; - -export enum GFXCullMode { - NONE, - FRONT, - BACK, -}; - -export enum GFXComparisonFunc { - NEVER, - LESS, - EQUAL, - LESS_EQUAL, - GREATER, - NOT_EQUAL, - GREATER_EQUAL, - ALWAYS, -}; - -export enum GFXStencilOp { - KEEP, - ZERO, - REPLACE, - INCR, - DECR, - INVERT, - INCR_WRAP, - DECR_WRAP, -}; - -export enum GFXBlendOp { - ADD, - SUB, - REV_SUB, - MIN, - MAX, -}; - -export enum GFXBlendFactor { - ZERO, - ONE, - SRC_ALPHA, - DST_ALPHA, - ONE_MINUS_SRC_ALPHA, - ONE_MINUS_DST_ALPHA, - SRC_COLOR, - DST_COLOR, - ONE_MINUS_SRC_COLOR, - ONE_MINUS_DST_COLOR, - SRC_ALPHA_SATURATE, - CONSTANT_COLOR, - ONE_MINUS_CONSTANT_COLOR, - CONSTANT_ALPHA, - ONE_MINUS_CONSTANT_ALPHA, -}; - -export enum GFXColorMask { - NONE = 0x0, - R = 0x1, - G = 0x2, - B = 0x4, - A = 0x8, - ALL = R | G | B | A, -}; +import { GFXPolygonMode, GFXShadeModel, GFXCullMode, GFXComparisonFunc, GFXStencilOp, GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXPrimitiveMode } from './gfx-define'; export class GFXRasterizerState { isDiscard: boolean = false; diff --git a/cocos/gfx/queue.ts b/cocos/gfx/queue.ts index 6ebf7fc77e..a0ddfe2928 100644 --- a/cocos/gfx/queue.ts +++ b/cocos/gfx/queue.ts @@ -1,10 +1,6 @@ import { GFXDevice } from './device'; - -export enum GFXQueueType { - GRAPHICS, - COMPUTE, - TRANSFER, -}; +import { GFXCommandBuffer } from './command-buffer'; +import { GFXQueueType } from './gfx-define'; export interface GFXQueueInfo { type : GFXQueueType; @@ -18,6 +14,7 @@ export abstract class GFXQueue { public abstract initialize(info : GFXQueueInfo) : boolean; public abstract destroy(); + public abstract submit(cmdBuffs: GFXCommandBuffer[], fence?); public get type(): number { return this._type; diff --git a/cocos/gfx/render-pass.ts b/cocos/gfx/render-pass.ts index 8dc6b7cd84..8cd3fcaab2 100644 --- a/cocos/gfx/render-pass.ts +++ b/cocos/gfx/render-pass.ts @@ -1,35 +1,6 @@ -import { GFXFormat, GFXFormatInfo } from './define'; +import { GFXFormat, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint } from './gfx-define'; import { GFXDevice } from './device'; -// Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. -export enum GFXLoadOp -{ - LOAD, // Load the contents from the fbo from previous - CLEAR, // Clear the fbo - DISCARD, // Ignore writing to the fbo and keep old data -}; - -// Enumerates all possible values of operations to be performed when Storing to a Framebuffer Object. -export enum GFXStoreOp -{ - STORE, // Write the source to the destination - DISCARD, // Don't write the source to the destination -}; - -export enum GFXTextureLayout -{ - UNDEFINED, - GENERAL, - COLOR_ATTACHMENT_OPTIMAL, - DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - DEPTH_STENCIL_READONLY_OPTIMAL, - SHADER_READONLY_OPTIMAL, - TRANSFER_SRC_OPTIMAL, - TRANSFER_DST_OPTIMAL, - PREINITIALIZED, - PRESENT_SRC, -}; - export class GFXColorAttachment { format : GFXFormat = GFXFormat.UNKNOWN; @@ -52,28 +23,21 @@ export class GFXDepthStencilAttachment endLayout : GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; }; -export enum GFXPipelineBindPoint +export interface GFXSubPassInfo { - GRAPHICS, - COMPUTE, - RAY_TRACING, + bindPoint : GFXPipelineBindPoint; + inputs : number[]; + colors : number[]; + resolves : number[]; + depthStencil : number; + preserves : number[]; }; -export class GFXSubPassInfo +export interface GFXRenderPassInfo { - bindPoint : GFXPipelineBindPoint = GFXPipelineBindPoint.GRAPHICS; - inputs : number[] = []; - colors : number[] = []; - resolves : number[] = []; - depthStencil : number = -1; - preserves : number[] = []; -}; - -export class GFXRenderPassInfo -{ - colorAttachment : GFXColorAttachment[] = []; - depthStencilAttachment : GFXDepthStencilAttachment | null = null; - //subPasses : GFXSubPassInfo[] = []; + colorAttachment? : GFXColorAttachment[]; + depthStencilAttachment? : GFXDepthStencilAttachment; + //subPasses? : GFXSubPassInfo[]; }; export abstract class GFXRenderPass { diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index 1258adf23c..885e0fe8cc 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -1,21 +1,23 @@ import { GFXDevice } from './device'; -import { GFXComparisonFunc } from './pipeline-state'; +import { GFXFilter, GFXAddress, GFXComparisonFunc } from './gfx-define'; -export enum GFXFilter { - NONE, - POINT, - LINEAR, - ANISOTROPIC, +export interface GFXSamplerInfo { + name? : string; + minFilter? : GFXFilter; + magFilter? : GFXFilter; + mipFilter? : GFXFilter; + addressU? : GFXAddress; + addressV? : GFXAddress; + addressW? : GFXAddress; + maxAnisotropy? : number; + cmpFunc? : GFXComparisonFunc; + borderColor? : number[]; + minLOD? : number; + maxLOD? : number; + mipLODBias? : number; }; -export enum GFXAddress { - WRAP, - MIRROR, - CLAMP, - BORDER, -}; - -export class GFXSamplerInfo { +export class GFXSamplerState { name : string = ""; minFilter : GFXFilter = GFXFilter.LINEAR; magFilter : GFXFilter = GFXFilter.LINEAR; @@ -30,7 +32,7 @@ export class GFXSamplerInfo { maxLOD : number = 1000; mipLODBias : number = 0.0; - public compare(state : GFXSamplerInfo) : boolean { + public compare(state : GFXSamplerState) : boolean { return (this.minFilter === state.minFilter) && (this.magFilter === state.magFilter) && (this.mipFilter === state.mipFilter) && @@ -50,11 +52,16 @@ export abstract class GFXSampler { constructor(device : GFXDevice) { this._device = device; + this._state = new GFXSamplerState; } public abstract initialize(info : GFXSamplerInfo) : boolean; public abstract destroy() : void; + public get state(): GFXSamplerState { + return this._state; + } + protected _device : GFXDevice; - protected _state : GFXSamplerInfo | null = null; + protected _state : GFXSamplerState; }; diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index afd54e3ad8..b175bc1dd3 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -1,22 +1,17 @@ import { GFXDevice } from './device'; -import { GFXBinding } from './binding-layout'; -import { GFXType } from './define'; - -export enum GFXShaderType { - VERTEX, - HULL, - DOMAIN, - GEOMETRY, - FRAGMENT, - COMPUTE, - COUNT, -}; +import { GFXType, GFXShaderType } from './gfx-define'; export interface GFXShaderMacro { macro: string; value: string; }; +export interface GFXShaderStage { + type: GFXShaderType; + source: string; + macros?: GFXShaderMacro[]; +}; + export interface GFXUniform { name: string; type: GFXType; @@ -37,14 +32,8 @@ export interface GFXUniformSampler { count: number; }; -export interface GFXShaderStage { - type: GFXShaderType; - source: string; - macros?: GFXShaderMacro[]; -}; - export interface GFXShaderInfo { - name?: string; + name: string; stages: GFXShaderStage[]; //bindings: GFXBinding[]; diff --git a/cocos/gfx/texture-view.ts b/cocos/gfx/texture-view.ts index bd5dec1cc6..37a13a70f7 100644 --- a/cocos/gfx/texture-view.ts +++ b/cocos/gfx/texture-view.ts @@ -1,16 +1,7 @@ -import { GFXFormat, GFXFormatInfo } from './define'; +import { GFXFormat, GFXTextureViewType } from './gfx-define'; import { GFXDevice } from './device'; import { GFXTexture } from './texture'; -export enum GFXTextureViewType { - TV1D, - TV2D, - TV3D, - CUBE, - TV1D_ARRAY, - TV2D_ARRAY, -}; - export interface GFXTextureViewInfo { texture: GFXTexture; type: GFXTextureViewType; diff --git a/cocos/gfx/texture.ts b/cocos/gfx/texture.ts index 5d36e5d00c..6650e475ba 100644 --- a/cocos/gfx/texture.ts +++ b/cocos/gfx/texture.ts @@ -1,35 +1,6 @@ -import { GFXFormat, GFXFormatInfo } from './define'; +import { GFXFormat, GFXTextureType, GFXTextureUsage, GFXTextureFlags, GFXTextureUsageBit, GFXTextureFlagBit } from './gfx-define'; import { GFXDevice } from './device'; -export enum GFXTextureType { - TEX1D, - TEX2D, - TEX3D, -}; - -export enum GFXTextureUsageBit { - NONE = 0, - TRANSFER_SRC = 0x1, - TRANSFER_DST = 0x2, - SAMPLED = 0x4, - STORAGE = 0x8, - COLOR_ATTACHMENT = 0x10, - DEPTH_STENCIL_ATTACHMENT = 0x20, - TRANSIENT_ATTACHMENT = 0x40, - INPUT_ATTACHMENT = 0x80, -}; - -export type GFXTextureUsage = GFXTextureUsageBit; - -export enum GFXTextureFlagBit { - NONE = 0, - GEN_MIPMAP = 0x1, - CUBEMAP = 0x2, - BAKUP_BUFFER = 0x4, -}; - -export type GFXTextureFlags = GFXTextureFlagBit; - export interface GFXTextureInfo { type: GFXTextureType; usage: GFXTextureUsage; diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 604e56ed5c..ecc150f184 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,8 +1,8 @@ -import { GFXBufferInfo, GFXBuffer, GFXMemoryUsageBit, GFXBufferAccess, GFXBufferAccessBit, GFXBufferUsageBit } from '../buffer'; +import { GFXBufferInfo, GFXBuffer } from '../buffer'; import { GFXDevice } from '../device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; import { WebGLGFXDevice } from './webgl-device'; -import { BufferView } from '../define'; +import { GFXMemoryUsageBit } from '../gfx-define'; export class WebGLGFXBuffer extends GFXBuffer { @@ -23,7 +23,7 @@ export class WebGLGFXBuffer extends GFXBuffer { } //this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; - this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._bufferView); + this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); return true; } @@ -38,13 +38,13 @@ export class WebGLGFXBuffer extends GFXBuffer { this._bufferView = null; } - public update(buffer: BufferView, offset: number) { + public update(buffer: ArrayBuffer, offset?: number) { if (this._bufferView) { - this._bufferView.set(buffer, offset); + this._bufferView.set(new Uint8Array(buffer), offset); } - this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset, buffer); + this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset? offset : 0, buffer); } public get webGLDevice(): WebGLGFXDevice { diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 71a1e3bc91..00464cf366 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,5 +1,5 @@ import { GFXDevice } from '../device'; -import { GFXCommandBuffer, GFXCommandBufferInfo, GFXBufferTextureCopy } from '../command-buffer'; +import { GFXCommandBuffer, GFXCommandBufferInfo } from '../command-buffer'; import { GFXBuffer } from '../buffer'; import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; @@ -14,8 +14,8 @@ import { WebGLGFXPipelineState } from './webgl-pipeline-state'; import { GFXBindingLayout } from '../binding-layout'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; import { GFXTexture } from '../texture'; -import { GFXTextureLayout } from '../render-pass'; import { WebGLGFXTexture } from './webgl-texture'; +import { GFXColor, GFXViewport, GFXRect, GFXBufferTextureCopy, GFXTextureLayout } from '../gfx-define'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { @@ -52,12 +52,11 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public end() { } - public beginRenderPass(framebuffer : GFXFramebuffer, viewport : number[], numClearColors : number, clearColors : number[], clearStencil : number) { + public beginRenderPass(framebuffer : GFXFramebuffer, renderArea : GFXRect, clearColors : GFXColor[], clearDepth: number, clearStencil : number) { let cmd = (this._allocator).beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); if (cmd) { cmd.gpuFramebuffer = (framebuffer).gpuFramebuffer; - cmd.viewport = viewport.slice(); - cmd.numClearColors = numClearColors; + cmd.renderArea = renderArea; cmd.clearColors = clearColors.slice(); cmd.clearStencil = clearStencil; this.cmdPackage.beginRenderPassCmds.push(cmd); @@ -117,13 +116,13 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public updateBuffer(buffer : GFXBuffer, data : Buffer, offset : number) { + public updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset : number) { let gpuBuffer = (buffer).gpuBuffer; if(gpuBuffer) { let cmd = (this._allocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { cmd.gpuBuffer = gpuBuffer; - cmd.buffer = data.slice(0); + cmd.buffer = data; cmd.offset = offset; this.cmdPackage.updateBufferCmds.push(cmd); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 6ee4ffd7a7..b51b9b920f 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,18 +1,10 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../buffer"; -import { GFXTextureViewType } from "../texture-view"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, BufferView } from "../define"; -import { GFXShaderType } from "../shader"; -import { GFXLoadOp, GFXTextureLayout } from "../render-pass"; -import { GFXColorMask, GFXCullMode } from "../pipeline-state"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXViewport, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit } from "../gfx-define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; -import { GFXBindingType } from "../binding-layout"; import { WebGLTexUnit } from "./webgl-state-cache"; -import { GFXBufferTextureCopy } from "../command-buffer"; -import { GFXTextureFlagBit } from "../texture"; -function GFXFormatToWebGLType(format: GFXFormat, device : WebGLGFXDevice): GLenum { +function GFXFormatToWebGLType(format: GFXFormat, device: WebGLGFXDevice): GLenum { switch (format) { case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; @@ -71,7 +63,7 @@ function GFXFormatToWebGLType(format: GFXFormat, device : WebGLGFXDevice): GLenu case GFXFormat.D16: return WebGLRenderingContext.UNSIGNED_SHORT; case GFXFormat.D16S8: return WebGLRenderingContext.UNSIGNED_SHORT; case GFXFormat.D24: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.D24S8: return device.WEBGL_depth_texture? device.WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL : WebGLRenderingContext.UNSIGNED_INT; + case GFXFormat.D24S8: return device.WEBGL_depth_texture ? device.WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL : WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.D32F: return WebGLRenderingContext.FLOAT; case GFXFormat.D32F_S8: return WebGLRenderingContext.FLOAT; @@ -282,8 +274,7 @@ function WebGLGetComponentCount(glType: GLenum): GFXType { case WebGLRenderingContext.FLOAT_MAT3: return 3; case WebGLRenderingContext.FLOAT_MAT4: return 4; default: { - console.error("Unsupported GLType, get component count failed."); - return 0; + return 1; } } } @@ -357,9 +348,8 @@ export class WebGLCmdObject { export class WebGLCmdBeginRenderPass extends WebGLCmdObject { gpuFramebuffer: WebGLGPUFramebuffer | null = null; - viewport: number[] = []; - numClearColors: number = 0; - clearColors: number[] = []; + renderArea: GFXRect = { left: 0.0, top: 0.0, width: 0.0, height: 0.0 }; + clearColors: GFXColor[] = []; clearDepth: number = 1.0; clearStencil: number = 0; @@ -415,7 +405,7 @@ export class WebGLCmdDraw extends WebGLCmdObject { export class WebGLCmdUpdateBuffer extends WebGLCmdObject { gpuBuffer: WebGLGPUBuffer | null = null; - buffer: Buffer | null = null; + buffer: ArrayBuffer | null = null; offset: number = 0; constructor() { @@ -560,7 +550,7 @@ export function WebGLCmdFuncDestroyBuffer(device: WebGLGFXDevice, gpuBuffer: Web } } -export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: BufferView) { +export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { let gl = device.gl; @@ -570,7 +560,7 @@ export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer.buffer); + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); break; } case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { @@ -578,7 +568,7 @@ export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer.buffer); + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); break; } default: { @@ -775,8 +765,9 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG var isSuccess = gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS); if (!isSuccess) { console.error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed."); + console.error(gpuStage.source); console.error(gl.getShaderInfoLog(gpuStage.glShader)); - } else { + gl.deleteShader(gpuStage.glShader); gpuStage.glShader = 0; } @@ -797,7 +788,9 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG gl.linkProgram(gpuShader.glProgram); var isSuccess = gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS); - if (!isSuccess) { + if (isSuccess) { + console.info("Shader '" + gpuShader.name + "' compilation successed."); + } else { console.error("Failed to link shader '" + gpuShader.name + "'."); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); @@ -820,7 +813,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG let glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); let varName: string; - let nameOffset = info.name.search('['); + let nameOffset = info.name.indexOf('['); if (nameOffset !== -1) { varName = info.name.substr(0, nameOffset); } else { @@ -921,7 +914,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG let glLoc = gl.getUniformLocation(gpuShader.glProgram, info.name); if (glLoc) { let varName: string; - let nameOffset = info.name.search('['); + let nameOffset = info.name.indexOf('['); if (nameOffset !== -1) { varName = info.name.substr(0, nameOffset); } else { @@ -996,6 +989,37 @@ export function WebGLCmdFuncDestroyShader(device: WebGLGFXDevice, gpuShader: Web export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { + gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); + + let offsets = [0, 0, 0, 0, 0, 0, 0, 0]; + + for(let i = 0; i < gpuInputAssembler.attributes.length; ++i) { + let attrib = gpuInputAssembler.attributes[i]; + + let stream = attrib.stream ? attrib.stream : 0; + //if (stream < gpuInputAssembler.gpuVertexBuffers.length) { + + let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; + + let glType = GFXFormatToWebGLType(attrib.format, device); + let size = WebGLGetTypeSize(glType); + + gpuInputAssembler.glAttribs[i] = { + glBuffer: gpuBuffer.glBuffer, + glLoc: attrib.semantic, + glType: glType, + size: size, + count: GFXFormatInfos[attrib.format].count, + stride: gpuBuffer.stride, + componentCount: WebGLGetComponentCount(glType), + isInstanced: attrib.isInstanced? attrib.isInstanced : false, + offset: offsets[stream], + }; + + offsets[stream] += size; + } + + /* if (gpuInputAssembler.gpuShader) { let attribCount = gpuInputAssembler.gpuShader.glInputs.length; gpuInputAssembler.glAttribs = new Array(attribCount); @@ -1033,6 +1057,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput } } } + */ } export function WebGLCmdFuncDestroyInputAssembler(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { @@ -1067,30 +1092,30 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG device.stateCache.glFramebuffer = cmd.gpuFramebuffer.glFramebuffer; } - if (device.stateCache.viewport[0] !== cmd.viewport[0] || - device.stateCache.viewport[1] !== cmd.viewport[1] || - device.stateCache.viewport[2] !== cmd.viewport[2] || - device.stateCache.viewport[3] !== cmd.viewport[3]) { + if (device.stateCache.viewport.left !== cmd.renderArea.left || + device.stateCache.viewport.top !== cmd.renderArea.top || + device.stateCache.viewport.width !== cmd.renderArea.width || + device.stateCache.viewport.height !== cmd.renderArea.height) { - gl.viewport(cmd.viewport[0], cmd.viewport[1], cmd.viewport[2], cmd.viewport[3]); + gl.viewport(cmd.renderArea.left, cmd.renderArea.top, cmd.renderArea.width, cmd.renderArea.height); - device.stateCache.viewport[0] = cmd.viewport[0]; - device.stateCache.viewport[1] = cmd.viewport[1]; - device.stateCache.viewport[2] = cmd.viewport[2]; - device.stateCache.viewport[3] = cmd.viewport[3]; + device.stateCache.viewport.left = cmd.renderArea.left; + device.stateCache.viewport.top = cmd.renderArea.top; + device.stateCache.viewport.width = cmd.renderArea.width; + device.stateCache.viewport.height = cmd.renderArea.height; } - if (device.stateCache.scissorRect[0] !== cmd.viewport[0] || - device.stateCache.scissorRect[1] !== cmd.viewport[1] || - device.stateCache.scissorRect[2] !== cmd.viewport[2] || - device.stateCache.scissorRect[3] !== cmd.viewport[3]) { + if (device.stateCache.scissorRect.left !== cmd.renderArea.left || + device.stateCache.scissorRect.top !== cmd.renderArea.top || + device.stateCache.scissorRect.width !== cmd.renderArea.width || + device.stateCache.scissorRect.height !== cmd.renderArea.height) { - gl.scissor(cmd.viewport[0], cmd.viewport[1], cmd.viewport[2], cmd.viewport[3]); + gl.scissor(cmd.renderArea.left, cmd.renderArea.top, cmd.renderArea.width, cmd.renderArea.height); - device.stateCache.scissorRect[0] = cmd.viewport[0]; - device.stateCache.scissorRect[1] = cmd.viewport[1]; - device.stateCache.scissorRect[2] = cmd.viewport[2]; - device.stateCache.scissorRect[3] = cmd.viewport[3]; + device.stateCache.scissorRect.left = cmd.renderArea.left; + device.stateCache.scissorRect.top = cmd.renderArea.top; + device.stateCache.scissorRect.width = cmd.renderArea.width; + device.stateCache.scissorRect.height = cmd.renderArea.height; } let curGPURenderPass = cmd.gpuFramebuffer.gpuRenderPass; @@ -1110,7 +1135,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.colorMask(true, true, true, true); } - gl.clearColor(cmd.clearColors[0], cmd.clearColors[1], cmd.clearColors[2], cmd.clearColors[3]); + let clearColor = cmd.clearColors[0]; + gl.clearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); clears |= WebGLRenderingContext.COLOR_BUFFER_BIT; break; @@ -1520,9 +1546,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 2*m; + let idx = 2 * m; if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1]) { + glBlock.bufferView.getInt32(offset + 4) !== glUniform.bufferView[idx + 1]) { gl.uniform2iv(glUniform.glLoc, glUniform.bufferView); break; } @@ -1534,10 +1560,10 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.INT_VEC3: { let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 3*m; + let idx = 3 * m; if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2]) { + glBlock.bufferView.getInt32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getInt32(offset + 8) !== glUniform.bufferView[idx + 2]) { gl.uniform3iv(glUniform.glLoc, glUniform.bufferView); break; } @@ -1550,11 +1576,11 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 4*m; + let idx = 4 * m; if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getInt32(offset+8) !== glUniform.bufferView[idx+2] || - glBlock.bufferView.getInt32(offset+12) !== glUniform.bufferView[idx+3]) { + glBlock.bufferView.getInt32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getInt32(offset + 8) !== glUniform.bufferView[idx + 2] || + glBlock.bufferView.getInt32(offset + 12) !== glUniform.bufferView[idx + 3]) { gl.uniform4iv(glUniform.glLoc, glUniform.bufferView); break; } @@ -1578,9 +1604,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 2*m; + let idx = 2 * m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1]) { + glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1]) { gl.uniform2fv(glUniform.glLoc, glUniform.bufferView); break; } @@ -1591,10 +1617,10 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_VEC3: { let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 3*m; + let idx = 3 * m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2]) { + glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2]) { gl.uniform3fv(glUniform.glLoc, glUniform.bufferView); break; } @@ -1605,11 +1631,11 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_VEC4: { let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 4*m; + let idx = 4 * m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || - glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3]) { + glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || + glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3]) { gl.uniform4fv(glUniform.glLoc, glUniform.bufferView); break; } @@ -1620,11 +1646,11 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_MAT2: { let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 4*m; + let idx = 4 * m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || - glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3]) { + glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || + glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3]) { gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); break; } @@ -1635,16 +1661,16 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_MAT3: { let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 9*m; + let idx = 9 * m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || - glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3] || - glBlock.bufferView.getFloat32(offset+16) !== glUniform.bufferView[idx+4] || - glBlock.bufferView.getFloat32(offset+20) !== glUniform.bufferView[idx+5] || - glBlock.bufferView.getFloat32(offset+24) !== glUniform.bufferView[idx+6] || - glBlock.bufferView.getFloat32(offset+28) !== glUniform.bufferView[idx+7] || - glBlock.bufferView.getFloat32(offset+32) !== glUniform.bufferView[idx+8]) { + glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || + glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3] || + glBlock.bufferView.getFloat32(offset + 16) !== glUniform.bufferView[idx + 4] || + glBlock.bufferView.getFloat32(offset + 20) !== glUniform.bufferView[idx + 5] || + glBlock.bufferView.getFloat32(offset + 24) !== glUniform.bufferView[idx + 6] || + glBlock.bufferView.getFloat32(offset + 28) !== glUniform.bufferView[idx + 7] || + glBlock.bufferView.getFloat32(offset + 32) !== glUniform.bufferView[idx + 8]) { gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.bufferView); break; } @@ -1655,23 +1681,23 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_MAT4: { let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m) { - let idx = 16*m; + let idx = 16 * m; if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset+4) !== glUniform.bufferView[idx+1] || - glBlock.bufferView.getFloat32(offset+8) !== glUniform.bufferView[idx+2] || - glBlock.bufferView.getFloat32(offset+12) !== glUniform.bufferView[idx+3] || - glBlock.bufferView.getFloat32(offset+16) !== glUniform.bufferView[idx+4] || - glBlock.bufferView.getFloat32(offset+20) !== glUniform.bufferView[idx+5] || - glBlock.bufferView.getFloat32(offset+24) !== glUniform.bufferView[idx+6] || - glBlock.bufferView.getFloat32(offset+28) !== glUniform.bufferView[idx+7] || - glBlock.bufferView.getFloat32(offset+32) !== glUniform.bufferView[idx+8] || - glBlock.bufferView.getFloat32(offset+36) !== glUniform.bufferView[idx+9] || - glBlock.bufferView.getFloat32(offset+40) !== glUniform.bufferView[idx+10] || - glBlock.bufferView.getFloat32(offset+44) !== glUniform.bufferView[idx+11] || - glBlock.bufferView.getFloat32(offset+48) !== glUniform.bufferView[idx+12] || - glBlock.bufferView.getFloat32(offset+52) !== glUniform.bufferView[idx+13] || - glBlock.bufferView.getFloat32(offset+56) !== glUniform.bufferView[idx+14] || - glBlock.bufferView.getFloat32(offset+60) !== glUniform.bufferView[idx+15]) { + glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || + glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || + glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3] || + glBlock.bufferView.getFloat32(offset + 16) !== glUniform.bufferView[idx + 4] || + glBlock.bufferView.getFloat32(offset + 20) !== glUniform.bufferView[idx + 5] || + glBlock.bufferView.getFloat32(offset + 24) !== glUniform.bufferView[idx + 6] || + glBlock.bufferView.getFloat32(offset + 28) !== glUniform.bufferView[idx + 7] || + glBlock.bufferView.getFloat32(offset + 32) !== glUniform.bufferView[idx + 8] || + glBlock.bufferView.getFloat32(offset + 36) !== glUniform.bufferView[idx + 9] || + glBlock.bufferView.getFloat32(offset + 40) !== glUniform.bufferView[idx + 10] || + glBlock.bufferView.getFloat32(offset + 44) !== glUniform.bufferView[idx + 11] || + glBlock.bufferView.getFloat32(offset + 48) !== glUniform.bufferView[idx + 12] || + glBlock.bufferView.getFloat32(offset + 52) !== glUniform.bufferView[idx + 13] || + glBlock.bufferView.getFloat32(offset + 56) !== glUniform.bufferView[idx + 14] || + glBlock.bufferView.getFloat32(offset + 60) !== glUniform.bufferView[idx + 15]) { gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.bufferView); break; } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index e5f64d981c..9b58cd1393 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,37 +1,37 @@ import { GFXDeviceInfo, GFXDevice } from '../device'; -import { GFXBuffer, GFXBufferInfo, GFXBufferUsageBit } from '../buffer'; +import { GFXBuffer, GFXBufferInfo } from '../buffer'; import { WebGLGFXBuffer } from './webgl-buffer'; import { WebGLGFXQueue } from './webgl-queue'; import { WebGLStateCache } from './webgl-state-cache'; import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember } from './webgl-commands'; -import { GFXTextureInfo, GFXTextureType, GFXTextureFlagBit, GFXTexture } from '../texture'; -import { GFXTextureViewType, GFXTextureViewInfo, GFXTextureView } from '../texture-view'; +import { GFXTexture, GFXTextureInfo } from '../texture'; +import { GFXTextureViewInfo, GFXTextureView } from '../texture-view'; import { GFXRenderPassInfo, GFXRenderPass } from '../render-pass'; import { GFXFramebufferInfo, GFXFramebuffer } from '../framebuffer'; import { WebGLGFXRenderPass } from './webgl-render-pass'; import { WebGLGFXTextureView } from './webgl-texture-view'; import { WebGLGFXTexture } from './webgl-texture'; -import { GFXShaderInfo, GFXShader } from '../shader'; -import { GFXSamplerInfo, GFXFilter, GFXSampler, GFXAddress } from '../sampler'; +import { GFXShader, GFXShaderInfo } from '../shader'; +import { GFXSamplerInfo, GFXSampler } from '../sampler'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; import { GFXInputAssemblerInfo, GFXInputAssembler } from '../input-assembler'; import { WebGLGFXShader } from './webgl-shader'; import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../command-allocator'; import { GFXPipelineStateInfo, GFXPipelineState } from '../pipeline-state'; import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; -import { GFXBindingLayoutInfo, GFXBindingUnit, GFXBindingType, GFXBindingLayout } from '../binding-layout'; +import { GFXBindingUnit, GFXBindingLayout, GFXBindingLayoutInfo } from '../binding-layout'; import { WebGLGFXSampler } from './webgl-sampler'; import { GFXCommandBufferInfo, GFXCommandBuffer } from '../command-buffer'; import { GFXQueueInfo, GFXQueue } from '../queue'; import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; import { WebGLGFXPipelineState } from './webgl-pipeline-state'; -import { GFXPipelineLayoutInfo, GFXPipelineLayout } from '../pipeline-layout'; +import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../pipeline-layout'; import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; -import { GFXWindowInfo, GFXWindow } from '../window'; +import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { BufferView } from '../define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit } from '../gfx-define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -61,12 +61,9 @@ const WebGLWraps: GLenum[] = [ export class WebGLGFXDevice extends GFXDevice { stateCache: WebGLStateCache = new WebGLStateCache; - //webGLCmdAllocator: WebGLGFXCommandAllocator; constructor() { super(); - - //this.webGLCmdAllocator = new WebGLGFXCommandAllocator(this); } public initialize(info: GFXDeviceInfo): boolean { @@ -157,6 +154,8 @@ export class WebGLGFXDevice extends GFXDevice { height: this._webGLRC.drawingBufferHeight, }); + this._cmdAllocator = this.createCommandAllocator({}); + return true; } @@ -167,6 +166,11 @@ export class WebGLGFXDevice extends GFXDevice { this._mainWindow = null; } + if (this._cmdAllocator) { + this._cmdAllocator.destroy(); + this._cmdAllocator = null; + } + this._webGLRC = null; } @@ -331,7 +335,7 @@ export class WebGLGFXDevice extends GFXDevice { return this._queue; } - public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer: BufferView | null): WebGLGPUBuffer | null { + public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer: ArrayBuffer | null): WebGLGPUBuffer | null { let gpuBuffer: WebGLGPUBuffer = { objType: WebGLGPUObjectType.BUFFER, @@ -346,8 +350,8 @@ export class WebGLGFXDevice extends GFXDevice { }; if (buffer) { - gpuBuffer.buffer = buffer.buffer; - gpuBuffer.bufferView = buffer; + gpuBuffer.buffer = buffer; + gpuBuffer.bufferView = new Uint8Array(gpuBuffer.buffer); } //let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; @@ -365,7 +369,7 @@ export class WebGLGFXDevice extends GFXDevice { WebGLCmdFuncDestroyBuffer(this, gpuBuffer); } - public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: BufferView) { + public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { // TODO: Async let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; let isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; @@ -472,8 +476,8 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { let gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, - colorAttachments: info.colorAttachment, - depthStencilAttachment: info.depthStencilAttachment, + colorAttachments: info.colorAttachment? info.colorAttachment : [], + depthStencilAttachment: info.depthStencilAttachment? info.depthStencilAttachment : null, } return gpuRenderPass; @@ -578,13 +582,12 @@ export class WebGLGFXDevice extends GFXDevice { for (let i = 0; i < info.stages.length; ++i) { let stage = info.stages[i]; - let gpuStage = gpuStages[i]; - gpuStage.type = stage.type; - gpuStage.source = stage.source; - - if (stage.macros) { - gpuStage.macros = stage.macros; - } + gpuStages[i] = { + type: stage.type, + source: stage.source, + macros: stage.macros? stage.macros : [], + glShader: 0, + }; } let gpuShader: WebGLGPUShader = { @@ -704,12 +707,6 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPUInputAssembler(info: GFXInputAssemblerInfo): WebGLGPUInputAssembler { - let gpuShader: WebGLGPUShader | null = null; - - if (info.shader) { - gpuShader = (info.shader).gpuShader; - } - let gpuVertexBuffers: WebGLGPUBuffer[] = new Array(info.vertexBuffers.length); for (let i = 0; i < info.vertexBuffers.length; ++i) { @@ -739,7 +736,6 @@ export class WebGLGFXDevice extends GFXDevice { let gpuInputAssembler: WebGLGPUInputAssembler = { objType: WebGLGPUObjectType.INPUT_ASSEMBLER, attributes: info.attributes, - gpuShader: gpuShader, gpuVertexBuffers: gpuVertexBuffers, gpuIndexBuffer: gpuIndexBuffer, diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index 08b306d902..eaec3dca2d 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -11,6 +11,8 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { public initialize(info : GFXFramebufferInfo) : boolean { + this._renderPass = info.renderPass; + if(info.colorViews) { this._colorViews = info.colorViews; } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 29a29dcdc6..dc33439b9b 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,12 +1,8 @@ -import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from "../buffer"; -import { GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit } from "../texture"; -import { GFXTextureViewType } from "../texture-view"; -import { GFXFormat, GFXType, BufferView } from "../define"; +import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage } from "../gfx-define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../render-pass"; -import { GFXShaderType, GFXShaderMacro, GFXUniformBlock, GFXUniformSampler } from "../shader"; -import { GFXBindingType } from "../binding-layout"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; import { GFXInputAttribute } from "../input-assembler"; +import { GFXUniformBlock, GFXUniformSampler, GFXShaderMacro } from "../shader"; export enum WebGLGPUObjectType { UNKNOWN, @@ -40,7 +36,7 @@ export class WebGLGPUBuffer extends WebGLGPUObject { glTarget: GLenum = 0; glBuffer: WebGLBuffer = 0; buffer: ArrayBuffer | null = null; - bufferView: BufferView | null = null; + bufferView: Uint8Array | null = null; constructor() { super(WebGLGPUObjectType.BUFFER); @@ -245,7 +241,6 @@ export class WebGLAttrib { export class WebGLGPUInputAssembler extends WebGLGPUObject { attributes: GFXInputAttribute[] = []; - gpuShader: WebGLGPUShader | null = null; gpuVertexBuffers: WebGLGPUBuffer[] = []; gpuIndexBuffer: WebGLGPUBuffer | null = null; diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts index e35e1090ce..85f92c6cb2 100644 --- a/cocos/gfx/webgl/webgl-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -1,7 +1,8 @@ import { GFXDevice } from '../device'; -import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../pipeline-layout'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUPipelineLayout } from './webgl-gpu-objects'; +import { GFXPipelineLayout } from '../pipeline-layout'; +import { GFXPipelineLayoutInfo } from '../binding-layout'; export class WebGLGFXPipelineLayout extends GFXPipelineLayout { diff --git a/cocos/gfx/webgl/webgl-queue.ts b/cocos/gfx/webgl/webgl-queue.ts index 3e7be907f4..a6122ec847 100644 --- a/cocos/gfx/webgl/webgl-queue.ts +++ b/cocos/gfx/webgl/webgl-queue.ts @@ -22,7 +22,7 @@ export class WebGLGFXQueue extends GFXQueue { } - public submit(cmdBuffs: GFXCommandBuffer[], fence: null = null) { + public submit(cmdBuffs: GFXCommandBuffer[], fence?) { // TODO: Async if (!this._isAsync) { diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts index 46fe4be4c4..04fbd725eb 100644 --- a/cocos/gfx/webgl/webgl-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -1,8 +1,6 @@ import { GFXDevice } from '../device'; -import { WebGLGPUTexture, WebGLGPURenderPass } from './webgl-gpu-objects'; +import { WebGLGPURenderPass } from './webgl-gpu-objects'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../texture'; -import { GFXFormatSurfaceSize } from '../define'; import { GFXRenderPass, GFXRenderPassInfo } from '../render-pass'; export class WebGLGFXRenderPass extends GFXRenderPass { @@ -13,8 +11,13 @@ export class WebGLGFXRenderPass extends GFXRenderPass { public initialize(info: GFXRenderPassInfo): boolean { - this._colorInfos = info.colorAttachment; - this._depthStencilInfo = info.depthStencilAttachment; + if (info.colorAttachment) { + this._colorInfos = info.colorAttachment; + } + + if (info.depthStencilAttachment) { + this._depthStencilInfo = info.depthStencilAttachment; + } this._gpuRenderPass = this.webGLDevice.emitCmdCreateGPURenderPass(info); diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts index d4bb5d4484..575ca6fce7 100644 --- a/cocos/gfx/webgl/webgl-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -1,5 +1,5 @@ import { GFXDevice } from '../device'; -import { GFXSampler, GFXSamplerInfo } from '../sampler'; +import { GFXSampler, GFXSamplerInfo, GFXSamplerState } from '../sampler'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUSampler } from './webgl-gpu-objects'; @@ -7,11 +7,64 @@ export class WebGLGFXSampler extends GFXSampler { constructor(device : GFXDevice) { super(device); + + this._state = new GFXSamplerState; } public initialize(info : GFXSamplerInfo) : boolean { - this._state = info; + if(info.name) { + this._state.name = info.name; + } + + if(info.minFilter) { + this._state.minFilter = info.minFilter; + } + + if(info.magFilter) { + this._state.magFilter = info.magFilter; + } + + if(info.mipFilter) { + this._state.mipFilter = info.mipFilter; + } + + if(info.addressU) { + this._state.addressU = info.addressU; + } + + if(info.addressV) { + this._state.addressV = info.addressV; + } + + if(info.addressW) { + this._state.addressW = info.addressW; + } + + if(info.maxAnisotropy) { + this._state.maxAnisotropy = info.maxAnisotropy; + } + + if(info.cmpFunc) { + this._state.cmpFunc = info.cmpFunc; + } + + if(info.borderColor) { + this._state.borderColor = info.borderColor; + } + + if(info.minLOD) { + this._state.minLOD = info.minLOD; + } + + if(info.maxLOD) { + this._state.maxLOD = info.maxLOD; + } + + if(info.mipLODBias) { + this._state.mipLODBias = info.mipLODBias; + } + this._gpuSampler = this.webGLDevice.emitCmdCreateGPUSampler(info); return true; diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts index 990b574022..ea478eff1d 100644 --- a/cocos/gfx/webgl/webgl-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -11,10 +11,7 @@ export class WebGLGFXShader extends GFXShader { public initialize(info: GFXShaderInfo): boolean { - if (info.name) { - this._name = info.name; - } - + this._name = info.name; this._stages = info.stages; this._blocks = info.blocks; this._samplers = info.samplers; diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index dde193308f..cb79db0312 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -1,4 +1,4 @@ -import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES } from "../define"; +import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES, GFXViewport, GFXRect } from "../gfx-define"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; export interface WebGLTexUnit @@ -20,8 +20,8 @@ export class WebGLStateCache { glTex2DUnits : WebGLTexUnit[]; glTexCubeUnits : WebGLTexUnit[]; glFramebuffer : WebGLFramebuffer = 0; - viewport : number[] = [0.0, 0.0, 0.0, 0.0]; - scissorRect : number[] = [0.0, 0.0, 0.0, 0.0]; + viewport : GFXViewport; + scissorRect : GFXRect; rs : GFXRasterizerState; dss : GFXDepthStencilState; bs : GFXBlendState; @@ -32,6 +32,8 @@ export class WebGLStateCache { constructor() { this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.viewport = { left: 0.0, top: 0.0, width: 0.0, height: 0.0, minDepth: 0.0, maxDepth: 0.0}; + this.scissorRect = { left: 0.0, top: 0.0, width: 0.0, height: 0.0}; this.rs = new GFXRasterizerState; this.dss = new GFXDepthStencilState; this.bs = new GFXBlendState; diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index b2133a8c22..04a30fe713 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -1,8 +1,8 @@ import { GFXDevice } from '../device'; import { WebGLGPUTexture } from './webgl-gpu-objects'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXTexture, GFXTextureInfo, GFXTextureFlagBit } from '../texture'; -import { GFXFormatSurfaceSize } from '../define'; +import { GFXTexture, GFXTextureInfo } from '../texture'; +import { GFXFormatSurfaceSize, GFXTextureFlagBit } from '../gfx-define'; export class WebGLGFXTexture extends GFXTexture { diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index e4d0349622..95f599767d 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -1,11 +1,7 @@ import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { GFXWindow, GFXWindowInfo } from '../window'; -import { GFXFramebufferInfo } from '../framebuffer'; -import { GFXRenderPassInfo, GFXColorAttachment, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint, GFXDepthStencilAttachment } from '../render-pass'; -import { GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit } from '../texture'; -import { GFXTextureViewType } from '../texture-view'; -import { GFXFormat } from '../define'; +import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXStoreOp } from '../gfx-define'; export class WebGLGFXWindow extends GFXWindow { diff --git a/cocos/gfx/window.ts b/cocos/gfx/window.ts index f4f60e6ee3..a84949d57e 100644 --- a/cocos/gfx/window.ts +++ b/cocos/gfx/window.ts @@ -2,7 +2,7 @@ import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; import { GFXTexture } from './texture'; import { GFXTextureView } from './texture-view'; -import { GFXFormat } from './define'; +import { GFXFormat } from './gfx-define'; import { GFXRenderPass } from './render-pass'; export interface GFXWindowInfo { diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 24db73d32c..7c68d890da 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,6 +1,10 @@ import { RenderFlow, RenderFlowInfo } from "../render-flow"; -import { GFXRenderPass } from "../../gfx/gfx-render-pass"; import { RenderPipeline } from "../render-pipeline"; +import { TestStage } from "./test-stage"; + +export enum ForwardStagePriority { + FORWARD = 0, +}; export class ForwardFlow extends RenderFlow { @@ -9,27 +13,36 @@ export class ForwardFlow extends RenderFlow { } public initialize(info: RenderFlowInfo): boolean { - - if(info.name) { + + if (info.name) { this._name = info.name; } this._priority = info.priority; - let device = this._pipeline.root.device; - if(!device) { + let mainWindow = this._pipeline.root.mainWindow; + if(!mainWindow || !mainWindow.framebuffer) { return false; } - //this._pipeline.root.mainWindow; - //this._renderPass = - + /* + this.createStage(ForwardStage, { + name: "ForwardStage", + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + */ + + this.createStage(TestStage, { + name: "TestStage", + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + return true; } public destroy(): void { this.destroyStages(); } - - private _renderPass: GFXRenderPass | null = null; }; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index a0f88066d9..ba1f6b932e 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -1,5 +1,11 @@ -import { RenderPipeline } from "../render-pipeline"; -import { Root } from "../../../core/root"; +import { RenderPipeline, RenderPassStage } from "../render-pipeline"; +import { Root } from "../../core/root"; +import { ForwardFlow } from "./forward-flow"; +import { GFXRenderPass } from "../../gfx/render-pass"; + +export enum ForwardFlowPriority { + FORWARD = 0, +}; export class ForwardPipeline extends RenderPipeline { @@ -9,10 +15,37 @@ export class ForwardPipeline extends RenderPipeline { public initialize(): boolean { + if(!this.createQuadInputAssembler()) { + return false; + } + + let mainWindow = this._root.mainWindow; + let windowPass: GFXRenderPass | null = null; + + if(mainWindow) { + windowPass = mainWindow.renderPass; + } + + if(!windowPass) { + console.error("RenderPass of main window is null."); + return false; + } + + this.addRenderPass(RenderPassStage.FORWARD, windowPass); + + // create flows + + this.createFlow(ForwardFlow, { + name: "ForwardFlow", + priority: ForwardFlowPriority.FORWARD, + }); + return true; } public destroy(): void { this.destroyFlows(); + this.clearRenderPasses(); + this.destroyQuadInputAssembler(); } }; diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index dc2cc64ada..a8e34bc09a 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -1,16 +1,53 @@ import { RenderStage, RenderStageInfo } from "../render-stage"; +import { RenderFlow } from "../render-flow"; +import { GFXCommandBuffer } from "../../gfx/command-buffer"; +import { RenderView } from "../render-view"; +import { GFXFramebuffer } from "../../gfx/framebuffer"; +import { GFXCommandBufferType } from "../../gfx/gfx-define"; +import { GFXInputAssembler } from "../../gfx/input-assembler"; export class ForwardStage extends RenderStage { + constructor(flow: RenderFlow) { + super(flow); + } + public initialize(info: RenderStageInfo): boolean { + + if(info.name) { + this._name = info.name; + } + + this._priority = info.priority; + this._framebuffer = info.framebuffer; + + this._cmdBuff = this._device.createCommandBuffer({ + allocator: this._device.commandAllocator, + type: GFXCommandBufferType.PRIMARY, + }); + return true; } public destroy() { + if (this._cmdBuff) { + this._cmdBuff.destroy(); + this._cmdBuff = null; + } } - public render() { + public render(view: RenderView) { + let cmdBuff = this._cmdBuff; + this._renderArea.width = view.width; + this._renderArea.height = view.height; + cmdBuff.begin(); + cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); + cmdBuff.draw(this._pipeline.quadIA); + cmdBuff.endRenderPass(); + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); } }; diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts new file mode 100644 index 0000000000..8887fe1588 --- /dev/null +++ b/cocos/pipeline/forward/test-stage.ts @@ -0,0 +1,156 @@ +import { RenderStage, RenderStageInfo } from "../render-stage"; +import { RenderFlow } from "../render-flow"; +import { GFXCommandBuffer } from "../../gfx/command-buffer"; +import { RenderView } from "../render-view"; +import { GFXFramebuffer } from "../../gfx/framebuffer"; +import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode } from "../../gfx/gfx-define"; +import { GFXInputAssembler } from "../../gfx/input-assembler"; +import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; +import { GFXShader } from "../../gfx/shader"; +import { GFXRenderPass } from "../../gfx/render-pass"; +import { GFXPipelineLayout } from "../../gfx/pipeline-layout"; +import { GFXBindingLayout } from "../../gfx/binding-layout"; + +let _shader_vs =` +attribute vec2 a_position; +attribute vec2 a_texCoord; +void main() { + gl_Position = vec4(a_position, 0.0, 1.0); +} +`; + +let _shader_fs =` +void main() { + gl_FragColor = vec4(0.3, 0.3, 0.8, 1.0); +}\n +`; + +export class TestStage extends RenderStage { + + constructor(flow: RenderFlow) { + super(flow); + } + + public initialize(info: RenderStageInfo): boolean { + + if (info.name) { + 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 + let vsStage = { + type: GFXShaderType.VERTEX, + source: _shader_vs, + }; + + let fsStage = { + type: GFXShaderType.FRAGMENT, + source: _shader_fs, + }; + + this._shader = this._device.createShader({ + name: "test", + stages: [vsStage, fsStage], + }); + if (!this._shader) { + return false; + } + + this._bindingLayout = this._device.createBindingLayout({ + bindings: [], + }); + if (!this._bindingLayout) { + return false; + } + + this._pipelineLayout = this._device.createPipelineLayout({ + layouts: [this._bindingLayout] + }); + if (!this._pipelineLayout) { + return false; + } + + if (!this._pipeline.quadIA) { + return false; + } + + let is: GFXInputState = { attributes: this._pipeline.quadIA.attributes }; + + this._pipelineState = this._device.createPipelineState({ + primitive: GFXPrimitiveMode.TRIANGLE_LIST, + shader: this._shader, + is: is, + rs: this._rs, + dss: this._dss, + bs: this._bs, + layout: this._pipelineLayout, + renderPass: this._framebuffer.renderPass, + }); + + return true; + } + + public destroy() { + + if (this._shader) { + this._shader.destroy(); + this._shader = 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) { + let cmdBuff = this._cmdBuff; + this._renderArea.width = view.width; + this._renderArea.height = view.height; + + cmdBuff.begin(); + cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); + cmdBuff.bindBindingLayout(this._bindingLayout); + cmdBuff.bindPipelineState(this._pipelineState); + cmdBuff.bindInputAssembler(this._pipeline.quadIA); + cmdBuff.draw(this._pipeline.quadIA); + cmdBuff.endRenderPass(); + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + } + + 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; +}; diff --git a/cocos/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts index 2e83e6062d..714802c72d 100644 --- a/cocos/pipeline/render-flow.ts +++ b/cocos/pipeline/render-flow.ts @@ -1,6 +1,8 @@ import { RenderStage, RenderStageInfo } from "./render-stage"; import { RenderView } from "./render-view"; import { RenderPipeline } from "./render-pipeline"; +import { GFXRenderPass } from "../gfx/render-pass"; +import { GFXDevice } from "../gfx/device"; export interface RenderFlowInfo { name?: string; @@ -10,6 +12,7 @@ export interface RenderFlowInfo { export abstract class RenderFlow { constructor(pipeline: RenderPipeline) { + this._device = pipeline.device; this._pipeline = pipeline; } @@ -47,10 +50,19 @@ export abstract class RenderFlow { this._stages = []; } + public get device(): GFXDevice { + return this._device; + } + + public get pipeline(): RenderPipeline { + return this._pipeline; + } + public get priority(): number { return this._priority; } + protected _device: GFXDevice; protected _pipeline: RenderPipeline; protected _name: string = ""; protected _priority: number = 0; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 3915757ddb..fb09846e29 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,12 +1,27 @@ import { RenderView } from "./render-view"; import { RenderFlow, RenderFlowInfo } from "./render-flow"; -import { GFXDevice } from "../gfx/gfx-device"; -import { Root } from "../../core/root"; +import { Root } from "../core/root"; +import { GFXRenderPass, GFXRenderPassInfo } from "../gfx/render-pass"; +import { GFXDevice } from "../gfx/device"; +import { GFXBuffer } from "../gfx/buffer"; +import { GFXInputAssembler, GFXInputAttribute } from "../gfx/input-assembler"; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXVertexSemantic, GFXFormat } from "../gfx/gfx-define"; + +export enum RenderPassStage { + FORWARD = 0, + CUSTOM = 100, +}; + +export interface QuadVertex { + position: number[]; + texCoord: number[]; +} export abstract class RenderPipeline { constructor(root: Root) { this._root = root; + this._device = root.device; } public abstract initialize(): boolean; @@ -19,7 +34,29 @@ export abstract class RenderPipeline { } public resize(width, height) { + } + public addRenderPass(stage: number, renderPass: GFXRenderPass) { + if (renderPass) { + this._renderPasses.set(stage, renderPass); + } + } + + public getRenderPass(stage: number): GFXRenderPass | null { + let renderPass = this._renderPasses.get(stage); + if (renderPass) { + return renderPass; + } else { + return null; + } + } + + public removeRenderPass(stage: number) { + this._renderPasses.delete(stage); + } + + public clearRenderPasses() { + this._renderPasses.clear(); } public createFlow(clazz: new (pipeline: RenderPipeline) => T, info: RenderFlowInfo): RenderFlow | null { @@ -47,10 +84,104 @@ export abstract class RenderPipeline { return this._root; } + public get device(): GFXDevice { + return this._device; + } + public get flows(): RenderFlow[] { return this._flows; } + public get quadIA(): GFXInputAssembler | null { + return this._quadIA; + } + + protected createQuadInputAssembler(): boolean { + + // create vertex buffer + + let vbStride = Float32Array.BYTES_PER_ELEMENT * 4; + let vbSize = vbStride * 4; + + this._quadVB = this._device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vbSize, + stride: vbStride, + }); + + if(!this._quadVB) { + return false; + } + + let verts = new Float32Array(4 * 4); + let n = 0; + verts[n++] = -1.0; verts[n++] = -1.0; verts[n++] = 0.0; verts[n++] = 0.0; + verts[n++] = 1.0; verts[n++] = -1.0; verts[n++] = 1.0; verts[n++] = 0.0; + verts[n++] = -1.0; verts[n++] = 1.0; verts[n++] = 0.0; verts[n++] = 1.0; + verts[n++] = 1.0; verts[n++] = 1.0; verts[n++] = 1.0; verts[n++] = 1.0; + + this._quadVB.update(verts); + + // create index buffer + let ibStride = Uint8Array.BYTES_PER_ELEMENT; + let ibSize = ibStride * 6; + + this._quadIB = this._device.createBuffer({ + usage: GFXBufferUsageBit.INDEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: ibSize, + stride: ibStride, + }); + + if(!this._quadIB) { + return false; + } + + let indices = new Uint8Array(6); + indices[0] = 0; indices[1] = 1; indices[2] = 2; + indices[3] = 1; indices[4] = 3; indices[5] = 2; + + this._quadIB.update(indices); + + // create input assembler + + let attributes: GFXInputAttribute[] = [ + {name: "a_position", semantic: GFXVertexSemantic.POSITION, format: GFXFormat.RG32F}, + {name: "a_texCoord", semantic: GFXVertexSemantic.TEXCOORD, format: GFXFormat.RG32F}, + ]; + + this._quadIA = this._device.createInputAssembler({ + attributes, + vertexBuffers: [this._quadVB], + indexBuffer: this._quadIB, + }); + + return true; + } + + protected destroyQuadInputAssembler() { + if(this._quadVB) { + this._quadVB.destroy(); + this._quadVB = null; + } + + if(this._quadIB) { + this._quadIB.destroy(); + this._quadIB = null; + } + + if(this._quadIA) { + this._quadIA.destroy(); + this._quadIA = null; + } + } + protected _root: Root; + protected _device: GFXDevice; + protected _renderPasses: Map = new Map; protected _flows: RenderFlow[] = []; + protected _quadVB: GFXBuffer | null = null; + protected _quadIB: GFXBuffer | null = null; + protected _quadIA: GFXInputAssembler | null = null; }; diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index 10e907787d..d0e9ee46f6 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -1,28 +1,90 @@ import { RenderView } from "./render-view"; -import { GFXRenderPass } from "../../gfx/render-pass"; -import { GFXFramebuffer } from "../../gfx/framebuffer"; +import { GFXRenderPass } from "../gfx/render-pass"; +import { GFXFramebuffer } from "../gfx/framebuffer"; +import { GFXCommandBuffer } from "../gfx/command-buffer"; +import { RenderFlow } from "./render-flow"; +import { GFXDevice } from "../gfx/device"; +import { RenderPipeline } from "./render-pipeline"; +import { GFXColor, GFX_MAX_ATTACHMENTS, GFXRect } from "../gfx/gfx-define"; export interface RenderStageInfo { name?: string; priority: number; - renderPass: GFXRenderPass; framebuffer: GFXFramebuffer; }; export abstract class RenderStage { + constructor(flow: RenderFlow) { + this._flow = flow; + this._pipeline = flow.pipeline; + this._device = flow.device; + + if (!this._flow.pipeline.root.device) { + throw new Error(""); + } + + this._device = this._flow.pipeline.root.device; + + this._clearColors = new Array(GFX_MAX_ATTACHMENTS); + for (let i = 0; i < GFX_MAX_ATTACHMENTS; ++i) { + this._clearColors[i] = { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }; + } + + this._renderArea = {left: 0, top: 0, width: 0, height: 0}; + } + public abstract initialize(info: RenderStageInfo): boolean; public abstract destroy(); public abstract render(view: RenderView); public resize(width, height) { - + + } + + public setClearColor(idx: number, color: GFXColor) { + console.assert(idx < GFX_MAX_ATTACHMENTS); + this._clearColors[idx] = color; + } + + public setClearDepth(depth: number) { + this._clearDepth = depth; + } + + public setClearStencil(stencil: number) { + this._clearStencil = stencil; + } + + public setRenderArea(width: number, height: number) { + this._renderArea.width = width; + this._renderArea.height = height; + } + + public get flow(): RenderFlow { + return this._flow; + } + + public get pipeline(): RenderPipeline { + return this._pipeline; } public get priority(): number { return this._priority; } + public get framebuffer(): GFXFramebuffer | null { + return this._framebuffer; + } + + protected _flow: RenderFlow; + protected _pipeline: RenderPipeline; + protected _device: GFXDevice; protected _name: string = ""; protected _priority: number = 0; + protected _framebuffer: GFXFramebuffer | null = null; + protected _cmdBuff: GFXCommandBuffer | null = null; + protected _clearColors: GFXColor[]; + protected _clearDepth: number = 1.0; + protected _clearStencil: number = 0; + protected _renderArea: GFXRect; }; diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index 849d500612..7e3fab45d4 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -1,6 +1,6 @@ -import { Scene } from "../scene/scene"; -import { Camera } from "../scene/camera"; -import { GFXWindow } from "../gfx/gfx-window"; +import { Scene } from "../renderer/scene/scene"; +import { Camera } from "../renderer/scene/camera"; +import { GFXWindow } from "../gfx/window"; export interface RenderViewInfo { window: GFXWindow; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 833363baea..93b21bb1e7 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -5,8 +5,9 @@ import { GFXBuffer } from '../../gfx/buffer'; import { GFXSampler } from '../../gfx/sampler'; import { GFXDevice } from '../../gfx/device'; import { GFXDepthStencilAttachment, GFXColorAttachment } from '../../gfx/render-pass'; -import { GFXPipelineState, GFXPrimitiveMode, GFXRasterizerState, GFXDepthStencilState, GFXBlendState, GFXInputState } from '../../gfx/pipeline-state'; +import { GFXPipelineState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState, GFXInputState } from '../../gfx/pipeline-state'; import { GFXBindingLayoutInfo } from '../../gfx/binding-layout'; +import { GFXPrimitiveMode } from '../../gfx/gfx-define'; interface PassInfo { programName?: string; diff --git a/cocos/renderer/pipeline/forward/forward-flow.ts b/cocos/renderer/pipeline/forward/forward-flow.ts deleted file mode 100644 index fcc8cb7dfb..0000000000 --- a/cocos/renderer/pipeline/forward/forward-flow.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { RenderPipeline } from "../../../pipeline/render-pipeline"; -import { RenderFlow, RenderFlowInfo } from "../../../pipeline/render-flow"; -import { GFXRenderPass } from "../../../gfx/render-pass"; - -export class ForwardFlow extends RenderFlow { - - constructor(pipeline: RenderPipeline) { - super(pipeline); - } - - public initialize(info: RenderFlowInfo): boolean { - - if(info.name) { - this._name = info.name; - } - - this._priority = info.priority; - - let device = this._pipeline.root.device; - if(!device) { - return false; - } - - //this._pipeline.root.mainWindow; - //this._renderPass = - - return true; - } - - public destroy(): void { - this.destroyStages(); - } - - private _renderPass: GFXRenderPass | null = null; -}; diff --git a/cocos/renderer/pipeline/forward/forward-pipeline.ts b/cocos/renderer/pipeline/forward/forward-pipeline.ts deleted file mode 100644 index 0bcf0e3b88..0000000000 --- a/cocos/renderer/pipeline/forward/forward-pipeline.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Root } from "../../../core/root"; -import { RenderPipeline } from "../../../pipeline/render-pipeline"; - -export class ForwardPipeline extends RenderPipeline { - - constructor(root: Root) { - super(root); - } - - public initialize(): boolean { - - return true; - } - - public destroy(): void { - this.destroyFlows(); - } -}; From 01a2b85f5b119cc8efd664c45fa080bf3b5660e4 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 12:30:42 +0800 Subject: [PATCH 016/267] bind vertex attribute location by builtin name --- cocos/core/CCDirector.js | 2 + cocos/gfx/gfx-define.ts | 22 +++++++++ cocos/gfx/webgl/webgl-commands.ts | 69 +++++++++++++++++++++++++--- cocos/gfx/webgl/webgl-gpu-objects.ts | 3 +- 4 files changed, 89 insertions(+), 7 deletions(-) diff --git a/cocos/core/CCDirector.js b/cocos/core/CCDirector.js index 8f2b92ceb1..e9f488970b 100644 --- a/cocos/core/CCDirector.js +++ b/cocos/core/CCDirector.js @@ -195,6 +195,7 @@ class Director extends EventTarget { // this.registerSystem('animation', AnimationSystem, ['AnimationComponent'], 200); // this.registerSystem('skinning-model', SkinningModelSystem, ['SkinningModelComponent'], 100); // init renderSystem + /* { this._renderSystem = new RenderSystem(); let renderComps = ['cc.CameraComponent']; @@ -202,6 +203,7 @@ class Director extends EventTarget { getClassByName(compName).system = this._renderSystem; }); } + */ { this._physicsSystem = new PhysicsSystem(); diff --git a/cocos/gfx/gfx-define.ts b/cocos/gfx/gfx-define.ts index 10c5688270..0c986970ef 100644 --- a/cocos/gfx/gfx-define.ts +++ b/cocos/gfx/gfx-define.ts @@ -22,6 +22,28 @@ export const GFX_MAX_VERTEX_ATTRIBUTES: number = 8; export const GFX_MAX_TEXTURE_UNITS: number = 16; export const GFX_MAX_ATTACHMENTS: number = 4; +export const GFX_ATTRIBUTE_POSITION = "a_position"; +export const GFX_ATTRIBUTE_POSITION1 = "a_position1"; +export const GFX_ATTRIBUTE_POSITION2 = "a_position2"; +export const GFX_ATTRIBUTE_POSITION3 = "a_position3"; +export const GFX_ATTRIBUTE_COLOR = "a_color"; +export const GFX_ATTRIBUTE_COLOR1 = "a_color1"; +export const GFX_ATTRIBUTE_COLOR2 = "a_color2"; +export const GFX_ATTRIBUTE_COLOR3 = "a_color3"; +export const GFX_ATTRIBUTE_NORMAL = "a_normal"; +export const GFX_ATTRIBUTE_NORMAL1 = "a_normal1"; +export const GFX_ATTRIBUTE_NORMAL2 = "a_normal2"; +export const GFX_ATTRIBUTE_NORMAL3 = "a_normal3"; +export const GFX_ATTRIBUTE_TANGENT = "a_tangent"; +export const GFX_ATTRIBUTE_BINORMAL = "a_binormal"; +export const GFX_ATTRIBUTE_TEXCOORD = "a_texCoord"; +export const GFX_ATTRIBUTE_TEXCOORD1 = "a_texCoord1"; +export const GFX_ATTRIBUTE_TEXCOORD2 = "a_texCoord2"; +export const GFX_ATTRIBUTE_TEXCOORD3 = "a_texCoord3"; +export const GFX_ATTRIBUTE_JOINTS = "a_joints"; +export const GFX_ATTRIBUTE_WEIGHTS = "a_weights"; +export const GFX_ATTRIBUTE_SV_INSTANCE_ID = "sv_instanceID"; + export enum GFXType { UNKNOWN, BOOL, diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index b51b9b920f..bc0fa08fc1 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,6 +1,6 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXViewport, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit } from "../gfx-define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXViewport, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFX_ATTRIBUTE_POSITION, GFXVertexSemantic, GFX_ATTRIBUTE_POSITION1, GFX_ATTRIBUTE_POSITION2, GFX_ATTRIBUTE_POSITION3, GFX_ATTRIBUTE_COLOR, GFX_ATTRIBUTE_COLOR1, GFX_ATTRIBUTE_COLOR2, GFX_ATTRIBUTE_COLOR3, GFX_ATTRIBUTE_NORMAL, GFX_ATTRIBUTE_NORMAL1, GFX_ATTRIBUTE_NORMAL2, GFX_ATTRIBUTE_NORMAL3, GFX_ATTRIBUTE_TEXCOORD, GFX_ATTRIBUTE_TEXCOORD1, GFX_ATTRIBUTE_TEXCOORD2, GFX_ATTRIBUTE_TEXCOORD3, GFX_ATTRIBUTE_JOINTS, GFX_ATTRIBUTE_WEIGHTS, GFX_ATTRIBUTE_SV_INSTANCE_ID, GFX_ATTRIBUTE_TANGENT, GFX_ATTRIBUTE_BINORMAL } from "../gfx-define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; @@ -810,8 +810,6 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG for (let i = 0; i < activeAttribCount; ++i) { let info = gl.getActiveAttrib(gpuShader.glProgram, i); if (info) { - let glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); - let varName: string; let nameOffset = info.name.indexOf('['); if (nameOffset !== -1) { @@ -820,6 +818,64 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG varName = info.name; } + let semantic = GFXVertexSemantic.UNKNOWN; + let glLoc = -1; + + if (varName === GFX_ATTRIBUTE_POSITION) { + semantic = GFXVertexSemantic.POSITION; + } else if (varName === GFX_ATTRIBUTE_POSITION1) { + semantic = GFXVertexSemantic.POSITION1; + } else if (varName === GFX_ATTRIBUTE_POSITION2) { + semantic = GFXVertexSemantic.POSITION2; + } else if (varName === GFX_ATTRIBUTE_POSITION3) { + semantic = GFXVertexSemantic.POSITION3; + } else if (varName === GFX_ATTRIBUTE_COLOR) { + semantic = GFXVertexSemantic.COLOR; + } else if (varName === GFX_ATTRIBUTE_COLOR1) { + semantic = GFXVertexSemantic.COLOR1; + } else if (varName === GFX_ATTRIBUTE_COLOR2) { + semantic = GFXVertexSemantic.COLOR2; + } else if (varName === GFX_ATTRIBUTE_COLOR3) { + semantic = GFXVertexSemantic.COLOR3; + } else if (varName === GFX_ATTRIBUTE_NORMAL) { + semantic = GFXVertexSemantic.NORMAL; + } else if (varName === GFX_ATTRIBUTE_NORMAL1) { + semantic = GFXVertexSemantic.NORMAL1; + } else if (varName === GFX_ATTRIBUTE_NORMAL2) { + semantic = GFXVertexSemantic.NORMAL2; + } else if (varName === GFX_ATTRIBUTE_NORMAL3) { + semantic = GFXVertexSemantic.NORMAL3; + } else if (varName === GFX_ATTRIBUTE_TANGENT) { + semantic = GFXVertexSemantic.TANGENT; + } else if (varName === GFX_ATTRIBUTE_BINORMAL) { + semantic = GFXVertexSemantic.BINORMAL; + } else if (varName === GFX_ATTRIBUTE_TEXCOORD) { + semantic = GFXVertexSemantic.TEXCOORD; + } else if (varName === GFX_ATTRIBUTE_TEXCOORD1) { + semantic = GFXVertexSemantic.TEXCOORD1; + } else if (varName === GFX_ATTRIBUTE_TEXCOORD2) { + semantic = GFXVertexSemantic.TEXCOORD2; + } else if (varName === GFX_ATTRIBUTE_TEXCOORD3) { + semantic = GFXVertexSemantic.TEXCOORD3; + } else if (varName === GFX_ATTRIBUTE_JOINTS) { + semantic = GFXVertexSemantic.JOINTS; + } else if (varName === GFX_ATTRIBUTE_WEIGHTS) { + semantic = GFXVertexSemantic.WEIGHTS; + } else if (varName === GFX_ATTRIBUTE_SV_INSTANCE_ID) { + semantic = GFXVertexSemantic.SV_INSTANCE_ID; + } else { + console.error("Unsupported vertex attribute semantic."); + } + + if(semantic !== GFXVertexSemantic.UNKNOWN) { + glLoc = semantic; + gl.bindAttribLocation(gpuShader.glProgram, glLoc, varName); + + } else { + glLoc = -1; + //glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); + } + let type = WebGLTypeToGFXType(info.type); let stride = WebGLGetTypeSize(info.type); @@ -830,6 +886,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG stride: stride, count: info.size, size: stride * info.size, + semantic: semantic, glType: info.type, glLoc: glLoc, @@ -993,14 +1050,14 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput let offsets = [0, 0, 0, 0, 0, 0, 0, 0]; - for(let i = 0; i < gpuInputAssembler.attributes.length; ++i) { + for (let i = 0; i < gpuInputAssembler.attributes.length; ++i) { let attrib = gpuInputAssembler.attributes[i]; let stream = attrib.stream ? attrib.stream : 0; //if (stream < gpuInputAssembler.gpuVertexBuffers.length) { let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; - + let glType = GFXFormatToWebGLType(attrib.format, device); let size = WebGLGetTypeSize(glType); @@ -1012,7 +1069,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput count: GFXFormatInfos[attrib.format].count, stride: gpuBuffer.stride, componentCount: WebGLGetComponentCount(glType), - isInstanced: attrib.isInstanced? attrib.isInstanced : false, + isInstanced: attrib.isInstanced ? attrib.isInstanced : false, offset: offsets[stream], }; diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index dc33439b9b..9c3258c502 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage } from "../gfx-define"; +import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage, GFXVertexSemantic } from "../gfx-define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../render-pass"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; import { GFXInputAttribute } from "../input-assembler"; @@ -126,6 +126,7 @@ export class WebGLGPUInput { stride: number = 0; count: number = 0; size: number = 0; + semantic: GFXVertexSemantic = GFXVertexSemantic.UNKNOWN; glType: GLenum = 0; glLoc: GLint = 0; From 56b53b2298f644dc52ddfa4891e539b32a1d8c16 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 15:28:51 +0800 Subject: [PATCH 017/267] add a new scene manager --- cocos/core/CCDirector.js | 4 + cocos/core/root.ts | 62 ++++++++++------ cocos/pipeline/render-view.ts | 47 +++++++++--- cocos/renderer/scene/camera.js | 14 +++- cocos/renderer/scene/light.js | 14 +++- cocos/scene/scene-manager.ts | 131 +++++++++++++++++++++++++++++++++ 6 files changed, 237 insertions(+), 35 deletions(-) create mode 100644 cocos/scene/scene-manager.ts diff --git a/cocos/core/CCDirector.js b/cocos/core/CCDirector.js index e9f488970b..db624a218e 100644 --- a/cocos/core/CCDirector.js +++ b/cocos/core/CCDirector.js @@ -711,6 +711,10 @@ class Director extends EventTarget { cc.Camera.main.backgroundColor = clearColor; } + get root() { + return this._root; + } + /** * !#en Returns current logic Scene. * !#zh 获取当前逻辑场景。 diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 2ca0b18756..6cf372bb49 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,13 +1,17 @@ -import Scene from "../renderer/scene/scene"; import { GFXWindow, GFXWindowInfo } from "../gfx/window"; import { GFXDevice } from "../gfx/device"; -import { RenderView, RenderViewInfo } from "../pipeline/render-view"; +import { RenderView, RenderViewInfo, RenderViewPriority } from "../pipeline/render-view"; import { RenderPipeline } from "../pipeline/render-pipeline"; import { ForwardPipeline } from "../pipeline/forward/forward-pipeline"; +import { SceneManager, SceneManagerInfo } from "../scene/scene-manager"; export interface RootInfo { }; +export interface SceneInfo { + name: string; +}; + export class Root { constructor(device: GFXDevice) { @@ -15,6 +19,11 @@ export class Root { } public initialize(info: RootInfo): boolean { + + if (!this._device.mainWindow) { + return false; + } + this._mainWindow = this._device.mainWindow; let pipeline = new ForwardPipeline(this); @@ -29,7 +38,7 @@ export class Root { public destroy() { this.destroyViews(); - this.destroyScenes(); + this.destroySceneManagers(); if (this._pipeline) { this._pipeline.destroy(); @@ -39,15 +48,14 @@ export class Root { public frameMove(deltaTime: number) { - if (this._pipeline) { - for (let i = 0; i < this._views.length; ++i) { - this._pipeline.render(this._views[i]); + for (let i = 0; i < this._views.length; ++i) { + let view = this._views[i]; + if(view.isEnable() && view.isAttached) { + (this._pipeline).render(view); } } - if (this._device) { - this._device.present(); - } + (this._device).present(); } public createWindow(info: GFXWindowInfo): GFXWindow | null { @@ -79,23 +87,31 @@ export class Root { this._windows = []; } - public createScene(): Scene | null { - let scene = new Scene; - this._scenes.push(scene); - return scene; + public createSceneManager(info: SceneManagerInfo): SceneManager | null { + let scene = new SceneManager; + if(scene.initialize(info)) { + this._sceneMgrs.push(scene); + return scene; + } else { + return null; + } } - public destroyScene(scene: Scene) { - for (let i = 0; i < this._scenes.length; ++i) { - if (this._scenes[i] === scene) { - this._scenes.splice(i); + public destroySceneManager(sceneMgr: SceneManager) { + for (let i = 0; i < this._sceneMgrs.length; ++i) { + if (this._sceneMgrs[i] === sceneMgr) { + sceneMgr.destroy(); + this._sceneMgrs.splice(i); return; } } } - public destroyScenes() { - this._scenes = []; + public destroySceneManagers() { + for (let i = 0; i < this._sceneMgrs.length; ++i) { + this._sceneMgrs[i].destroy(); + } + this._sceneMgrs = []; } public createView(info: RenderViewInfo): RenderView | null { @@ -139,8 +155,8 @@ export class Root { return this._pipeline; } - public get scenes(): Scene[] { - return this._scenes; + public get sceneManagers(): SceneManager[] { + return this._sceneMgrs; } public get views(): RenderView[] { @@ -148,9 +164,9 @@ export class Root { } private _device: GFXDevice; - private _mainWindow: GFXWindow | null = null; private _windows: GFXWindow[] = []; + private _mainWindow: GFXWindow | null = null; private _pipeline: RenderPipeline | null = null; - private _scenes: Scene[] = []; + private _sceneMgrs: SceneManager[] = []; private _views: RenderView[] = []; }; diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index 7e3fab45d4..7b8f3372f3 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -1,8 +1,13 @@ -import { Scene } from "../renderer/scene/scene"; import { Camera } from "../renderer/scene/camera"; import { GFXWindow } from "../gfx/window"; +import { SceneManager } from "../scene/scene-manager"; + +export enum RenderViewPriority { + GENERAL = 100, +}; export interface RenderViewInfo { + name: string; window: GFXWindow; priority: number; width: number; @@ -23,6 +28,7 @@ export class RenderView { return false; } + this._name = info.name; this._window = info.window; this._priority = info.priority; this._width = info.width; @@ -42,14 +48,32 @@ export class RenderView { } - public attach(scene: Scene, camera: Camera) { - this._scene = scene; + public attach(camera: Camera) { + this._sceneMgr = camera.sceneMgr; this._camera = camera; + this._isAttached = true; } public detach() { - this._scene = null; + this._sceneMgr = null; this._camera = null; + this._isAttached = false; + } + + public enable(isEnable: boolean) { + this._isEnable = isEnable; + } + + public isEnable() : boolean { + return this._isEnable; + } + + public isAttached() : boolean { + return this._isAttached; + } + + public get name(): string { + return this._name; } public get window(): GFXWindow | null { @@ -68,10 +92,13 @@ export class RenderView { return this._height; } - protected _window: GFXWindow | null = null; - protected _priority: number = 0; - protected _width: number = 0; - protected _height: number = 0; - protected _scene: Scene | null = null; - protected _camera: Camera | null = null; + private _name: string = ""; + private _window: GFXWindow | null = null; + private _priority: number = 0; + private _width: number = 0; + private _height: number = 0; + private _sceneMgr: SceneManager | null = null; + private _camera: Camera | null = null; + private _isAttached: boolean = false; + private _isEnable: boolean = true; }; diff --git a/cocos/renderer/scene/camera.js b/cocos/renderer/scene/camera.js index 898800c409..5511fc08ff 100644 --- a/cocos/renderer/scene/camera.js +++ b/cocos/renderer/scene/camera.js @@ -18,7 +18,11 @@ export default class Camera { /** * Setup a default perspective camera */ - constructor() { + constructor(sceneMgr, name) { + + this._sceneMgr = sceneMgr; + this._name = name; + this._poolID = -1; this._node = null; @@ -51,6 +55,14 @@ export default class Camera { this._orthoHeight = 10; } + get sceneMgr() { + return this._sceneMgr; + } + + get name() { + return this._name; + } + /** * Get the hosting node of this camera * @returns {Node} the hosting node diff --git a/cocos/renderer/scene/light.js b/cocos/renderer/scene/light.js index 2fe1e5070f..61d5c3a234 100644 --- a/cocos/renderer/scene/light.js +++ b/cocos/renderer/scene/light.js @@ -51,7 +51,11 @@ export default class Light { /** * Setup a default directional light with no shadows */ - constructor() { + constructor(sceneMgr, name) { + + this._sceneMgr = sceneMgr; + this._name = name; + this._poolID = -1; this._node = null; @@ -90,6 +94,14 @@ export default class Light { this._shadowFrustumSize = 50; // used for directional light. } + get sceneMgr() { + return this._sceneMgr; + } + + get name() { + return this._name; + } + /** * Get the hosting node of this camera * @returns {Node} the hosting node diff --git a/cocos/scene/scene-manager.ts b/cocos/scene/scene-manager.ts new file mode 100644 index 0000000000..b4c764e478 --- /dev/null +++ b/cocos/scene/scene-manager.ts @@ -0,0 +1,131 @@ +import Node from "../scene-graph/node"; +import Camera from "../renderer/scene/camera"; +import Light from "../renderer/scene/light"; + +export interface SceneManagerInfo { + name: string; +}; + +export interface SceneNodeInfo { + name: string; + isStatic: boolean; + //parent: Node; +} + +export class SceneManager { + + constructor() { + } + + public initialize(info: SceneManagerInfo): boolean { + this._name = info.name; + + return true; + } + + public destroy() { + this.destroyCameras(); + this.destroyLights(); + this.destroyNodes(); + } + + public createNode(info: SceneNodeInfo): Node { + let node = new Node(name); + this._nodes.set(node.uuid, node); + return node; + } + + public destroyNode(node: Node) { + this._nodes.delete(node.uuid); + } + + public destroyNodes() { + this._nodes.clear(); + } + + public getNode(id: number): Node | null { + let node = this._nodes.get(id); + if (node) { + return node; + } else { + return null; + } + } + + public createCamera(name: string): Camera { + let camera = new Camera(this, name); + this._cameras.push(camera); + return camera; + } + + public destroyCamera(camera: Camera) { + for (let i = 0; i < this._cameras.length; ++i) { + if (this._cameras[i] === camera) { + this._cameras.slice(i); + return; + } + } + } + + public destroyCameras() { + this._cameras = []; + } + + public getCamera(name: string): Camera | null { + for (let i = 0; i < this._cameras.length; ++i) { + let camera = this._cameras[i]; + if (camera.getName() === name) { + return camera; + } + } + + return null; + } + + public createLight(name: string): Light { + let light = new Light(this, name); + this._lights.push(light); + return light; + } + + public destroyLight(light: Light) { + for (let i = 0; i < this._lights.length; ++i) { + if (this._lights[i] === light) { + this._lights.slice(i); + return; + } + } + } + + public destroyLights() { + this._lights = []; + } + + public getLight(name: string): Light | null { + for (let i = 0; i < this._lights.length; ++i) { + let light = this._lights[i]; + if (light.getName() === name) { + return light; + } + } + + return null; + } + + public get name(): string { + return this._name; + } + + public get cameras(): Camera[] { + return this._cameras; + } + + public get lights(): Light[] { + return this._lights; + } + + protected _name: string = ""; + protected _nodes: Map = new Map; + protected _cameras: Camera[] = []; + protected _lights: Light[] = []; +}; From 41c453bf194bc05269b98ccf416e69e1df1510bb Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 16:15:26 +0800 Subject: [PATCH 018/267] rename scene-manager to render-scene --- cocos/core/root.ts | 34 +++++++++---------- cocos/renderer/scene/camera.js | 8 ++--- cocos/renderer/scene/light.js | 8 ++--- .../scene/render-scene.ts} | 28 +++++++++------ 4 files changed, 42 insertions(+), 36 deletions(-) rename cocos/{scene/scene-manager.ts => renderer/scene/render-scene.ts} (78%) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 6cf372bb49..9649d82e3f 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -3,7 +3,7 @@ import { GFXDevice } from "../gfx/device"; import { RenderView, RenderViewInfo, RenderViewPriority } from "../pipeline/render-view"; import { RenderPipeline } from "../pipeline/render-pipeline"; import { ForwardPipeline } from "../pipeline/forward/forward-pipeline"; -import { SceneManager, SceneManagerInfo } from "../scene/scene-manager"; +import { RenderScene, RenderSceneInfo } from "../renderer/scene/render-scene"; export interface RootInfo { }; @@ -38,7 +38,7 @@ export class Root { public destroy() { this.destroyViews(); - this.destroySceneManagers(); + this.destroyScenes(); if (this._pipeline) { this._pipeline.destroy(); @@ -87,31 +87,31 @@ export class Root { this._windows = []; } - public createSceneManager(info: SceneManagerInfo): SceneManager | null { - let scene = new SceneManager; + public createScene(info: RenderSceneInfo): RenderScene | null { + let scene = new RenderScene; if(scene.initialize(info)) { - this._sceneMgrs.push(scene); + this._scenes.push(scene); return scene; } else { return null; } } - public destroySceneManager(sceneMgr: SceneManager) { - for (let i = 0; i < this._sceneMgrs.length; ++i) { - if (this._sceneMgrs[i] === sceneMgr) { - sceneMgr.destroy(); - this._sceneMgrs.splice(i); + public destroyScene(scene: RenderScene) { + for (let i = 0; i < this._scenes.length; ++i) { + if (this._scenes[i] === scene) { + scene.destroy(); + this._scenes.splice(i); return; } } } - public destroySceneManagers() { - for (let i = 0; i < this._sceneMgrs.length; ++i) { - this._sceneMgrs[i].destroy(); + public destroyScenes() { + for (let i = 0; i < this._scenes.length; ++i) { + this._scenes[i].destroy(); } - this._sceneMgrs = []; + this._scenes = []; } public createView(info: RenderViewInfo): RenderView | null { @@ -155,8 +155,8 @@ export class Root { return this._pipeline; } - public get sceneManagers(): SceneManager[] { - return this._sceneMgrs; + public get sceneManagers(): RenderScene[] { + return this._scenes; } public get views(): RenderView[] { @@ -167,6 +167,6 @@ export class Root { private _windows: GFXWindow[] = []; private _mainWindow: GFXWindow | null = null; private _pipeline: RenderPipeline | null = null; - private _sceneMgrs: SceneManager[] = []; + private _scenes: RenderScene[] = []; private _views: RenderView[] = []; }; diff --git a/cocos/renderer/scene/camera.js b/cocos/renderer/scene/camera.js index 5511fc08ff..8e9ec33d2a 100644 --- a/cocos/renderer/scene/camera.js +++ b/cocos/renderer/scene/camera.js @@ -18,9 +18,9 @@ export default class Camera { /** * Setup a default perspective camera */ - constructor(sceneMgr, name) { + constructor(scene, name) { - this._sceneMgr = sceneMgr; + this._scene = scene; this._name = name; this._poolID = -1; @@ -55,8 +55,8 @@ export default class Camera { this._orthoHeight = 10; } - get sceneMgr() { - return this._sceneMgr; + get scene() { + return this._scene; } get name() { diff --git a/cocos/renderer/scene/light.js b/cocos/renderer/scene/light.js index 61d5c3a234..16e4f59a87 100644 --- a/cocos/renderer/scene/light.js +++ b/cocos/renderer/scene/light.js @@ -51,9 +51,9 @@ export default class Light { /** * Setup a default directional light with no shadows */ - constructor(sceneMgr, name) { + constructor(scene, name) { - this._sceneMgr = sceneMgr; + this._scene = scene; this._name = name; this._poolID = -1; @@ -94,8 +94,8 @@ export default class Light { this._shadowFrustumSize = 50; // used for directional light. } - get sceneMgr() { - return this._sceneMgr; + get scene() { + return this._scene; } get name() { diff --git a/cocos/scene/scene-manager.ts b/cocos/renderer/scene/render-scene.ts similarity index 78% rename from cocos/scene/scene-manager.ts rename to cocos/renderer/scene/render-scene.ts index b4c764e478..dd31338cb9 100644 --- a/cocos/scene/scene-manager.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,25 +1,29 @@ -import Node from "../scene-graph/node"; -import Camera from "../renderer/scene/camera"; -import Light from "../renderer/scene/light"; +import Node from "../../scene-graph/node"; +import Camera from "./camera"; +import Light from "./light"; -export interface SceneManagerInfo { +export interface RenderSceneInfo { name: string; }; export interface SceneNodeInfo { name: string; - isStatic: boolean; + isStatic?: boolean; //parent: Node; } -export class SceneManager { +export class RenderScene { constructor() { } - public initialize(info: SceneManagerInfo): boolean { + public initialize(info: RenderSceneInfo): boolean { this._name = info.name; + let cameraNode = this.createNode({ name: "mainCamNode", isStatic: false }); + this._mainCamera = this.createCamera("mainCamera"); + this._mainCamera.setNode(cameraNode); + return true; } @@ -69,6 +73,7 @@ export class SceneManager { public destroyCameras() { this._cameras = []; + this._mainCamera = null; } public getCamera(name: string): Camera | null { @@ -124,8 +129,9 @@ export class SceneManager { return this._lights; } - protected _name: string = ""; - protected _nodes: Map = new Map; - protected _cameras: Camera[] = []; - protected _lights: Light[] = []; + private _name: string = ""; + private _nodes: Map = new Map; + private _cameras: Camera[] = []; + private _mainCamera: Camera | null = null; + private _lights: Light[] = []; }; From 80d0339869abcbc79f860db727fef7de9a1aac14 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 17:07:43 +0800 Subject: [PATCH 019/267] add model management to renderscene --- cocos/pipeline/render-view.ts | 4 ++-- cocos/renderer/scene/model.js | 28 ++++++++++++++++++++++++ cocos/renderer/scene/render-scene.ts | 32 ++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index 7b8f3372f3..aa58ea44d0 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -1,6 +1,6 @@ import { Camera } from "../renderer/scene/camera"; import { GFXWindow } from "../gfx/window"; -import { SceneManager } from "../scene/scene-manager"; +import { RenderScene } from "../renderer/scene/render-scene"; export enum RenderViewPriority { GENERAL = 100, @@ -97,7 +97,7 @@ export class RenderView { private _priority: number = 0; private _width: number = 0; private _height: number = 0; - private _sceneMgr: SceneManager | null = null; + private _sceneMgr: RenderScene | null = null; private _camera: Camera | null = null; private _isAttached: boolean = false; private _isEnable: boolean = true; diff --git a/cocos/renderer/scene/model.js b/cocos/renderer/scene/model.js index 91aef6f362..9d0c40b37c 100644 --- a/cocos/renderer/scene/model.js +++ b/cocos/renderer/scene/model.js @@ -9,8 +9,12 @@ export default class Model { * Setup a default empty model */ constructor() { + this._scene = null; + this._id = 0; + this._type = 'default'; this._poolID = -1; + this._isEnable = true; this._node = null; this._inputAssembler = null; this._effect = null; @@ -23,6 +27,22 @@ export default class Model { this._boundingShape = null; } + setScene(scene) { + this._scene = scene; + + if(this._scene) { + this._id = this._scene.generateModelId(); + } + } + + get scene() { + return this._scene; + } + + get id() { + return this._id; + } + _updateTransform() { if (!this._node._hasChanged || !this._boundingShape) return; this._node.updateWorldTransformFull(); @@ -41,6 +61,14 @@ export default class Model { this._boundingShape = aabb.clone(this._bsModelSpace); } + enable(isEnable) { + this._isEnable = isEnable; + } + + isEnable() { + return this._isEnable; + } + /** * Get the hosting node of this camera * @returns {Node} the hosting node diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index dd31338cb9..28d018c9a1 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,6 +1,7 @@ import Node from "../../scene-graph/node"; import Camera from "./camera"; import Light from "./light"; +import Model from "./model"; export interface RenderSceneInfo { name: string; @@ -31,6 +32,7 @@ export class RenderScene { this.destroyCameras(); this.destroyLights(); this.destroyNodes(); + this.destroyModels(); } public createNode(info: SceneNodeInfo): Node { @@ -117,6 +119,30 @@ export class RenderScene { return null; } + public createModel(clazz: new () => T): Model { + let model = new clazz; + model.setScene(this); + this._models.push(model); + return model; + } + + public destroyModel(model: Model) { + for (let i = 0; i < this._models.length; ++i) { + if (this._models[i] === model) { + this._models.slice(i); + return; + } + } + } + + public destroyModels() { + this._models = []; + } + + public generateModelId(): number { + return this._modelId++; + } + public get name(): string { return this._name; } @@ -129,9 +155,15 @@ export class RenderScene { return this._lights; } + public get models(): Model[] { + return this._models; + } + private _name: string = ""; private _nodes: Map = new Map; private _cameras: Camera[] = []; private _mainCamera: Camera | null = null; private _lights: Light[] = []; + private _models: Model[] = []; + private _modelId: number = 0; }; From 08a0cf761c8e3852d1c0d37c4e6ae5755ffc77ff Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 2 Jan 2019 17:52:35 +0800 Subject: [PATCH 020/267] adapt render scene in components --- cocos/3d/framework/camera-component.js | 16 ++++++++----- cocos/3d/framework/light-component.js | 17 ++++++++------ cocos/3d/framework/model-component.js | 12 +++++++--- cocos/3d/framework/renderable-component.js | 4 ++-- cocos/components/CCComponent.js | 6 ++++- cocos/renderer/scene/camera.js | 1 + cocos/renderer/scene/light.js | 1 + cocos/renderer/scene/model.js | 1 + cocos/scene-graph/base-node.js | 27 +++++++++++++++++++++- cocos/scene-graph/node.js | 3 ++- cocos/scene-graph/scene.js | 6 +++++ 11 files changed, 73 insertions(+), 21 deletions(-) diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index c7cedc8479..a0ce36302e 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -23,12 +23,12 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import RenderSystemActor from './renderSystemActor'; import renderer from '../../renderer/index'; import { toRadian } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; import { Color, Enum, Rect } from '../../core/value-types'; import enums from '../../renderer/enums'; +import Component from '../../components/CCComponent'; /** * @typedef {import('../../core/value-types/index').Color} Color @@ -74,12 +74,12 @@ let CameraClearFlag = Enum({ * * !#ch 相机组件 * @class CameraComponent - * @extends RenderSystemActor + * @extends Component */ @ccclass('cc.CameraComponent') @menu('Components/CameraComponent') @executeInEditMode -export default class CameraComponent extends RenderSystemActor{ +export default class CameraComponent extends Component { @property _projection = CameraProjection.PERSPECTIVE; @@ -302,10 +302,10 @@ export default class CameraComponent extends RenderSystemActor{ constructor() { super(); - this._camera = new renderer.Camera(); } onLoad() { + this._camera = this._renderScene.createCamera(this.name); this.projection = this._projection; this.priority = this._priority; this.fov = this._fov; @@ -322,11 +322,15 @@ export default class CameraComponent extends RenderSystemActor{ } onEnable() { - this.scene.addCamera(this._camera); + this._camera._enable = this.enabled; } onDisable() { - this.scene.removeCamera(this._camera); + this._camera._enable = this.enabled; + } + + onDestroy() { + this._renderScene.destroyCamera(this._camera); } /** diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js index 25901e4323..44da06f009 100644 --- a/cocos/3d/framework/light-component.js +++ b/cocos/3d/framework/light-component.js @@ -23,11 +23,11 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import RenderSystemActor from './renderSystemActor'; import renderer from '../../renderer/index'; import { Color, Enum } from '../../core/value-types'; import { toRadian } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; +import Component from '../../components/CCComponent'; /** * !#en The light source type @@ -108,12 +108,12 @@ const LightShadowType = Enum({ * * !#ch 光源组件 * @class LightComponent - * @extends RenderSystemActor + * @extends Component */ @ccclass('cc.LightComponent') @menu('Components/LightComponent') @executeInEditMode -export default class LightComponent extends RenderSystemActor { +export default class LightComponent extends Component { @property _type = LightType.Directional; @@ -412,11 +412,10 @@ export default class LightComponent extends RenderSystemActor { constructor() { super(); - - this._light = new renderer.Light(); } onLoad() { + this._light = this._renderScene.createLight(this.name); this._light.setNode(this.node); this.type = this._type; this.color = this._color; @@ -434,10 +433,14 @@ export default class LightComponent extends RenderSystemActor { } onEnable() { - this.scene.addLight(this._light); + this._light._enable = this.enabled; } onDisable() { - this.scene.removeLight(this._light); + this._light._enable = this.enabled; + } + + onDestroy() { + this._renderScene.destroyLight(this._light); } } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index cd656e6650..65da63e0d4 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -178,13 +178,19 @@ export default class ModelComponent extends RenderableComponent { onEnable() { for (let i = 0; i < this._models.length; ++i) { - this.scene.addModel(this._models[i]); + this._models[i]._enable = this.enabled; } } onDisable() { for (let i = 0; i < this._models.length; ++i) { - this.scene.removeModel(this._models[i]); + this._models[i]._enable = this.enabled; + } + } + + onDestroy() { + for (let i = 0; i < this._models.length; ++i) { + this._renderScene.destroyModel(this._models[i]); } } @@ -212,7 +218,7 @@ export default class ModelComponent extends RenderableComponent { } _createModel() { - return new Model(); + return this._renderScene.createModel(Model); } _updateModelParams() { diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.js index eac40b9af4..be220f7d13 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.js @@ -1,11 +1,11 @@ //@ts-check -import RenderSystemActor from "./renderSystemActor"; import { _decorator } from '../../core/data/index'; import Material from "../assets/material"; +import Component from "../../components/CCComponent"; const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') -export default class RenderableComponent extends RenderSystemActor { +export default class RenderableComponent extends Component { /** * @type {Material[]} */ diff --git a/cocos/components/CCComponent.js b/cocos/components/CCComponent.js index ad5e99f5c0..c90dcfda7f 100644 --- a/cocos/components/CCComponent.js +++ b/cocos/components/CCComponent.js @@ -195,6 +195,10 @@ class Component extends CCObject { static system = null; + get _renderScene() { + return this.node._scene._renderScene; + } + constructor () { super(); if (CC_EDITOR) { @@ -718,4 +722,4 @@ value(Component, '_registerEditorProps', function (cls, props) { Component.prototype.__scriptUuid = ''; cc.Component = Component; -export default Component; \ No newline at end of file +export default Component; diff --git a/cocos/renderer/scene/camera.js b/cocos/renderer/scene/camera.js index 8e9ec33d2a..63dd0323b4 100644 --- a/cocos/renderer/scene/camera.js +++ b/cocos/renderer/scene/camera.js @@ -22,6 +22,7 @@ export default class Camera { this._scene = scene; this._name = name; + this._enable = false; this._poolID = -1; this._node = null; diff --git a/cocos/renderer/scene/light.js b/cocos/renderer/scene/light.js index 16e4f59a87..a9272f98d9 100644 --- a/cocos/renderer/scene/light.js +++ b/cocos/renderer/scene/light.js @@ -55,6 +55,7 @@ export default class Light { this._scene = scene; this._name = name; + this._enable = false; this._poolID = -1; this._node = null; diff --git a/cocos/renderer/scene/model.js b/cocos/renderer/scene/model.js index 9d0c40b37c..fff9d96afe 100644 --- a/cocos/renderer/scene/model.js +++ b/cocos/renderer/scene/model.js @@ -11,6 +11,7 @@ export default class Model { constructor() { this._scene = null; this._id = 0; + this._enable = false; this._type = 'default'; this._poolID = -1; diff --git a/cocos/scene-graph/base-node.js b/cocos/scene-graph/base-node.js index 181cf5aaab..ba4dfd45b2 100644 --- a/cocos/scene-graph/base-node.js +++ b/cocos/scene-graph/base-node.js @@ -392,6 +392,27 @@ export default class BaseNode extends CCObject { this.setParent(value); } + /** + * !#en which scene this node belongs to. + * !#zh 此节点属于哪个场景。 + * @property _scene + * @type {cc.Scene}} + * @private + */ + _scene = null; + + static _setScene(node) { + if (node instanceof cc.Scene) { + node._scene = node; + } else { + if (node._parent == null) { + cc.error('Node %s(%s) has not attached to a scene.', node.name, node.uuid); + } else { + node._scene = node._parent._scene; + } + } + } + // ABSTRACT INTERFACES /** @@ -1052,7 +1073,11 @@ export default class BaseNode extends CCObject { } cleanup () {} - _onSetParent (/*oldParent*/) {} + _onSetParent(oldParent) { + if ((oldParent == null || oldParent._scene != this._parent._scene) && this._parent._scene != null) { + this.walk(this.constructor._setScene); + } + } _onPostActivated () {} _onBatchRestored () {} _onBatchCreated () {} diff --git a/cocos/scene-graph/node.js b/cocos/scene-graph/node.js index 3e756491bd..6fbaa226f5 100644 --- a/cocos/scene-graph/node.js +++ b/cocos/scene-graph/node.js @@ -91,7 +91,8 @@ class Node extends BaseNode { this.invalidateChildren(); } - _onSetParent(/*oldParent*/) { + _onSetParent(oldParent) { + super._onSetParent(oldParent); this.invalidateChildren(); } diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index d1cee7d257..9ff302b510 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -25,6 +25,8 @@ import Node from './node'; import { ccclass, property } from '../core/data/class-decorator'; +import BaseNode from './base-node'; +import { RenderScene } from '../renderer/scene/render-scene'; /** * !#en @@ -38,6 +40,9 @@ import { ccclass, property } from '../core/data/class-decorator'; */ @ccclass("cc.Scene") export default class Scene extends Node { + + _renderScene = new RenderScene(); + constructor(name) { super(name); @@ -84,6 +89,7 @@ export default class Scene extends Node { } this._inited = true; } + this.walk(BaseNode._setScene); } _activate (active) { From 9ec52a9ddaf7bb85a5757efcd8a673082ffc7b21 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 18:03:51 +0800 Subject: [PATCH 021/267] remove GFXVertexSemantic --- cocos/gfx/gfx-define.ts | 82 ++++++++++++---------------- cocos/gfx/input-assembler.ts | 4 +- cocos/gfx/webgl/webgl-commands.ts | 65 +++------------------- cocos/gfx/webgl/webgl-gpu-objects.ts | 3 +- cocos/pipeline/index.ts | 1 + cocos/pipeline/render-pipeline.ts | 8 +-- 6 files changed, 51 insertions(+), 112 deletions(-) create mode 100644 cocos/pipeline/index.ts diff --git a/cocos/gfx/gfx-define.ts b/cocos/gfx/gfx-define.ts index 0c986970ef..61c41f70c6 100644 --- a/cocos/gfx/gfx-define.ts +++ b/cocos/gfx/gfx-define.ts @@ -22,27 +22,16 @@ export const GFX_MAX_VERTEX_ATTRIBUTES: number = 8; export const GFX_MAX_TEXTURE_UNITS: number = 16; export const GFX_MAX_ATTACHMENTS: number = 4; -export const GFX_ATTRIBUTE_POSITION = "a_position"; -export const GFX_ATTRIBUTE_POSITION1 = "a_position1"; -export const GFX_ATTRIBUTE_POSITION2 = "a_position2"; -export const GFX_ATTRIBUTE_POSITION3 = "a_position3"; -export const GFX_ATTRIBUTE_COLOR = "a_color"; -export const GFX_ATTRIBUTE_COLOR1 = "a_color1"; -export const GFX_ATTRIBUTE_COLOR2 = "a_color2"; -export const GFX_ATTRIBUTE_COLOR3 = "a_color3"; -export const GFX_ATTRIBUTE_NORMAL = "a_normal"; -export const GFX_ATTRIBUTE_NORMAL1 = "a_normal1"; -export const GFX_ATTRIBUTE_NORMAL2 = "a_normal2"; -export const GFX_ATTRIBUTE_NORMAL3 = "a_normal3"; -export const GFX_ATTRIBUTE_TANGENT = "a_tangent"; -export const GFX_ATTRIBUTE_BINORMAL = "a_binormal"; -export const GFX_ATTRIBUTE_TEXCOORD = "a_texCoord"; -export const GFX_ATTRIBUTE_TEXCOORD1 = "a_texCoord1"; -export const GFX_ATTRIBUTE_TEXCOORD2 = "a_texCoord2"; -export const GFX_ATTRIBUTE_TEXCOORD3 = "a_texCoord3"; -export const GFX_ATTRIBUTE_JOINTS = "a_joints"; -export const GFX_ATTRIBUTE_WEIGHTS = "a_weights"; -export const GFX_ATTRIBUTE_SV_INSTANCE_ID = "sv_instanceID"; +export const GFX_ATTRIBUTE_POSITION = "a_position"; // 0 +export const GFX_ATTRIBUTE_COLOR = "a_color"; // 1 +export const GFX_ATTRIBUTE_COLOR1 = "a_color1"; // 2 +export const GFX_ATTRIBUTE_NORMAL = "a_normal"; // 3 +export const GFX_ATTRIBUTE_TANGENT = "a_tangent"; // 4 +export const GFX_ATTRIBUTE_BINORMAL = "a_binormal"; // 5 +export const GFX_ATTRIBUTE_TEXCOORD = "a_texCoord"; // 6 +export const GFX_ATTRIBUTE_TEXCOORD1 = "a_texCoord1"; // 7 +export const GFX_ATTRIBUTE_JOINTS = "a_joints"; // 8 +export const GFX_ATTRIBUTE_WEIGHTS = "a_weights"; // 9 export enum GFXType { UNKNOWN, @@ -202,31 +191,6 @@ export enum GFXFormat { PVRTC2_4BPP, }; -export enum GFXVertexSemantic { - UNKNOWN, - POSITION, - POSITION1, - POSITION2, - POSITION3, - COLOR, - COLOR1, - COLOR2, - COLOR3, - NORMAL, - NORMAL1, - NORMAL2, - NORMAL3, - TANGENT, - BINORMAL, - TEXCOORD, - TEXCOORD1, - TEXCOORD2, - TEXCOORD3, - JOINTS, - WEIGHTS, - SV_INSTANCE_ID, -}; - export enum GFXBufferUsageBit { NONE = 0, TRANSFER_SRC = 0x1, @@ -730,3 +694,29 @@ export function GFXGetTypeSize(type: GFXType): number { } } } + +export function GFXGetAttributeBinding(name: string) : number { + if (name === GFX_ATTRIBUTE_POSITION) { + return 20; + } else if (name === GFX_ATTRIBUTE_COLOR) { + return 21; + } else if (name === GFX_ATTRIBUTE_COLOR1) { + return 22; + } else if (name === GFX_ATTRIBUTE_NORMAL) { + return 23; + } else if (name === GFX_ATTRIBUTE_TANGENT) { + return 24; + } else if (name === GFX_ATTRIBUTE_BINORMAL) { + return 25; + } else if (name === GFX_ATTRIBUTE_TEXCOORD) { + return 26; + } else if (name === GFX_ATTRIBUTE_TEXCOORD1) { + return 27; + } else if (name === GFX_ATTRIBUTE_JOINTS) { + return 28; + } else if (name === GFX_ATTRIBUTE_WEIGHTS) { + return 29; + } else { + return -1; + } +} diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 7ad9707570..9d54ee9ace 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,10 +1,10 @@ import { GFXDevice } from './device'; -import { GFXFormat, GFXVertexSemantic } from './gfx-define'; +import { GFXFormat } from './gfx-define'; import { GFXBuffer } from './buffer'; export interface GFXInputAttribute { + binding?: number; name: string; - semantic: GFXVertexSemantic; format: GFXFormat; stream?: number; isInstanced?: boolean; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index bc0fa08fc1..f9b2826577 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,6 +1,6 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXViewport, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFX_ATTRIBUTE_POSITION, GFXVertexSemantic, GFX_ATTRIBUTE_POSITION1, GFX_ATTRIBUTE_POSITION2, GFX_ATTRIBUTE_POSITION3, GFX_ATTRIBUTE_COLOR, GFX_ATTRIBUTE_COLOR1, GFX_ATTRIBUTE_COLOR2, GFX_ATTRIBUTE_COLOR3, GFX_ATTRIBUTE_NORMAL, GFX_ATTRIBUTE_NORMAL1, GFX_ATTRIBUTE_NORMAL2, GFX_ATTRIBUTE_NORMAL3, GFX_ATTRIBUTE_TEXCOORD, GFX_ATTRIBUTE_TEXCOORD1, GFX_ATTRIBUTE_TEXCOORD2, GFX_ATTRIBUTE_TEXCOORD3, GFX_ATTRIBUTE_JOINTS, GFX_ATTRIBUTE_WEIGHTS, GFX_ATTRIBUTE_SV_INSTANCE_ID, GFX_ATTRIBUTE_TANGENT, GFX_ATTRIBUTE_BINORMAL } from "../gfx-define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXGetAttributeBinding } from "../gfx-define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; @@ -818,75 +818,24 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG varName = info.name; } - let semantic = GFXVertexSemantic.UNKNOWN; - let glLoc = -1; + let glLoc = GFXGetAttributeBinding(varName); - if (varName === GFX_ATTRIBUTE_POSITION) { - semantic = GFXVertexSemantic.POSITION; - } else if (varName === GFX_ATTRIBUTE_POSITION1) { - semantic = GFXVertexSemantic.POSITION1; - } else if (varName === GFX_ATTRIBUTE_POSITION2) { - semantic = GFXVertexSemantic.POSITION2; - } else if (varName === GFX_ATTRIBUTE_POSITION3) { - semantic = GFXVertexSemantic.POSITION3; - } else if (varName === GFX_ATTRIBUTE_COLOR) { - semantic = GFXVertexSemantic.COLOR; - } else if (varName === GFX_ATTRIBUTE_COLOR1) { - semantic = GFXVertexSemantic.COLOR1; - } else if (varName === GFX_ATTRIBUTE_COLOR2) { - semantic = GFXVertexSemantic.COLOR2; - } else if (varName === GFX_ATTRIBUTE_COLOR3) { - semantic = GFXVertexSemantic.COLOR3; - } else if (varName === GFX_ATTRIBUTE_NORMAL) { - semantic = GFXVertexSemantic.NORMAL; - } else if (varName === GFX_ATTRIBUTE_NORMAL1) { - semantic = GFXVertexSemantic.NORMAL1; - } else if (varName === GFX_ATTRIBUTE_NORMAL2) { - semantic = GFXVertexSemantic.NORMAL2; - } else if (varName === GFX_ATTRIBUTE_NORMAL3) { - semantic = GFXVertexSemantic.NORMAL3; - } else if (varName === GFX_ATTRIBUTE_TANGENT) { - semantic = GFXVertexSemantic.TANGENT; - } else if (varName === GFX_ATTRIBUTE_BINORMAL) { - semantic = GFXVertexSemantic.BINORMAL; - } else if (varName === GFX_ATTRIBUTE_TEXCOORD) { - semantic = GFXVertexSemantic.TEXCOORD; - } else if (varName === GFX_ATTRIBUTE_TEXCOORD1) { - semantic = GFXVertexSemantic.TEXCOORD1; - } else if (varName === GFX_ATTRIBUTE_TEXCOORD2) { - semantic = GFXVertexSemantic.TEXCOORD2; - } else if (varName === GFX_ATTRIBUTE_TEXCOORD3) { - semantic = GFXVertexSemantic.TEXCOORD3; - } else if (varName === GFX_ATTRIBUTE_JOINTS) { - semantic = GFXVertexSemantic.JOINTS; - } else if (varName === GFX_ATTRIBUTE_WEIGHTS) { - semantic = GFXVertexSemantic.WEIGHTS; - } else if (varName === GFX_ATTRIBUTE_SV_INSTANCE_ID) { - semantic = GFXVertexSemantic.SV_INSTANCE_ID; - } else { - console.error("Unsupported vertex attribute semantic."); - } - - if(semantic !== GFXVertexSemantic.UNKNOWN) { - glLoc = semantic; + if(glLoc >= 0) { gl.bindAttribLocation(gpuShader.glProgram, glLoc, varName); - - } else { - glLoc = -1; + }/* else { //glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); - } + }*/ let type = WebGLTypeToGFXType(info.type); let stride = WebGLGetTypeSize(info.type); gpuShader.glInputs[i] = { - binding: -1, + binding: glLoc, name: varName, type: type, stride: stride, count: info.size, size: stride * info.size, - semantic: semantic, glType: info.type, glLoc: glLoc, @@ -1063,7 +1012,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput gpuInputAssembler.glAttribs[i] = { glBuffer: gpuBuffer.glBuffer, - glLoc: attrib.semantic, + glLoc: attrib.binding? attrib.binding : -1, glType: glType, size: size, count: GFXFormatInfos[attrib.format].count, diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 9c3258c502..dc33439b9b 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage, GFXVertexSemantic } from "../gfx-define"; +import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage } from "../gfx-define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../render-pass"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; import { GFXInputAttribute } from "../input-assembler"; @@ -126,7 +126,6 @@ export class WebGLGPUInput { stride: number = 0; count: number = 0; size: number = 0; - semantic: GFXVertexSemantic = GFXVertexSemantic.UNKNOWN; glType: GLenum = 0; glLoc: GLint = 0; diff --git a/cocos/pipeline/index.ts b/cocos/pipeline/index.ts new file mode 100644 index 0000000000..3bdeba37ab --- /dev/null +++ b/cocos/pipeline/index.ts @@ -0,0 +1 @@ +import "./render-view"; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index fb09846e29..64c8fcbc69 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,11 +1,11 @@ import { RenderView } from "./render-view"; import { RenderFlow, RenderFlowInfo } from "./render-flow"; import { Root } from "../core/root"; -import { GFXRenderPass, GFXRenderPassInfo } from "../gfx/render-pass"; +import { GFXRenderPass } from "../gfx/render-pass"; import { GFXDevice } from "../gfx/device"; import { GFXBuffer } from "../gfx/buffer"; import { GFXInputAssembler, GFXInputAttribute } from "../gfx/input-assembler"; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXVertexSemantic, GFXFormat } from "../gfx/gfx-define"; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../gfx/gfx-define"; export enum RenderPassStage { FORWARD = 0, @@ -147,8 +147,8 @@ export abstract class RenderPipeline { // create input assembler let attributes: GFXInputAttribute[] = [ - {name: "a_position", semantic: GFXVertexSemantic.POSITION, format: GFXFormat.RG32F}, - {name: "a_texCoord", semantic: GFXVertexSemantic.TEXCOORD, format: GFXFormat.RG32F}, + {name: "a_position", format: GFXFormat.RG32F}, + {name: "a_texCoord", format: GFXFormat.RG32F}, ]; this._quadIA = this._device.createInputAssembler({ From af2789ffd9402d0d19c3dc295876142298c707a0 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Sun, 30 Dec 2018 00:26:17 +0800 Subject: [PATCH 022/267] pass --- CHANGELOG.txt | 38 +-- EngineErrorMap.md | 2 +- cocos/3d/assets/effect-asset.js | 46 --- cocos/3d/assets/effect-asset.ts | 92 +++++ cocos/3d/builtin/effects.js | 4 +- cocos/camera/CCCamera.js | 2 +- cocos/core/{CCDirector.js => director.js} | 12 +- cocos/core/{CCGame.js => game.js} | 3 +- cocos/core/index.js | 6 +- cocos/core/platform/CCView.js | 18 +- cocos/core/{CCScheduler.js => scheduler.js} | 16 +- cocos/gfx/binding-layout.ts | 2 +- cocos/gfx/buffer.ts | 2 +- cocos/gfx/command-buffer.ts | 2 +- cocos/gfx/{gfx-define.ts => define.ts} | 316 +++++++++--------- cocos/gfx/input-assembler.ts | 2 +- cocos/gfx/pipeline-layout.ts | 2 +- cocos/gfx/pipeline-state.ts | 2 +- cocos/gfx/queue.ts | 2 +- cocos/gfx/render-pass.ts | 4 +- cocos/gfx/sampler.ts | 2 +- cocos/gfx/shader.ts | 2 +- cocos/gfx/texture-view.ts | 2 +- cocos/gfx/texture.ts | 2 +- cocos/gfx/webgl/webgl-buffer.ts | 2 +- cocos/gfx/webgl/webgl-command-buffer.ts | 2 +- cocos/gfx/webgl/webgl-commands.ts | 4 +- cocos/gfx/webgl/webgl-device.ts | 4 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 2 +- cocos/gfx/webgl/webgl-render-pass.ts | 4 +- cocos/gfx/webgl/webgl-state-cache.ts | 2 +- cocos/gfx/webgl/webgl-texture.ts | 2 +- cocos/gfx/webgl/webgl-window.ts | 4 +- cocos/gfx/window.ts | 2 +- cocos/pipeline/forward/forward-stage.ts | 2 +- cocos/pipeline/forward/test-stage.ts | 4 +- cocos/pipeline/render-pipeline.ts | 4 +- cocos/pipeline/render-stage.ts | 2 +- cocos/renderer/core/effect.js | 286 ---------------- cocos/renderer/core/effect.ts | 311 +++++++++++++++++ cocos/renderer/core/pass.ts | 64 ++-- .../core/{technique.js => technique.ts} | 17 +- cocos/renderer/index.js | 2 +- docs/apisrc.json | 10 +- tsconfig.json | 111 +++--- 45 files changed, 747 insertions(+), 675 deletions(-) delete mode 100644 cocos/3d/assets/effect-asset.js create mode 100644 cocos/3d/assets/effect-asset.ts rename cocos/core/{CCDirector.js => director.js} (99%) rename cocos/core/{CCGame.js => game.js} (99%) rename cocos/core/{CCScheduler.js => scheduler.js} (99%) rename cocos/gfx/{gfx-define.ts => define.ts} (71%) delete mode 100644 cocos/renderer/core/effect.js create mode 100644 cocos/renderer/core/effect.ts rename cocos/renderer/core/{technique.js => technique.ts} (61%) diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 6c0475d26c..ea43954e0f 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,7 +1,7 @@ ChangeLog: Cocos2d-x v3.8 @ September.6 2015 - + [NEW] spine: Supported Spine runtime 2.3 (Both native and web engine) [NEW] Animate: Added Animate's getCurrentFrameIndex function [NEW] network: Upgrade SocketIO support to v1.x @@ -58,9 +58,9 @@ Cocos2d-x v3.7.1 @ August.12 2015 Cocos2d-x v3.7 Final @ July 20 2015 [REFINE] web: Add compatible Uint16Array defintion - + [FIX] web: Fixed url check regular expression not supporting localhost issue - [FIX] web: Fixed issue that sprite doesn't update texture rect correctly + [FIX] web: Fixed issue that sprite doesn't update texture rect correctly Cocos2d-x v3.7 RC1 @ July 14 2015 [REFINE] Improved localStorage warning when disabled @@ -181,9 +181,9 @@ Cocos2d-JS v3.5 @ April 1 2015 * Replaced '==' with '===' for better performance. * Added `path` parameter in `ccs.load` to support modifying cocostudio project resource path. * Added animationList to Cocostudio ActionTimeline to support playing animation by name. -* Made ParticleSystem support creation from an map object. +* Made ParticleSystem support creation from an map object. * Added missing functions to `cc.Grid3D` and `cc.PageTurn3D`. -* Added tip message functions to `cc.TextFieldTTF` for mobile browser. +* Added tip message functions to `cc.TextFieldTTF` for mobile browser. * Added a function `cc.sys.openURL`. * Disabled retina display by default for better performance. * Added Bower support. @@ -192,15 +192,15 @@ Cocos2d-JS v3.5 @ April 1 2015 * Bug fixes: 1. Fixed a bug of chipmunk.js that it doesn't work under closure compiler advanced mode. 2. Fixed a bug of Cocos Studio parser that widget didn't set its layout component. - 3. Fixed grammatical mistakes in cocostudio parser logs. + 3. Fixed grammatical mistakes in cocostudio parser logs. 4. Fixed memory leak issue in `cc.LabelBMFont`. 5. Fixed a bug of `cc.Scale9Sprite` that its `updateDisplayColor` doesn't take effect. 6. Fixed a bug of Cocos Studio parser that `cc.Scale9Sprite` doesn't display correctly if its texture isn't preloaded. - 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance. + 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance. 8. Fixed a bug of Cocos Studio parser that the background color of `ccui.Layout` can't be parsed correctly. 9. Fixed a bug of `cc.ClippingNode` that it doesn't work when set `inverted` to true in Canvas Mode. 10. Fixed a bug of `ccs.Armature` that its name was modified to animation name when loading from json files. - 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view. + 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view. 12. Fixed a bug of `cc.Scheduler` that its parameter `repeat` is invalid in schedule function. 13. Fixed a bug of `cc.Scheduler` that `unschedule` function may fail. @@ -225,19 +225,19 @@ Cocos2d-JS v3.4 Beta0 @ March 19 2015 1. Added `getSpriteFrame` to `cc.Sprite` to fix API inconsistency. 2. Added `getObject` to `cc.TMXObjectGroup` to fix API inconsistency. 3. Added `addImageAsync` to `cc.textureCache` to fix API inconsistency. - 4. Fixed a bug of `cc.text` that its default font name is incorrect. + 4. Fixed a bug of `cc.text` that its default font name is incorrect. 5. Fixed a bug of `ccui.PageView` that its `getPage` doesn't work. 6. Fixed a bug of `ccui.ImageView` that its `loadTexture` doesn't work while it's invoked multiple times at the same frame. 7. Fixed a bug of `ccui` that its load event callbacks have some mistakes. 8. Fixed a bug of `cc.Layer` that its bake function doesn't work when the layer has a parent node. 9. Fixed typos in `cc.ClippingNode.WebGLRenderCmd` and `cc.ParticleSystem.WebGLRenderCmd` creation. - 10. Fixed a bug of `cc.Sprite` in `setTextureRect`. + 10. Fixed a bug of `cc.Sprite` in `setTextureRect`. 11. Fixed a bug of `cc.Screen`. 12. Fixed a bug of `cc.view` that it doesn't work on iOS 8.1.2. - 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero. - 14. Fixed a bug in hack for particles performance on canvas. + 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero. + 14. Fixed a bug in hack for particles performance on canvas. 15. Fixed a bug of `cc.audioEngine` that it doesn't work after minified/compiled. - 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8. + 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8. 17. Fixed a bug of `cc.CheckBox` that its position is incorrect when its texture isn't preloaded. 18. Fixed a bug of `cc.TMXLayer` that it stops to work after `setTileGID` called. 19. Fixed a bug of Cocos parser 2.x that it doesn't set widget's LayoutComponent. @@ -247,16 +247,16 @@ Cocos2d-JS v3.3 @ Feb.9, 2015 * Upgraded spine runtime to support the latest version and updated its test case. * Added an option "noCache" for debugging on browsers. -* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode. +* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode. * Added message to `ccs.load` when loading armature json file. * Improved particle system test case. * Bug fixes: - 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true. + 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true. 2. Fixed a bug of `cc.ClippingNode` when its stencil is `cc.Node` object in canvas mode. 3. Fixed a ccui bug that the position of widgets is incorrect after loaded v2.x json file with `ccs.load`. - 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work. - 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled. + 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work. + 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled. 6. Fixed a bug of `ccui.ScrollView` that its `dir` property is null when passing `DIR_NONE` as `direction` in `_endRecordSlidAction` function. Cocos2d-JS v3.3 RC0 @ Feb.1, 2015 @@ -309,7 +309,7 @@ Cocos2d-JS v3.3 Beta @ Jan.24, 2015 9. Fixed a bug of `cc.audioEngine` that its loading path is incorrect. 10. Fixed a bug of `ccui.Widget` that it can't touch when it's reused. 11. Fixed a bug of UI system that the `setNormalizedPosition` doesn't work. - 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`. + 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`. 13. Fixed release texture issue in canvas mode. 14. Fixed a bug of `ccs.actionManager` that its `getActionByName` doesn't work. 15. Fixed a bug of `cc.Sprite` that it can't draw without texture on WebGL mode. @@ -656,7 +656,7 @@ Cocos2d-html5-v3.0 alpha @ March.15, 2014 * Replace `replaceWithScene` and `runWithScene` with `runScene`. * move sys.xxx to cc.sys.xxx. * Refactor CCEGLView.js for better maintainability. -* Refactor CCScheduler.js for better maintainability. +* Refactor scheduler.js for better maintainability. * Remove arguments.callee which is forbidden in ECMAScript strict mode. * Refactor Array clean function for better performance. * Refactor some functions about array operation. diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 0726b09fc4..de7c7a4c46 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -276,7 +276,7 @@ warning: you CANNOT change update priority in scheduled function ### 1507 -CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f +scheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f ### 1508 diff --git a/cocos/3d/assets/effect-asset.js b/cocos/3d/assets/effect-asset.js deleted file mode 100644 index af5ae4aecd..0000000000 --- a/cocos/3d/assets/effect-asset.js +++ /dev/null @@ -1,46 +0,0 @@ -import Asset from "../../assets/CCAsset"; -import { property, ccclass } from "../../core/data/class-decorator"; - -@ccclass('cc.EffectAsset') -class EffectAsset extends Asset { - @property - techniques = []; - - @property - properties = {}; - - @property - shaders = []; - - onLoaded() { - let lib = cc.game._renderer._programLib; - this.shaders.forEach(s => lib.define(s)); - EffectAsset.register(this); - } -} - -let effects = EffectAsset._effects = {}; -EffectAsset.register = function(asset) { - effects[asset.name] = asset; -}; -EffectAsset.remove = function(name) { - if (effects[name]) { delete effects[name]; return; } - for (let n in effects) { - if (effects[n]._uuid === name) { - delete effects[n]; - return; - } - } -}; -EffectAsset.get = function(name) { - if (effects[name]) return effects[name]; - for (let n in effects) - if (effects[n]._uuid === name) - return effects[n]; -}; -EffectAsset.getAll = function() { - return effects; -}; - -export default EffectAsset; -cc.EffectAsset = EffectAsset; diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts new file mode 100644 index 0000000000..b268b8f979 --- /dev/null +++ b/cocos/3d/assets/effect-asset.ts @@ -0,0 +1,92 @@ +import Asset from '../../assets/CCAsset'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { PassInfo } from '../../renderer/core/pass'; + +const effects: { [name: string]: EffectAsset } = {}; + +interface TechniqueInfo { + passes: PassInfo[]; + queue?: number; + priority?: number; + lod?: number; +} + +interface PropertyMap { + [name: string]: { + type: number, + value: number | number[] | null, + }; +} + +interface ShaderInfo { + name: string; + vert: string; frag: string; + vert1: string; frag1: string; + defines: Array<{ + name: string; + type: string; + defines: string[]; + }>; + uniforms: Array<{ + name: string; + type: string; + binding: number; + defines: string[]; + } | { + blockName: string; + binding: number; + defines: string[]; + members: Array< { name: string, type: number } > + }>; + attributes: Array<{ + name: string; + type: string; + defines: string[]; + }>; + extensions: Array<{ + name: string; + define: string; + }>; +} + +@ccclass('cc.EffectAsset') +class EffectAsset extends Asset { + public static register(asset: EffectAsset) {effects[asset.name] = asset; } + public static remove(name: string) { + if (effects[name]) { delete effects[name]; return; } + for (const n in effects) { + if (effects[n]._uuid === name) { + delete effects[n]; + return; + } + } + } + public static get(name: string) { + if (effects[name]) { return effects[name]; } + for (const n in effects) { + if (effects[n]._uuid === name) { + return effects[n]; + } + } + } + public static getAll() { return effects; } + protected static _effects: { [name: string]: EffectAsset } = {}; + + @property + public techniques: TechniqueInfo[] = []; + + @property + public properties: PropertyMap = {}; + + @property + public shaders: ShaderInfo[] = []; + + public onLoaded() { + const lib = cc.game._renderer._programLib; + this.shaders.forEach((s) => lib.define(s)); + EffectAsset.register(this); + } +} + +export default EffectAsset; +cc.EffectAsset = EffectAsset; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 9e58c5f82d..d24467dbcf 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -6,7 +6,7 @@ export default [ "shaders": [ { "name": "aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9", - "vert": "\nattribute vec3 a_position;\nuniform mat4 _model;\nuniform mat4 _viewProj;\n#if USE_TEXTURE\n attribute vec2 a_uv0;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if USE_JOINTS_TEXTURE\nuniform sampler2D _u_jointsTexture;\nuniform float _u_jointsTextureSize;\nmat4 getBoneMatrix(const in float i) {\n float size = _u_jointsTextureSize;\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(_u_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(_u_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(_u_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(_u_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nuniform mat4 _u_jointMatrices[128];\nmat4 getBoneMatrix(const in float i) {\n return _u_jointMatrices[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 ;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_SKINNING\n pos = skinMatrix() * pos;\n #endif\n pos = _viewProj * _model * pos;\n #if USE_TEXTURE\n uv0 = a_uv0 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "vert": "\nattribute vec3 a_position;\nuniform mat4 _model;\nuniform mat4 _viewProj;\n#if USE_TEXTURE\n attribute vec2 a_texCoord1;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if USE_JOINTS_TEXTURE\nuniform sampler2D _u_jointsTexture;\nuniform float _u_jointsTextureSize;\nmat4 getBoneMatrix(const in float i) {\n float size = _u_jointsTextureSize;\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(_u_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(_u_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(_u_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(_u_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nuniform mat4 _u_jointMatrices[128];\nmat4 getBoneMatrix(const in float i) {\n return _u_jointMatrices[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 ;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_SKINNING\n pos = skinMatrix() * pos;\n #endif\n pos = _viewProj * _model * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord1 * 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"}, @@ -22,7 +22,7 @@ export default [ ], "attributes": [ {"name": "a_position", "type": 6, "defines": []}, - {"name": "a_uv0", "type": 5, "defines": ["USE_TEXTURE"]}, + {"name": "a_texCoord1", "type": 5, "defines": ["USE_TEXTURE"]}, {"name": "a_weights", "type": 7, "defines": ["USE_SKINNING"]}, {"name": "a_joints", "type": 7, "defines": ["USE_SKINNING"]} ], diff --git a/cocos/camera/CCCamera.js b/cocos/camera/CCCamera.js index 6c8c05e592..d197071376 100644 --- a/cocos/camera/CCCamera.js +++ b/cocos/camera/CCCamera.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import game from '../core/CCGame'; +import game from '../core/game'; import AffineTrans from '../core/value-types/affine-transform'; import mat4 from '../core/vmath/mat4'; import vec2 from '../core/vmath/vec2'; diff --git a/cocos/core/CCDirector.js b/cocos/core/director.js similarity index 99% rename from cocos/core/CCDirector.js rename to cocos/core/director.js index db624a218e..bddb5b76e0 100644 --- a/cocos/core/CCDirector.js +++ b/cocos/core/director.js @@ -28,8 +28,8 @@ import EventTarget from './event/event-target'; import eventManager from './platform/event-manager/CCEventManager'; import ccobject from './data/object'; -import game from './CCGame'; -import Scheduler from './CCScheduler'; +import game from './game'; +import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; import ComponentScheduler from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; @@ -229,7 +229,7 @@ class Director extends EventTarget { * !#en * Converts a view coordinate to an WebGL coordinate
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)
- * Implementation can be found in CCDirectorWebGL. + * Implementation can be found in directorWebGL. * !#zh 将触摸点的屏幕坐标转换为 WebGL View 下的坐标。 * @method convertToGL * @param {Vec2} uiPoint @@ -251,7 +251,7 @@ class Director extends EventTarget { * !#en * Converts an OpenGL coordinate to a view coordinate
* Useful to convert node points to window points for calls such as glScissor
- * Implementation can be found in CCDirectorWebGL. + * Implementation can be found in directorWebGL. * !#zh 将触摸点的 WebGL View 坐标转换为屏幕坐标。 * @method convertToUI * @param {Vec2} glPoint @@ -680,7 +680,7 @@ class Director extends EventTarget { /** * !#en * Enables or disables WebGL depth test.
- * Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js + * Implementation can be found in directorCanvas.js/directorWebGL.js * !#zh 启用/禁用深度测试(在 Canvas 渲染模式下不会生效)。 * @method setDepthTest * @param {Boolean} on @@ -696,7 +696,7 @@ class Director extends EventTarget { /** * !#en * Set color for clear screen.
- * (Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js) + * (Implementation can be found in directorCanvas.js/directorWebGL.js) * !#zh * 设置场景的默认擦除颜色。
* 支持全透明,但不支持透明度为中间值。要支持全透明需手工开启 cc.macro.ENABLE_TRANSPARENT_CANVAS。 diff --git a/cocos/core/CCGame.js b/cocos/core/game.js similarity index 99% rename from cocos/core/CCGame.js rename to cocos/core/game.js index b45b6bf6da..4f875a8ecc 100644 --- a/cocos/core/CCGame.js +++ b/cocos/core/game.js @@ -30,7 +30,6 @@ import debug from './platform/CCDebug'; import { addon } from './utils/js'; import renderer from '../renderer'; -import '../gfx'; import builtinResMgr from '../3d/builtin/init'; /** @@ -793,7 +792,7 @@ var game = { // renderer.initWebGL(localCanvas, opts); // this._renderContext = renderer.device._gl; } - + if (!this._gfxDevice) { //if (!this._renderContext) { diff --git a/cocos/core/index.js b/cocos/core/index.js index 7a4503041f..a2e7d069f8 100644 --- a/cocos/core/index.js +++ b/cocos/core/index.js @@ -33,6 +33,6 @@ import './data'; import './event'; import './platform'; import './value-types'; -import './CCGame'; -import './CCScheduler'; -import './CCDirector'; \ No newline at end of file +import './game'; +import './scheduler'; +import './director'; diff --git a/cocos/core/platform/CCView.js b/cocos/core/platform/CCView.js index 085573e7c5..b3a42a57f6 100644 --- a/cocos/core/platform/CCView.js +++ b/cocos/core/platform/CCView.js @@ -28,7 +28,7 @@ import EventTarget from '../event/event-target'; import '../data/class'; import macro from '../platform/CCMacro'; -import game from '../CCGame'; +import game from '../game'; import Size from '../value-types/size'; import Rect from '../value-types/rect'; @@ -166,7 +166,7 @@ class View extends EventTarget { init () { __BrowserGetter.init(this); - + this._initFrameSize(); this.enableAntiAlias(true); @@ -303,9 +303,9 @@ class View extends EventTarget { /** * !#en * Sets the orientation of the game, it can be landscape, portrait or auto. - * When set it to landscape or portrait, and screen w/h ratio doesn't fit, + * When set it to landscape or portrait, and screen w/h ratio doesn't fit, * cc.view will automatically rotate the game canvas using CSS. - * Note that this function doesn't have any effect in native, + * Note that this function doesn't have any effect in native, * in native, you need to set the application orientation in native project settings * !#zh 设置游戏屏幕朝向,它能够是横版,竖版或自动。 * 当设置为横版或竖版,并且屏幕的宽高比例不匹配时, @@ -331,7 +331,7 @@ class View extends EventTarget { var isLandscape = w >= h; if (CC_EDITOR || !cc.sys.isMobile || - (isLandscape && this._orientation & macro.ORIENTATION_LANDSCAPE) || + (isLandscape && this._orientation & macro.ORIENTATION_LANDSCAPE) || (!isLandscape && this._orientation & macro.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; locFrameSize.height = h; @@ -514,9 +514,9 @@ class View extends EventTarget { * @param {Boolean} enabled - Enable or disable auto full screen on mobile devices */ enableAutoFullScreen(enabled) { - if (enabled && - enabled !== this._autoFullScreen && - cc.sys.isMobile && + if (enabled && + enabled !== this._autoFullScreen && + cc.sys.isMobile && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { // Automatically full screen when user touches on mobile version this._autoFullScreen = true; @@ -1486,4 +1486,4 @@ let view = cc.view = new View(); */ cc.winSize = cc.v2(); -export default view; \ No newline at end of file +export default view; diff --git a/cocos/core/CCScheduler.js b/cocos/core/scheduler.js similarity index 99% rename from cocos/core/CCScheduler.js rename to cocos/core/scheduler.js index 4b76e4be79..fa2737e4ce 100644 --- a/cocos/core/CCScheduler.js +++ b/cocos/core/scheduler.js @@ -299,7 +299,7 @@ class Scheduler { this._arrayForTimers = []; // Speed up indexing //this._arrayForUpdates = []; // Speed up indexing } - + //-----------------------private method---------------------- _removeHashElement (element) { delete this._hashForTimers[element.target._id]; @@ -509,7 +509,7 @@ class Scheduler { * @param {Number} [repeat=cc.macro.REPEAT_FOREVER] * @param {Number} [delay=0] * @param {Boolean} paused - * @example {@link cocos2d/core/CCScheduler/schedule.js} + * @example {@link cocos2d/core/scheduler/schedule.js} * @typescript * schedule(callback: Function, target: any, interval: number, repeat: number, delay: number, paused?: boolean): void * schedule(callback: Function, target: any, interval: number, paused?: boolean): void @@ -694,7 +694,7 @@ class Scheduler { } } - /** + /** * !#en Unschedules the update callback for a given target. * !#zh 取消指定对象的 update 定时器。 * @method unscheduleUpdate @@ -724,7 +724,7 @@ class Scheduler { } } - /** + /** * !#en * Unschedules all scheduled callbacks for a given target. * This also includes the "update" callback. @@ -752,7 +752,7 @@ class Scheduler { var element = this._hashForTimers[targetId]; if (element) { var timers = element.timers; - if (timers.indexOf(element.currentTimer) > -1 && + if (timers.indexOf(element.currentTimer) > -1 && (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } @@ -839,7 +839,7 @@ class Scheduler { } } - /** + /** * !#en Checks whether a callback for a given target is scheduled. * !#zh 检查指定的回调函数和回调对象组合是否存在定时器。 * @method isScheduled @@ -862,7 +862,7 @@ class Scheduler { cc.errorID(1510); } } - + var element = this._hashForTimers[targetId]; if (!element) { @@ -1003,7 +1003,7 @@ class Scheduler { } //customer selectors - var self = this, + var self = this, element = self._hashForTimers[targetId]; if (element) { element.paused = true; diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index 59f535981a..f09d4d591b 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -2,7 +2,7 @@ import { GFXDevice } from './device'; import { GFXBuffer } from './buffer'; import { GFXTextureView } from './texture-view'; import { GFXSampler } from './sampler'; -import { GFXBindingType } from './gfx-define'; +import { GFXBindingType } from './define'; export interface GFXBinding { binding : number; diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 54b2c7da0b..f575bb4310 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -1,5 +1,5 @@ import { GFXDevice } from './device'; -import { GFXBufferUsage, GFXMemoryUsage, GFXBufferUsageBit, GFXMemoryUsageBit } from './gfx-define'; +import { GFXBufferUsage, GFXMemoryUsage, GFXBufferUsageBit, GFXMemoryUsageBit } from './define'; export interface GFXBufferInfo { usage: GFXBufferUsage; diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index 4b2eb5b6b9..fd50e99947 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -6,7 +6,7 @@ import { GFXPipelineState } from './pipeline-state'; import { GFXBindingLayout } from './binding-layout'; import { GFXTexture } from './texture'; import { GFXFramebuffer } from './framebuffer'; -import { GFXColor, GFXRect, GFXCommandBufferType, GFXBufferTextureCopy, GFXTextureLayout } from './gfx-define'; +import { GFXColor, GFXRect, GFXCommandBufferType, GFXBufferTextureCopy, GFXTextureLayout } from './define'; export interface GFXCommandBufferInfo { allocator : GFXCommandAllocator; diff --git a/cocos/gfx/gfx-define.ts b/cocos/gfx/define.ts similarity index 71% rename from cocos/gfx/gfx-define.ts rename to cocos/gfx/define.ts index 61c41f70c6..79045a1da7 100644 --- a/cocos/gfx/gfx-define.ts +++ b/cocos/gfx/define.ts @@ -16,22 +16,22 @@ export enum WebGLEXT { COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03, COMPRESSED_RGB_ETC1_WEBGL = 0x8D64, -}; +} export const GFX_MAX_VERTEX_ATTRIBUTES: number = 8; export const GFX_MAX_TEXTURE_UNITS: number = 16; export const GFX_MAX_ATTACHMENTS: number = 4; -export const GFX_ATTRIBUTE_POSITION = "a_position"; // 0 -export const GFX_ATTRIBUTE_COLOR = "a_color"; // 1 -export const GFX_ATTRIBUTE_COLOR1 = "a_color1"; // 2 -export const GFX_ATTRIBUTE_NORMAL = "a_normal"; // 3 -export const GFX_ATTRIBUTE_TANGENT = "a_tangent"; // 4 -export const GFX_ATTRIBUTE_BINORMAL = "a_binormal"; // 5 -export const GFX_ATTRIBUTE_TEXCOORD = "a_texCoord"; // 6 -export const GFX_ATTRIBUTE_TEXCOORD1 = "a_texCoord1"; // 7 -export const GFX_ATTRIBUTE_JOINTS = "a_joints"; // 8 -export const GFX_ATTRIBUTE_WEIGHTS = "a_weights"; // 9 +export const GFX_ATTRIBUTE_POSITION = 'a_position'; // 0 +export const GFX_ATTRIBUTE_COLOR = 'a_color'; // 1 +export const GFX_ATTRIBUTE_COLOR1 = 'a_color1'; // 2 +export const GFX_ATTRIBUTE_NORMAL = 'a_normal'; // 3 +export const GFX_ATTRIBUTE_TANGENT = 'a_tangent'; // 4 +export const GFX_ATTRIBUTE_BINORMAL = 'a_binormal'; // 5 +export const GFX_ATTRIBUTE_TEXCOORD = 'a_texCoord'; // 6 +export const GFX_ATTRIBUTE_TEXCOORD1 = 'a_texCoord1'; // 7 +export const GFX_ATTRIBUTE_JOINTS = 'a_joints'; // 8 +export const GFX_ATTRIBUTE_WEIGHTS = 'a_weights'; // 9 export enum GFXType { UNKNOWN, @@ -67,7 +67,7 @@ export enum GFXType { SAMPLER3D, SAMPLER_CUBE, COUNT, -}; +} export enum GFXFormat { @@ -189,7 +189,7 @@ export enum GFXFormat { PVRTC_RGBA4, PVRTC2_2BPP, PVRTC2_4BPP, -}; +} export enum GFXBufferUsageBit { NONE = 0, @@ -199,7 +199,7 @@ export enum GFXBufferUsageBit { VERTEX = 0x8, UNIFORM = 0x10, STORAGE = 0x20, -}; +} export type GFXBufferUsage = GFXBufferUsageBit; @@ -207,7 +207,7 @@ export enum GFXMemoryUsageBit { NONE = 0, DEVICE = 0x1, HOST = 0x2, -}; +} export type GFXMemoryUsage = GFXMemoryUsageBit; @@ -215,7 +215,7 @@ export enum GFXBufferAccessBit { NONE = 0, READ = 0x1, WRITE = 0x2, -}; +} export type GFXBufferAccess = GFXBufferAccessBit; @@ -234,24 +234,24 @@ export enum GFXPrimitiveMode { TRIANGLE_PATCH_ADJACENCY, QUAD_PATCH_LIST, ISO_LINE_LIST, -}; +} export enum GFXPolygonMode { FILL, LINE, POINT, -}; +} export enum GFXShadeModel { GOURAND, FLAT, -}; +} export enum GFXCullMode { NONE, FRONT, BACK, -}; +} export enum GFXComparisonFunc { NEVER, @@ -262,18 +262,18 @@ export enum GFXComparisonFunc { NOT_EQUAL, GREATER_EQUAL, ALWAYS, -}; +} export enum GFXStencilOp { - KEEP, ZERO, + KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, DECR_WRAP, -}; +} export enum GFXBlendOp { ADD, @@ -281,7 +281,7 @@ export enum GFXBlendOp { REV_SUB, MIN, MAX, -}; +} export enum GFXBlendFactor { ZERO, @@ -299,7 +299,7 @@ export enum GFXBlendFactor { ONE_MINUS_CONSTANT_COLOR, CONSTANT_ALPHA, ONE_MINUS_CONSTANT_ALPHA, -}; +} export enum GFXColorMask { NONE = 0x0, @@ -308,27 +308,27 @@ export enum GFXColorMask { B = 0x4, A = 0x8, ALL = R | G | B | A, -}; +} export enum GFXFilter { NONE, POINT, LINEAR, ANISOTROPIC, -}; +} export enum GFXAddress { WRAP, MIRROR, CLAMP, BORDER, -}; +} export enum GFXTextureType { TEX1D, TEX2D, TEX3D, -}; +} export enum GFXTextureUsageBit { NONE = 0, @@ -340,7 +340,7 @@ export enum GFXTextureUsageBit { DEPTH_STENCIL_ATTACHMENT = 0x20, TRANSIENT_ATTACHMENT = 0x40, INPUT_ATTACHMENT = 0x80, -}; +} export type GFXTextureUsage = GFXTextureUsageBit; @@ -349,7 +349,7 @@ export enum GFXTextureFlagBit { GEN_MIPMAP = 0x1, CUBEMAP = 0x2, BAKUP_BUFFER = 0x4, -}; +} export type GFXTextureFlags = GFXTextureFlagBit; @@ -360,7 +360,7 @@ export enum GFXTextureViewType { CUBE, TV1D_ARRAY, TV2D_ARRAY, -}; +} export enum GFXShaderType { VERTEX, @@ -370,32 +370,32 @@ export enum GFXShaderType { FRAGMENT, COMPUTE, COUNT, -}; +} export enum GFXBindingType { UNKNOWN, UNIFORM_BUFFER, SAMPLER, STORAGE_BUFFER, -}; +} export enum GFXCommandBufferType { PRIMARY, SECONDARY, -}; +} // Enumeration all possible values of operations to be performed on initially Loading a Framebuffer Object. export enum GFXLoadOp { LOAD, // Load the contents from the fbo from previous CLEAR, // Clear the fbo DISCARD, // Ignore writing to the fbo and keep old data -}; +} // Enumerates all possible values of operations to be performed when Storing to a Framebuffer Object. export enum GFXStoreOp { STORE, // Write the source to the destination DISCARD, // Don't write the source to the destination -}; +} export enum GFXTextureLayout { UNDEFINED, @@ -408,19 +408,19 @@ export enum GFXTextureLayout { TRANSFER_DST_OPTIMAL, PREINITIALIZED, PRESENT_SRC, -}; +} export enum GFXPipelineBindPoint { GRAPHICS, COMPUTE, RAY_TRACING, -}; +} export enum GFXQueueType { GRAPHICS, COMPUTE, TRANSFER, -}; +} // Interfaces @@ -429,7 +429,7 @@ export interface GFXRect { top: number; width: number; height: number; -}; +} export interface GFXViewport { left: number; @@ -438,21 +438,21 @@ export interface GFXViewport { height: number; minDepth: number; maxDepth: number; -}; +} export interface GFXColor { r: number; g: number; b: number; a: number; -}; +} export interface GFXTextureSubres { baseMipLevel: number; levelCount: number; baseArrayLayer: number; layerCount: number; -}; +} export interface GFXTextureCopy { srcSubres: GFXTextureSubres; @@ -460,7 +460,7 @@ export interface GFXTextureCopy { dstSubres: GFXTextureSubres; dstOffset: number[]; extent: number[]; -}; +} export interface GFXBufferTextureCopy { buffOffset: number; @@ -469,7 +469,7 @@ export interface GFXBufferTextureCopy { texOffset: number[]; texExtent: number[]; texSubres: GFXTextureSubres; -}; +} export interface GFXFormatInfo { readonly name: string; @@ -480,112 +480,112 @@ export interface GFXFormatInfo { readonly hasDepth: boolean; readonly hasStencil: boolean; readonly isCompressed: boolean; -}; +} export const GFXFormatInfos: GFXFormatInfo[] = [ - { name: "UNKNOWN", size: 0, count: 0, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'UNKNOWN', size: 0, count: 0, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "A8", size: 1, count: 1, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "L8", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "LA8", size: 1, count: 2, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'A8', size: 1, count: 1, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'L8', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'LA8', size: 1, count: 2, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R8", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R8SN", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R8UI", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R8I", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R16F", size: 2, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R16UI", size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R16I", size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R32F", size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R32UI", size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R32I", size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8SN', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8UI', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R8I', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R16F', size: 2, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R16UI', size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R16I', size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R32F', size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R32UI', size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R32I', size: 4, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG8", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG8SN", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG8UI", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG8I", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG16F", size: 4, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG16UI", size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG16I", size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG32F", size: 8, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG32UI", size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RG32I", size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8SN', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8UI', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG8I', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG16F', size: 4, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG16UI', size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG16I', size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG32F', size: 8, count: 2, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG32UI', size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RG32I', size: 8, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB8", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "SRGB8", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB8SN", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB8UI", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB8I", size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB16F", size: 6, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB16UI", size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB16I", size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB32F", size: 12, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB32UI", size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB32I", size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'SRGB8', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8SN', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8UI', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB8I', size: 3, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB16F', size: 6, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB16UI', size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB16I', size: 6, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB32F', size: 12, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB32UI', size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB32I', size: 12, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA8", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "SRGB8_A8", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA8SN", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA8UI", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA8I", size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA16F", size: 8, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA16UI", size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA16I", size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA32F", size: 16, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA32UI", size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA32I", size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'SRGB8_A8', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8SN', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8UI', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA8I', size: 4, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA16F', size: 8, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA16UI', size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA16I', size: 8, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA32F', size: 16, count: 4, isFloating: true, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA32UI', size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA32I', size: 16, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R5G6B5", size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "R11G11B10F", size: 4, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB5A1", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGBA4", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB10A2", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB10A2UI", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "RGB9E5", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R5G6B5', size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'R11G11B10F', size: 4, count: 3, isFloating: true, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB5A1', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGBA4', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB10A2', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB10A2UI', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, + { name: 'RGB9E5', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: false }, - { name: "D16", size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, - { name: "D16S8", size: 3, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, - { name: "D24", size: 3, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, - { name: "D24S8", size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, - { name: "D32F", size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, - { name: "D32FS8", size: 5, count: 2, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: 'D16', size: 2, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: 'D16S8', size: 3, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: 'D24', size: 3, count: 1, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: 'D24S8', size: 4, count: 2, isFloating: false, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, + { name: 'D32F', size: 4, count: 1, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: false, isCompressed: false }, + { name: 'D32FS8', size: 5, count: 2, isFloating: true, hasAlpha: false, hasDepth: true, hasStencil: true, isCompressed: false }, - { name: "BC1", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC1_ALPHA", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC1_SRGB", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC1_SRGB_ALPHA", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC2", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC2_SRGB", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC3", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC3_SRGB", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC4", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC4_SNORM", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC5", size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC5_SNORM", size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC6H_UF16", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC6H_SF16", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC7", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "BC7_SRGB", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1_ALPHA', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1_SRGB', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC1_SRGB_ALPHA', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC2', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC2_SRGB', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC3', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC3_SRGB', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC4', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC4_SNORM', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC5', size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC5_SNORM', size: 1, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC6H_UF16', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC6H_SF16', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC7', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'BC7_SRGB', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC_RGB8", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC2_RGB8", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC2_SRGB8", size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC2_RGB8_A1", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC2_SRGB8_A1", size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC2_RGBA8", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "ETC2_SRGB8_A8", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "EAC_R11", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "EAC_R11SN", size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "EAC_RG11", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "EAC_RG11SN", size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC_RGB8', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_RGB8', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_SRGB8', size: 1, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_RGB8_A1', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_SRGB8_A1', size: 1, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_RGBA8', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'ETC2_SRGB8_A8', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_R11', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_R11SN', size: 1, count: 1, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_RG11', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'EAC_RG11SN', size: 2, count: 2, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "PVRTC_RGB2", size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "PVRTC_RGBA2", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "PVRTC_RGB4", size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "PVRTC_RGBA4", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "PVRTC2_2BPP", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, - { name: "PVRTC2_4BPP", size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGB2', size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGBA2', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGB4', size: 2, count: 3, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC_RGBA4', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC2_2BPP', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, + { name: 'PVRTC2_4BPP', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, ]; export function GFXFormatSize(format: GFXFormat, width: number, height: number, depth: number): number { @@ -695,28 +695,16 @@ export function GFXGetTypeSize(type: GFXType): number { } } -export function GFXGetAttributeBinding(name: string) : number { - if (name === GFX_ATTRIBUTE_POSITION) { - return 20; - } else if (name === GFX_ATTRIBUTE_COLOR) { - return 21; - } else if (name === GFX_ATTRIBUTE_COLOR1) { - return 22; - } else if (name === GFX_ATTRIBUTE_NORMAL) { - return 23; - } else if (name === GFX_ATTRIBUTE_TANGENT) { - return 24; - } else if (name === GFX_ATTRIBUTE_BINORMAL) { - return 25; - } else if (name === GFX_ATTRIBUTE_TEXCOORD) { - return 26; - } else if (name === GFX_ATTRIBUTE_TEXCOORD1) { - return 27; - } else if (name === GFX_ATTRIBUTE_JOINTS) { - return 28; - } else if (name === GFX_ATTRIBUTE_WEIGHTS) { - return 29; - } else { - return -1; - } -} +const GFXBuiltinAttributeBindings = { + [GFX_ATTRIBUTE_POSITION]: 20, + [GFX_ATTRIBUTE_COLOR]: 21, + [GFX_ATTRIBUTE_COLOR1]: 22, + [GFX_ATTRIBUTE_NORMAL]: 23, + [GFX_ATTRIBUTE_TANGENT]: 24, + [GFX_ATTRIBUTE_BINORMAL]: 25, + [GFX_ATTRIBUTE_TEXCOORD]: 26, + [GFX_ATTRIBUTE_TEXCOORD1]: 27, + [GFX_ATTRIBUTE_JOINTS]: 28, + [GFX_ATTRIBUTE_WEIGHTS]: 29, +}; +export { GFXBuiltinAttributeBindings }; diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 9d54ee9ace..88be409ef4 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,5 +1,5 @@ import { GFXDevice } from './device'; -import { GFXFormat } from './gfx-define'; +import { GFXFormat } from './define'; import { GFXBuffer } from './buffer'; export interface GFXInputAttribute { diff --git a/cocos/gfx/pipeline-layout.ts b/cocos/gfx/pipeline-layout.ts index 00b0a34c54..9f883248bf 100644 --- a/cocos/gfx/pipeline-layout.ts +++ b/cocos/gfx/pipeline-layout.ts @@ -1,6 +1,6 @@ import { GFXDevice } from './device'; import { GFXBindingLayout } from './binding-layout'; -import { GFXShaderType } from './gfx-define'; +import { GFXShaderType } from './define'; export interface GFXPushConstantRange { shaderType : GFXShaderType; diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index 410c20a5be..fbb24740e6 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -3,7 +3,7 @@ import { GFXShader } from './shader'; import { GFXRenderPass } from './render-pass'; import { GFXPipelineLayout } from './pipeline-layout'; import { GFXInputAttribute } from './input-assembler'; -import { GFXPolygonMode, GFXShadeModel, GFXCullMode, GFXComparisonFunc, GFXStencilOp, GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXPrimitiveMode } from './gfx-define'; +import { GFXPolygonMode, GFXShadeModel, GFXCullMode, GFXComparisonFunc, GFXStencilOp, GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXPrimitiveMode } from './define'; export class GFXRasterizerState { isDiscard: boolean = false; diff --git a/cocos/gfx/queue.ts b/cocos/gfx/queue.ts index a0ddfe2928..15de82f7c5 100644 --- a/cocos/gfx/queue.ts +++ b/cocos/gfx/queue.ts @@ -1,6 +1,6 @@ import { GFXDevice } from './device'; import { GFXCommandBuffer } from './command-buffer'; -import { GFXQueueType } from './gfx-define'; +import { GFXQueueType } from './define'; export interface GFXQueueInfo { type : GFXQueueType; diff --git a/cocos/gfx/render-pass.ts b/cocos/gfx/render-pass.ts index 8cd3fcaab2..ae832ee6c2 100644 --- a/cocos/gfx/render-pass.ts +++ b/cocos/gfx/render-pass.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint } from './gfx-define'; +import { GFXFormat, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint } from './define'; import { GFXDevice } from './device'; export class GFXColorAttachment @@ -35,7 +35,7 @@ export interface GFXSubPassInfo export interface GFXRenderPassInfo { - colorAttachment? : GFXColorAttachment[]; + colorAttachments? : GFXColorAttachment[]; depthStencilAttachment? : GFXDepthStencilAttachment; //subPasses? : GFXSubPassInfo[]; }; diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index 885e0fe8cc..994c6ea4e0 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -1,5 +1,5 @@ import { GFXDevice } from './device'; -import { GFXFilter, GFXAddress, GFXComparisonFunc } from './gfx-define'; +import { GFXFilter, GFXAddress, GFXComparisonFunc } from './define'; export interface GFXSamplerInfo { name? : string; diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index b175bc1dd3..d21ac8aaf5 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -1,5 +1,5 @@ import { GFXDevice } from './device'; -import { GFXType, GFXShaderType } from './gfx-define'; +import { GFXType, GFXShaderType } from './define'; export interface GFXShaderMacro { macro: string; diff --git a/cocos/gfx/texture-view.ts b/cocos/gfx/texture-view.ts index 37a13a70f7..bceeeb3d56 100644 --- a/cocos/gfx/texture-view.ts +++ b/cocos/gfx/texture-view.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXTextureViewType } from './gfx-define'; +import { GFXFormat, GFXTextureViewType } from './define'; import { GFXDevice } from './device'; import { GFXTexture } from './texture'; diff --git a/cocos/gfx/texture.ts b/cocos/gfx/texture.ts index 6650e475ba..92e8e1d6d0 100644 --- a/cocos/gfx/texture.ts +++ b/cocos/gfx/texture.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXTextureType, GFXTextureUsage, GFXTextureFlags, GFXTextureUsageBit, GFXTextureFlagBit } from './gfx-define'; +import { GFXFormat, GFXTextureType, GFXTextureUsage, GFXTextureFlags, GFXTextureUsageBit, GFXTextureFlagBit } from './define'; import { GFXDevice } from './device'; export interface GFXTextureInfo { diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index ecc150f184..86dff88ccf 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -2,7 +2,7 @@ import { GFXBufferInfo, GFXBuffer } from '../buffer'; import { GFXDevice } from '../device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXMemoryUsageBit } from '../gfx-define'; +import { GFXMemoryUsageBit } from '../define'; export class WebGLGFXBuffer extends GFXBuffer { diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 00464cf366..09746d9d34 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -15,7 +15,7 @@ import { GFXBindingLayout } from '../binding-layout'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; import { GFXTexture } from '../texture'; import { WebGLGFXTexture } from './webgl-texture'; -import { GFXColor, GFXViewport, GFXRect, GFXBufferTextureCopy, GFXTextureLayout } from '../gfx-define'; +import { GFXColor, GFXViewport, GFXRect, GFXBufferTextureCopy, GFXTextureLayout } from '../define'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index f9b2826577..46b4ec0946 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,6 +1,6 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXGetAttributeBinding } from "../gfx-define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXBuiltinAttributeBindings } from "../define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; @@ -818,7 +818,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG varName = info.name; } - let glLoc = GFXGetAttributeBinding(varName); + let glLoc = GFXBuiltinAttributeBindings[varName]; if(glLoc >= 0) { gl.bindAttribLocation(gpuShader.glProgram, glLoc, varName); diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 9b58cd1393..c8518a4d01 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -31,7 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit } from '../gfx-define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit } from '../define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -476,7 +476,7 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { let gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, - colorAttachments: info.colorAttachment? info.colorAttachment : [], + colorAttachments: info.colorAttachments? info.colorAttachments : [], depthStencilAttachment: info.depthStencilAttachment? info.depthStencilAttachment : null, } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index dc33439b9b..8a3877d582 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage } from "../gfx-define"; +import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage } from "../define"; import { GFXColorAttachment, GFXDepthStencilAttachment } from "../render-pass"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; import { GFXInputAttribute } from "../input-assembler"; diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts index 04fbd725eb..b907ce4982 100644 --- a/cocos/gfx/webgl/webgl-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -11,8 +11,8 @@ export class WebGLGFXRenderPass extends GFXRenderPass { public initialize(info: GFXRenderPassInfo): boolean { - if (info.colorAttachment) { - this._colorInfos = info.colorAttachment; + if (info.colorAttachments) { + this._colorInfos = info.colorAttachments; } if (info.depthStencilAttachment) { diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index cb79db0312..5a6eecea2e 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -1,4 +1,4 @@ -import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES, GFXViewport, GFXRect } from "../gfx-define"; +import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES, GFXViewport, GFXRect } from "../define"; import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; export interface WebGLTexUnit diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index 04a30fe713..56c2293505 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -2,7 +2,7 @@ import { GFXDevice } from '../device'; import { WebGLGPUTexture } from './webgl-gpu-objects'; import { WebGLGFXDevice } from './webgl-device'; import { GFXTexture, GFXTextureInfo } from '../texture'; -import { GFXFormatSurfaceSize, GFXTextureFlagBit } from '../gfx-define'; +import { GFXFormatSurfaceSize, GFXTextureFlagBit } from '../define'; export class WebGLGFXTexture extends GFXTexture { diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index 95f599767d..f07a612024 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -1,7 +1,7 @@ import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { GFXWindow, GFXWindowInfo } from '../window'; -import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXStoreOp } from '../gfx-define'; +import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXStoreOp } from '../define'; export class WebGLGFXWindow extends GFXWindow { @@ -34,7 +34,7 @@ export class WebGLGFXWindow extends GFXWindow { } this._renderPass = this._device.createRenderPass({ - colorAttachment: [{ + colorAttachments: [{ format: this._colorFmt, loadOp: GFXLoadOp.CLEAR, storeOp: GFXStoreOp.STORE, diff --git a/cocos/gfx/window.ts b/cocos/gfx/window.ts index a84949d57e..f4f60e6ee3 100644 --- a/cocos/gfx/window.ts +++ b/cocos/gfx/window.ts @@ -2,7 +2,7 @@ import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; import { GFXTexture } from './texture'; import { GFXTextureView } from './texture-view'; -import { GFXFormat } from './gfx-define'; +import { GFXFormat } from './define'; import { GFXRenderPass } from './render-pass'; export interface GFXWindowInfo { diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index a8e34bc09a..a89647a1e8 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -3,7 +3,7 @@ import { RenderFlow } from "../render-flow"; import { GFXCommandBuffer } from "../../gfx/command-buffer"; import { RenderView } from "../render-view"; import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType } from "../../gfx/gfx-define"; +import { GFXCommandBufferType } from "../../gfx/define"; import { GFXInputAssembler } from "../../gfx/input-assembler"; export class ForwardStage extends RenderStage { diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 8887fe1588..375d7bf03b 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -3,7 +3,7 @@ import { RenderFlow } from "../render-flow"; import { GFXCommandBuffer } from "../../gfx/command-buffer"; import { RenderView } from "../render-view"; import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode } from "../../gfx/gfx-define"; +import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode } from "../../gfx/define"; import { GFXInputAssembler } from "../../gfx/input-assembler"; import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; import { GFXShader } from "../../gfx/shader"; @@ -122,7 +122,7 @@ export class TestStage extends RenderStage { this._pipelineState.destroy(); this._pipelineState = null; } - + if (this._cmdBuff) { this._cmdBuff.destroy(); this._cmdBuff = null; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 64c8fcbc69..1feb09f8d2 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -5,7 +5,7 @@ import { GFXRenderPass } from "../gfx/render-pass"; import { GFXDevice } from "../gfx/device"; import { GFXBuffer } from "../gfx/buffer"; import { GFXInputAssembler, GFXInputAttribute } from "../gfx/input-assembler"; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../gfx/gfx-define"; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../gfx/define"; export enum RenderPassStage { FORWARD = 0, @@ -145,7 +145,7 @@ export abstract class RenderPipeline { this._quadIB.update(indices); // create input assembler - + let attributes: GFXInputAttribute[] = [ {name: "a_position", format: GFXFormat.RG32F}, {name: "a_texCoord", format: GFXFormat.RG32F}, diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index d0e9ee46f6..90011e91fa 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -5,7 +5,7 @@ import { GFXCommandBuffer } from "../gfx/command-buffer"; import { RenderFlow } from "./render-flow"; import { GFXDevice } from "../gfx/device"; import { RenderPipeline } from "./render-pipeline"; -import { GFXColor, GFX_MAX_ATTACHMENTS, GFXRect } from "../gfx/gfx-define"; +import { GFXColor, GFX_MAX_ATTACHMENTS, GFXRect } from "../gfx/define"; export interface RenderStageInfo { name?: string; diff --git a/cocos/renderer/core/effect.js b/cocos/renderer/core/effect.js deleted file mode 100644 index af0ca98e13..0000000000 --- a/cocos/renderer/core/effect.js +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import enums from '../enums'; -import Pass from './pass'; -import Technique from './technique'; -import { Vec2, Vec3, Vec4, Color, Mat4 } from '../../core/value-types'; -import { CCObject } from '../../core/data'; -import Texture2D from '../gfx/texture-2d'; -import TextureCube from '../gfx/texture-cube'; - -let _typeMap = { - [enums.PARAM_INT]: Number, - [enums.PARAM_INT2]: Vec2, - [enums.PARAM_INT3]: Vec3, - [enums.PARAM_INT4]: Vec4, - [enums.PARAM_FLOAT]: Number, - [enums.PARAM_FLOAT2]: Vec2, - [enums.PARAM_FLOAT3]: Vec3, - [enums.PARAM_FLOAT4]: Vec4, - [enums.PARAM_COLOR3]: Color, - [enums.PARAM_COLOR4]: Color, - [enums.PARAM_MAT4]: Mat4, - [enums.PARAM_TEXTURE_2D]: Texture2D, - [enums.PARAM_TEXTURE_CUBE]: TextureCube, - number: Number, - boolean: Boolean, - default: CCObject -}; -let getInstanceType = function(t) { return _typeMap[t] || _typeMap.default; }; -let typeCheck = function(value, type) { - let instanceType = getInstanceType(type); - switch (typeof value) { - case 'object': return (value === null) || (value instanceof instanceType); - case 'number': return instanceType === Number; - default: return false; - } -}; - -let _globalTechLod = 600; - -class Effect { - /** - * @param {Array} techniques - */ - constructor(name, techniques, programs, properties = {}, lod = -1) { - this._name = name; - this._techniques = techniques; - this._properties = properties; - this._programs = programs; - this._defines = {}; - this._dependencies = {}; - this._maxLOD = lod; - this.selectTechnique(); - } - - set LOD(lod) { - if (lod === this._maxLOD) { - return; - } - this._maxLOD = lod; - this.selectTechnique(); - } - - clear() { - this._techniques.length = 0; - this._properties = {}; - this._defines = {}; - this._dependencies.length = 0; - } - - getTechnique(index) { - if (index < 0 || index >= this._techniques.length) - return null; - return this._techniques[index]; - } - - getProperty(name) { - if (!this._properties[name]) { - console.warn(`Failed to get property ${name}, property not found.`); - return null; - } - return this._properties[name].value; - } - - setProperty(name, value) { - let prop = this._properties[name]; - if (!prop) { - console.warn(`Failed to set property ${name}, property not found.`); - return; - } - else if (!typeCheck(value, prop.type)) { - console.warn(`Failed to set property ${name}, property type mismatch.`); - return; - } - this._properties[name].value = value; - } - - getDefine(name) { - let def = this._defines[name]; - if (def !== undefined) return def; - console.warn(`Failed to get define ${name}, define not found.`); - return null; - } - - define(name, value) { - if (this._defines[name] !== undefined) this._defines[name] = value; - else console.warn(`Failed to set define ${name}, define not found.`); - } - - extractDefines(out = {}) { - return Object.assign(out, this._defines); - } - - extractDependencies(out = {}) { - return Object.assign(out, this._dependencies); - } - - getActiveTechnique() { - return this._techniques[this._activeTechIdx]; - } - - selectTechnique() { - let lod = this._maxLOD === -1 ? _globalTechLod : this._maxLOD; - this._activeTechIdx = 0; - for (let i = 0; i < this._techniques.length; i++) { - if (this._techniques[i]._lod <= lod) { - this._activeTechIdx = i; - break; - } - } - - // defines - this._defines = {}; - this._techniques[this._activeTechIdx].passes.forEach(pass => this._programs[pass._programName].defines.forEach(def => - this._defines[def.name] = getInstanceCtor(def.type)())); - - // extensions - this._dependencies = {}; - this._techniques[this._activeTechIdx].passes.forEach(pass => this._programs[pass._programName].extensions - .filter(ext => ext.define).forEach(ext => this._dependencies[ext.define] = ext.name)); - } - - static setGlobalLod(lod) { - _globalTechLod = lod; - } -} - -let _ctorMap = { - [Number]: v => v || 0, - [Boolean]: v => v || false, - [Vec2]: v => v ? cc.v2(v[0], v[1]) : cc.v2(), - [Vec3]: v => v ? cc.v3(v[0], v[1], v[2]) : cc.v3(), - [Vec4]: v => v ? cc.v4(v[0], v[1], v[2], v[3]) : cc.v4(), - [Color]: v => v ? cc.color(v[0] * 255, v[1] * 255, v[2] * 255, - (v[3] || 1) * 255) : cc.color(), - [Mat4]: v => v ? cc.mat4( - v[0], v[1], v[2], v[3], - v[4], v[5], v[6], v[7], - v[8], v[9], v[10], v[11], - v[12], v[13], v[14], v[15], - ) : cc.mat4(), - [Texture2D]: () => null, - [TextureCube]: () => null, - [CCObject]: () => null -}; -let getInstanceCtor = function(t) { return _ctorMap[getInstanceType(t)]; }; - -let getInvolvedPrograms = function(effect) { - let programs = {}, lib = cc.game._renderer._programLib; - effect.techniques.forEach(tech => { - tech.passes.forEach(pass => { - programs[pass.program] = lib.getTemplate(pass.program); - }); - }); - return programs; -}; - -let parseProperties = (function() { - function genPropInfo(displayName, type, value) { - return { - type: type, - displayName: displayName, - instanceType: getInstanceType(type), - value: getInstanceCtor(type)(value) - }; - } - return function(effect, programs) { - let props = {}; - // properties may be specified in the shader too - for (let p in programs) { - programs[p].uniforms.forEach(prop => { - if (!prop.property) return; - props[prop.name] = genPropInfo(prop.displayName, prop.type, prop.value); - }); - } - for (let prop in effect.properties) { - let propInfo = effect.properties[prop], uniformInfo; - // always try getting the type from shaders first - if (propInfo.tech !== undefined && propInfo.pass !== undefined) { - let pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program; - uniformInfo = programs[pname].uniforms.find(u => u.name === prop); - } else { - for (let p in programs) { - uniformInfo = programs[p].uniforms.find(u => u.name === prop); - if (uniformInfo) break; - } - } - // the property is not defined in all the shaders used in techs - if (!uniformInfo) { - console.warn(`illegal property: ${prop}`); - continue; - } - // TODO: different param with same name for different passes - props[prop] = genPropInfo( - propInfo.displayName || uniformInfo.displayName, - propInfo.type || uniformInfo.type, - propInfo.value || uniformInfo.value); - } - return props; - }; -})(); - -Effect.parseEffect = function(effect) { - // techniques - let techNum = effect.techniques.length, tech; - let programs = getInvolvedPrograms(effect); - let techniques = new Array(techNum); - for (let j = 0; j < techNum; ++j) { - tech = effect.techniques[j]; - let passNum = tech.passes.length; - let passes = new Array(passNum); - for (let k = 0; k < passNum; ++k) { - let pass = tech.passes[k]; - passes[k] = new Pass(pass.program); - passes[k].setStage(pass.stage); - passes[k].setDepth(pass.depthTest, pass.depthWrite, pass.depthFunc); - passes[k].setCullMode(pass.cullMode); - passes[k].setBlend(pass.blend, pass.blendEq, pass.blendSrc, - pass.blendDst, pass.blendAlphaEq, pass.blendSrcAlpha, pass.blendDstAlpha, pass.blendColor); - passes[k].setStencilFront(pass.stencilTest, pass.stencilFuncFront, pass.stencilRefFront, pass.stencilMaskFront, - pass.stencilFailOpFront, pass.stencilZFailOpFront, pass.stencilZPassOpFront, pass.stencilWriteMaskFront); - passes[k].setStencilBack(pass.stencilTest, pass.stencilFuncBack, pass.stencilRefBack, pass.stencilMaskBack, - pass.stencilFailOpBack, pass.stencilZFailOpBack, pass.stencilZPassOpBack, pass.stencilWriteMaskBack); - } - techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); - } - // uniforms - let props = parseProperties(effect, programs), uniforms = {}; - for (let pn in programs) { - programs[pn].uniforms.forEach(u => { - let prop = props[u.name]; - uniforms[u.name] = { - type: prop ? prop.type : u.type, - value: prop ? prop.value : getInstanceCtor(u.type)(u.value) - }; - }); - } - - let parsedEffect = new Effect(effect.name, techniques, programs, uniforms); - return parsedEffect; -}; - -if (CC_EDITOR) { - Effect.parseForInspector = function(effect) { - let programs = getInvolvedPrograms(effect); - let props = parseProperties(effect, programs), defines = {}; - for (let pn in programs) { - programs[pn].uniforms.forEach(u => { - let prop = props[u.name]; - if (!prop) return; - prop.defines = u.defines; - }); - programs[pn].defines.forEach(define => { - defines[define.name] = { - instanceType: getInstanceType(define.type), - value: getInstanceCtor(define.type)(), - defines: define.defines - }; - }); - } - return { props, defines }; - }; -} - -export default Effect; -cc.Effect = Effect; diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts new file mode 100644 index 0000000000..4fc99c7b54 --- /dev/null +++ b/cocos/renderer/core/effect.ts @@ -0,0 +1,311 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import EffectAsset from '../../3d/assets/effect-asset'; +import { CCObject } from '../../core/data'; +import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; +import enums from '../enums'; +import Texture2D from '../gfx/texture-2d'; +import TextureCube from '../gfx/texture-cube'; +import { Pass } from './pass'; +import Technique from './technique'; + +const _typeMap = { + [enums.PARAM_INT]: 'Number', + [enums.PARAM_INT2]: Vec2, + [enums.PARAM_INT3]: Vec3, + [enums.PARAM_INT4]: Vec4, + [enums.PARAM_FLOAT]: 'Number', + [enums.PARAM_FLOAT2]: Vec2, + [enums.PARAM_FLOAT3]: Vec3, + [enums.PARAM_FLOAT4]: Vec4, + [enums.PARAM_COLOR3]: Color, + [enums.PARAM_COLOR4]: Color, + [enums.PARAM_MAT4]: Mat4, + [enums.PARAM_TEXTURE_2D]: Texture2D, + [enums.PARAM_TEXTURE_CUBE]: TextureCube, + number: 'Number', + boolean: 'Boolean', + default: CCObject, +}; +const getInstanceType = (t: number | string) => _typeMap[t] || _typeMap.default; +const typeCheck = (value: any, type: number) => { + const instanceType = getInstanceType(type); + switch (typeof value) { + case 'object': return (value === null) || (value instanceof instanceType); + case 'number': return instanceType === 'Number'; + default: return false; + } +}; + +let _globalTechLod = 600; + +const _ctorMap = { + ['Number']: (v?: number) => v || 0, + ['Boolean']: (v?: boolean) => v || false, + [Vec2]: (v?: number[]) => v ? new Vec2(v[0], v[1]) : new Vec2(), + [Vec3]: (v?: number[]) => v ? new Vec3(v[0], v[1], v[2]) : new Vec3(), + [Vec4]: (v?: number[]) => v ? new Vec4(v[0], v[1], v[2], v[3]) : new Vec4(), + [Color]: (v?: number[]) => v ? new Color(v[0] * 255, v[1] * 255, v[2] * 255, + (v[3] || 1) * 255) : new Color(), + [Mat4]: (v?: number[]) => v ? new Mat4( + v[0], v[1], v[2], v[3], + v[4], v[5], v[6], v[7], + v[8], v[9], v[10], v[11], + v[12], v[13], v[14], v[15] + ) : new Mat4(), + [Texture2D]: () => null, + [TextureCube]: () => null, + [CCObject]: () => null, +}; +const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; + +const getInvolvedPrograms = (effect: EffectAsset) => { + const programs: Programs = {}; + const lib = cc.game._renderer._programLib; + effect.techniques.forEach((tech) => { + tech.passes.forEach((pass) => { + programs[pass.program] = lib.getTemplate(pass.program); + }); + }); + return programs; +}; + +const parseProperties = (() => { + function genPropInfo(displayName: string, type: number, value: any) { + return { + type, + displayName, + instanceType: getInstanceType(type), + value: getInstanceCtor(type)(value), + }; + } + return (effect: EffectAsset, programs: Programs) => { + const props = {}; + // properties may be specified in the shader too + for (const p of Object.keys(programs)) { + programs[p].uniforms.forEach((prop) => { + if (!prop.property) { return; } + props[prop.name] = genPropInfo(prop.displayName, prop.type, prop.value); + }); + } + for (const prop of Object.keys(effect.properties)) { + const propInfo = effect.properties[prop]; + let uniformInfo; + // always try getting the type from shaders first + if (propInfo.tech !== undefined && propInfo.pass !== undefined) { + const pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program; + uniformInfo = programs[pname].uniforms.find((u) => u.name === prop); + } else { + for (const p of Object.keys(programs)) { + uniformInfo = programs[p].uniforms.find((u) => u.name === prop); + if (uniformInfo) { break; } + } + } + // the property is not defined in all the shaders used in techs + if (!uniformInfo) { + console.warn(`illegal property: ${prop}`); + continue; + } + // TODO: different param with same name for different passes + props[prop] = genPropInfo( + propInfo.displayName || uniformInfo.displayName, + propInfo.type || uniformInfo.type, + propInfo.value || uniformInfo.value); + } + return props; + }; +})(); + +const parseEffect = (effect: EffectAsset) => { + // techniques + const techNum = effect.techniques.length; + const programs = getInvolvedPrograms(effect); + const techniques = new Array(techNum); + let tech; + for (let j = 0; j < techNum; ++j) { + tech = effect.techniques[j]; + const passNum = tech.passes.length; + const passes = new Array(passNum); + for (let k = 0; k < passNum; ++k) { + const passInfo = tech.passes[k]; + passInfo.device = cc.game._renderContext; + passes[k] = Pass.create(passInfo); + } + techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); + } + // uniforms + const props = parseProperties(effect, programs); + const uniforms = {}; + for (const pn of Object.keys(programs)) { + programs[pn].uniforms.forEach((u) => { + const prop = props[u.name]; + uniforms[u.name] = { + type: prop ? prop.type : u.type, + value: prop ? prop.value : getInstanceCtor(u.type)(u.value), + }; + }); + } + + return new Effect(effect.name, techniques, programs, uniforms); +}; + +let parseForInspector = (effect: EffectAsset) => {}; + +if (CC_EDITOR) { + parseForInspector = (effect: EffectAsset) => { + const programs = getInvolvedPrograms(effect); + const props = parseProperties(effect, programs); + const defines = {}; + for (const pn of Object.keys(programs)) { + programs[pn].uniforms.forEach((u) => { + const prop = props[u.name]; + if (!prop) { return; } + prop.defines = u.defines; + }); + programs[pn].defines.forEach((define) => { + defines[define.name] = { + instanceType: getInstanceType(define.type), + value: getInstanceCtor(define.type)(), + defines: define.defines, + }; + }); + } + return { props, defines }; + }; +} + +interface PropertyMap { + [name: string]: { type: number, value: any }; +} +interface DefineMap { + [name: string]: number | boolean; +} +interface DependencyMap { + [define: string]: string; +} +interface ProgramInfo { + uniforms: Array< { name: string, type: string } >; + defines: Array< { name: string, type: string } >; + extensions: Array< { name: string, define: string } >; +} +interface Programs { + [name: string]: ProgramInfo; +} + +class Effect { + public static parseEffect = parseEffect; + public static parseForInspector = parseForInspector; + public static setGlobalLod(lod: number) { _globalTechLod = lod; } + + protected _name: string = ''; + protected _techniques: Technique[] = []; + protected _properties: PropertyMap = {}; + protected _programs: Programs = {}; + protected _defines: DefineMap = {}; + protected _dependencies: DependencyMap = {}; + protected _maxLOD: number = 0; + protected _activeTechIdx: number = 0; + + constructor(name: string, techniques: Technique[], programs: Programs, properties: PropertyMap = {}, lod = -1) { + this._name = name; + this._techniques = techniques; + this._properties = properties; + this._programs = programs; + this._defines = {}; + this._dependencies = {}; + this._maxLOD = lod; + this.selectTechnique(); + } + + set LOD(lod: number) { + if (lod === this._maxLOD) { + return; + } + this._maxLOD = lod; + this.selectTechnique(); + } + + public clear() { + this._techniques.length = 0; + this._properties = {}; + this._defines = {}; + this._dependencies = {}; + } + + public getTechnique(index: number) { + if (index < 0 || index >= this._techniques.length) { return null; } + return this._techniques[index]; + } + + public getProperty(name: string) { + if (!this._properties[name]) { + console.warn(`Failed to get property ${name}, property not found.`); + return null; + } + return this._properties[name].value; + } + + public setProperty(name: string, value: any) { + const prop = this._properties[name]; + if (!prop) { + console.warn(`Failed to set property ${name}, property not found.`); + return; + } else if (!typeCheck(value, prop.type)) { + console.warn(`Failed to set property ${name}, property type mismatch.`); + return; + } + this._properties[name].value = value; + } + + public getDefine(name: string) { + const def = this._defines[name]; + if (def !== undefined) { return def; } + console.warn(`Failed to get define ${name}, define not found.`); + return null; + } + + public define(name: string, value: number | boolean) { + if (this._defines[name] !== undefined) { + this._defines[name] = value; + } else { + console.warn(`Failed to set define ${name}, define not found.`); + } + } + + public extractDefines(out = {}) { + return Object.assign(out, this._defines); + } + + public extractDependencies(out = {}) { + return Object.assign(out, this._dependencies); + } + + public getActiveTechnique() { + return this._techniques[this._activeTechIdx]; + } + + public selectTechnique() { + const lod = this._maxLOD === -1 ? _globalTechLod : this._maxLOD; + this._activeTechIdx = 0; + for (let i = 0; i < this._techniques.length; i++) { + if (this._techniques[i]._lod <= lod) { + this._activeTechIdx = i; + break; + } + } + + // defines + this._defines = {}; + this._techniques[this._activeTechIdx].passes.forEach((pass) => + this._programs[pass._programName].defines.forEach((def) => + this._defines[def.name] = getInstanceCtor(def.type)())); + + // extensions + this._dependencies = {}; + this._techniques[this._activeTechIdx].passes.forEach((pass) => this._programs[pass._programName].extensions + .filter((ext) => ext.define).forEach((ext) => this._dependencies[ext.define] = ext.name)); + } +} + +export default Effect; +cc.Effect = Effect; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 93b21bb1e7..dd7d8619aa 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,46 +1,58 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { PassStage } from './constants'; -import { GFXBuffer } from '../../gfx/buffer'; -import { GFXSampler } from '../../gfx/sampler'; -import { GFXDevice } from '../../gfx/device'; -import { GFXDepthStencilAttachment, GFXColorAttachment } from '../../gfx/render-pass'; -import { GFXPipelineState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState, GFXInputState } from '../../gfx/pipeline-state'; import { GFXBindingLayoutInfo } from '../../gfx/binding-layout'; -import { GFXPrimitiveMode } from '../../gfx/gfx-define'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXPrimitiveMode } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, GFXInputState, + GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; +import { GFXColorAttachment, GFXDepthStencilAttachment } from '../../gfx/render-pass'; +import { GFXSampler } from '../../gfx/sampler'; +import { PassStage } from './constants'; -interface PassInfo { - programName?: string; +export interface PassInfo { + device: GFXDevice; + program: string; primitive?: GFXPrimitiveMode; stage?: PassStage; inputState?: GFXInputState; rasterizerState?: GFXRasterizerState; depthStencilState?: GFXDepthStencilState; blendState?: GFXBlendState; + blendTarget?: GFXBlendTarget; bindingLayoutInfo?: GFXBindingLayoutInfo; + colorAttachment?: GFXColorAttachment; + depthStencilAttachment?: GFXDepthStencilAttachment; } -export default class Pass { - static create(info: PassInfo) { - let pass = new Pass(); - let device = pass._device = cc.game._renderContext; - pass._programName = info.programName || ''; +export class Pass { + public static create(info: PassInfo) { + const pass = new Pass(); + const device = pass._device = info.device; + pass._programName = info.program; pass._stage = info.stage || PassStage.DEFAULT; + // pipeline state + const shader = device.createShader({ name: info.program, stages: [] }); + if (!shader) { console.error('create shader failed'); return; } + const bindingLayout = device.createBindingLayout(info.bindingLayoutInfo || { bindings: [] }); + if (!bindingLayout) { console.error('create binding layout failed'); return; } + const layout = device.createPipelineLayout({ layouts: [bindingLayout] }); + if (!layout) { console.error('create pipeline layout failed'); return; } + const renderPass = device.createRenderPass({ + colorAttachments: [Object.assign(new GFXColorAttachment(), info.colorAttachment)], + depthStencilAttachment: Object.assign(new GFXDepthStencilAttachment(), info.depthStencilAttachment), + }); + if (!renderPass) { console.error('create render pass failed'); return; } + const bs = Object.assign(new GFXBlendState(), info.blendState); + Object.assign(bs.targets[0], info.blendTarget); + pass._pipelineState = device.createPipelineState({ primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, - shader: null, - is: Object.assign(new GFXInputState, info.inputState), - rs: Object.assign(new GFXRasterizerState, info.rasterizerState), - dss: Object.assign(new GFXDepthStencilState, info.depthStencilState), - bs: Object.assign(new GFXBlendState, info.blendState), - layout: device.createPipelineLayout({ - layouts: [device.createBindingLayout(info.bindingLayoutInfo || { bindings: [] })] - }), - renderPass: device.createRenderPass({ - colorAttachments: [new GFXColorAttachment], - depthStencilAttachment: new GFXDepthStencilAttachment - }) + is: Object.assign(new GFXInputState(), info.inputState), + rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), + dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState), + bs, shader, layout, renderPass, }); } diff --git a/cocos/renderer/core/technique.js b/cocos/renderer/core/technique.ts similarity index 61% rename from cocos/renderer/core/technique.js rename to cocos/renderer/core/technique.ts index 6ec993f2ab..1b0a2baf81 100644 --- a/cocos/renderer/core/technique.js +++ b/cocos/renderer/core/technique.ts @@ -1,24 +1,25 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { RenderQueue } from "./constants"; +import { RenderQueue } from './constants'; +import { Pass } from './pass'; let _genID = 0; export default class Technique { - /** - * @param {Array} stages - * @param {Array} passes - * @param {Number} renderQueue - */ + protected _id: number = -1; + protected _renderQueue: number = RenderQueue.OPAQUE; + protected _priority: number = 0; + protected _lod: number = -1; + protected _passes: Pass[] = []; + constructor(renderQueue = RenderQueue.OPAQUE, priority = 0, lod = -1, passes = []) { this._id = _genID++; this._renderQueue = renderQueue; this._priority = priority; this._lod = lod; this._passes = passes; - // TODO: this._version = 'webgl' or 'webgl2' // ???? } - setRenderQueue(renderQueue) { + public setRenderQueue(renderQueue: number) { this._renderQueue = renderQueue; } diff --git a/cocos/renderer/index.js b/cocos/renderer/index.js index 0512679989..593e989d8e 100644 --- a/cocos/renderer/index.js +++ b/cocos/renderer/index.js @@ -3,7 +3,7 @@ import { createIA } from './utils'; import config from './config'; import { RenderQueue, PassStage } from './core/constants'; -import Pass from './core/pass'; +import { Pass } from './core/pass'; import Technique from './core/technique'; import Effect from './core/effect'; import InputAssembler from './core/input-assembler'; diff --git a/docs/apisrc.json b/docs/apisrc.json index 2c235ed36c..a0e00ced60 100644 --- a/docs/apisrc.json +++ b/docs/apisrc.json @@ -17,12 +17,12 @@ "./cocos2d/audio/**/*", "./cocos2d/core/CCDebug.js", - "./cocos2d/core/CCDirector.js", + "./cocos2d/core/director.js", "./cocos2d/core/CCNode.js", "./cocos2d/core/CCPrivateNode.js", "./cocos2d/core/CCScene.js", - "./cocos2d/core/CCGame.js", - "./cocos2d/core/CCScheduler.js", + "./cocos2d/core/game.js", + "./cocos2d/core/scheduler.js", "./cocos2d/core/assets/**/*", @@ -42,7 +42,7 @@ "!./cocos2d/core/load-pipeline/asset-table.js", "./cocos2d/core/physics/**/*", - + "./cocos2d/core/platform/**/*", "!./cocos2d/core/platform/BKInputManager.js", "!./cocos2d/core/platform/CCAssetLibrary.js", @@ -79,4 +79,4 @@ "./extensions/ccpool/*.js", "./extensions/spine/*.js", "./extensions/dragonbones/*.js" -] \ No newline at end of file +] diff --git a/tsconfig.json b/tsconfig.json index fa152bcee8..19b0f7c62d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,62 +1,63 @@ { - "compilerOptions": { - /* Basic Options */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - // "lib": [], /* Specify library files to be included in the compilation. */ - "allowJs": false, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./dist", /* Redirect output structure to the directory. */ - "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + "compilerOptions": { + /* Basic Options */ + "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "lib": ["es2015", "es2017", "dom"], + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + "allowJs": false, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./dist", /* Redirect output structure to the directory. */ + "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + /* Experimental Options */ + "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + } + //"include" : ["./source"] + //"exclude" : ["js"] } - //"include" : ["./source"] - //"exclude" : ["js"] -} \ No newline at end of file From 962ae81ab78d13075f29422bf2d8daccf2fc1d94 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 18:46:33 +0800 Subject: [PATCH 023/267] fix gl error --- cocos/core/root.ts | 6 +++--- cocos/gfx/gfx-define.ts | 20 ++++++++++---------- cocos/gfx/webgl/webgl-device.ts | 15 +++++++++++---- cocos/renderer/scene/render-scene.ts | 4 ++++ 4 files changed, 28 insertions(+), 17 deletions(-) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 9649d82e3f..2882840121 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,6 +1,6 @@ import { GFXWindow, GFXWindowInfo } from "../gfx/window"; import { GFXDevice } from "../gfx/device"; -import { RenderView, RenderViewInfo, RenderViewPriority } from "../pipeline/render-view"; +import { RenderView, RenderViewInfo } from "../pipeline/render-view"; import { RenderPipeline } from "../pipeline/render-pipeline"; import { ForwardPipeline } from "../pipeline/forward/forward-pipeline"; import { RenderScene, RenderSceneInfo } from "../renderer/scene/render-scene"; @@ -50,7 +50,7 @@ export class Root { for (let i = 0; i < this._views.length; ++i) { let view = this._views[i]; - if(view.isEnable() && view.isAttached) { + if (view.isEnable() && view.isAttached) { (this._pipeline).render(view); } } @@ -89,7 +89,7 @@ export class Root { public createScene(info: RenderSceneInfo): RenderScene | null { let scene = new RenderScene; - if(scene.initialize(info)) { + if (scene.initialize(info)) { this._scenes.push(scene); return scene; } else { diff --git a/cocos/gfx/gfx-define.ts b/cocos/gfx/gfx-define.ts index 61c41f70c6..d5848a3e2d 100644 --- a/cocos/gfx/gfx-define.ts +++ b/cocos/gfx/gfx-define.ts @@ -697,25 +697,25 @@ export function GFXGetTypeSize(type: GFXType): number { export function GFXGetAttributeBinding(name: string) : number { if (name === GFX_ATTRIBUTE_POSITION) { - return 20; + return 6; } else if (name === GFX_ATTRIBUTE_COLOR) { - return 21; + return 7; } else if (name === GFX_ATTRIBUTE_COLOR1) { - return 22; + return 8; } else if (name === GFX_ATTRIBUTE_NORMAL) { - return 23; + return 9; } else if (name === GFX_ATTRIBUTE_TANGENT) { - return 24; + return 10; } else if (name === GFX_ATTRIBUTE_BINORMAL) { - return 25; + return 11; } else if (name === GFX_ATTRIBUTE_TEXCOORD) { - return 26; + return 12; } else if (name === GFX_ATTRIBUTE_TEXCOORD1) { - return 27; + return 13; } else if (name === GFX_ATTRIBUTE_JOINTS) { - return 28; + return 14; } else if (name === GFX_ATTRIBUTE_WEIGHTS) { - return 29; + return 15; } else { return -1; } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 9b58cd1393..dbca7d8dd8 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -31,7 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit } from '../gfx-define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType } from '../gfx-define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -145,6 +145,8 @@ export class WebGLGFXDevice extends GFXDevice { this._OES_element_index_uint = this._webGLRC.getExtension("OES_element_index_uint"); this._ANGLE_instanced_arrays = this._webGLRC.getExtension("ANGLE_instanced_arrays"); + this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); + // create primary window this._mainWindow = this.createWindow({ title: this._webGLRC.canvas.title, @@ -171,6 +173,11 @@ export class WebGLGFXDevice extends GFXDevice { this._cmdAllocator = null; } + if (this._queue) { + this._queue.destroy(); + this._queue = null; + } + this._webGLRC = null; } @@ -476,8 +483,8 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { let gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, - colorAttachments: info.colorAttachment? info.colorAttachment : [], - depthStencilAttachment: info.depthStencilAttachment? info.depthStencilAttachment : null, + colorAttachments: info.colorAttachment ? info.colorAttachment : [], + depthStencilAttachment: info.depthStencilAttachment ? info.depthStencilAttachment : null, } return gpuRenderPass; @@ -585,7 +592,7 @@ export class WebGLGFXDevice extends GFXDevice { gpuStages[i] = { type: stage.type, source: stage.source, - macros: stage.macros? stage.macros : [], + macros: stage.macros ? stage.macros : [], glShader: 0, }; } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 28d018c9a1..5f27e1de57 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -151,6 +151,10 @@ export class RenderScene { return this._cameras; } + public get mainCamera(): Camera | null { + return this._mainCamera; + } + public get lights(): Light[] { return this._lights; } From 9123cb36b16d3eb090235c8ff4f4876954bbd477 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 2 Jan 2019 20:56:40 +0800 Subject: [PATCH 024/267] fix gfx crashes --- cocos/gfx/define.ts | 18 +-- cocos/gfx/webgl/webgl-buffer.ts | 6 +- cocos/gfx/webgl/webgl-command-allocator.ts | 20 ++-- cocos/gfx/webgl/webgl-commands.ts | 128 ++++++++++++++------- cocos/gfx/webgl/webgl-device.ts | 11 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 3 +- cocos/gfx/webgl/webgl-input-assembler.ts | 11 +- cocos/gfx/webgl/webgl-texture-view.ts | 25 ++-- cocos/gfx/webgl/webgl-window.ts | 78 ++++++++----- 9 files changed, 187 insertions(+), 113 deletions(-) diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index cd7386c753..68de6cba03 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -18,7 +18,7 @@ export enum WebGLEXT { COMPRESSED_RGB_ETC1_WEBGL = 0x8D64, } -export const GFX_MAX_VERTEX_ATTRIBUTES: number = 8; +export const GFX_MAX_VERTEX_ATTRIBUTES: number = 16; export const GFX_MAX_TEXTURE_UNITS: number = 16; export const GFX_MAX_ATTACHMENTS: number = 4; @@ -695,7 +695,6 @@ export function GFXGetTypeSize(type: GFXType): number { } } -<<<<<<< HEAD:cocos/gfx/gfx-define.ts export function GFXGetAttributeBinding(name: string) : number { if (name === GFX_ATTRIBUTE_POSITION) { return 6; @@ -721,18 +720,3 @@ export function GFXGetAttributeBinding(name: string) : number { return -1; } } -======= -const GFXBuiltinAttributeBindings = { - [GFX_ATTRIBUTE_POSITION]: 20, - [GFX_ATTRIBUTE_COLOR]: 21, - [GFX_ATTRIBUTE_COLOR1]: 22, - [GFX_ATTRIBUTE_NORMAL]: 23, - [GFX_ATTRIBUTE_TANGENT]: 24, - [GFX_ATTRIBUTE_BINORMAL]: 25, - [GFX_ATTRIBUTE_TEXCOORD]: 26, - [GFX_ATTRIBUTE_TEXCOORD1]: 27, - [GFX_ATTRIBUTE_JOINTS]: 28, - [GFX_ATTRIBUTE_WEIGHTS]: 29, -}; -export { GFXBuiltinAttributeBindings }; ->>>>>>> f39457540e35b3cb5fe6bbf7586a0df2d602a94c:cocos/gfx/define.ts diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 86dff88ccf..c79dcf7ebd 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -15,7 +15,11 @@ export class WebGLGFXBuffer extends GFXBuffer { this._usage = info.usage; this._memUsage = info.memUsage; this._size = info.size; - this._stride = info.stride? info.stride : 1; + + if(info.stride) { + this._stride = info.stride; + } + this._stride = Math.max(this._stride, 1); if (this._memUsage & GFXMemoryUsageBit.HOST) { this._buffer = new ArrayBuffer(this._size); diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 8d54f06868..2a7b30d167 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -4,8 +4,12 @@ import { WebGLCmdUpdateBuffer, WebGLCmdBeginRenderPass, WebGLCmdBindInputAssembl export class WebGLGFXCommandPool { - constructor(count: number, increase : number) { + constructor(clazz: new() => T, count: number, increase : number) { this._frees = new Array(count); + for(let i = 0; i < count; ++i) { + this._frees[i] = new clazz(); + } + this._freeIdx = count - 1; this._increase = increase; } @@ -55,13 +59,13 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { constructor(device : GFXDevice) { super(device); - this.beginRenderPassCmdPool = new WebGLGFXCommandPool(64, 32); - this.bindPipelineStateCmdPool = new WebGLGFXCommandPool(64, 32); - this.bindBindingLayoutCmdPool = new WebGLGFXCommandPool(64, 32); - this.bindInputAssemblerCmdPool = new WebGLGFXCommandPool(64, 32); - this.drawCmdPool = new WebGLGFXCommandPool(64, 32); - this.updateBufferCmdPool = new WebGLGFXCommandPool(64, 32); - this.copyBufferToTextureCmdPool = new WebGLGFXCommandPool(64, 32); + this.beginRenderPassCmdPool = new WebGLGFXCommandPool(WebGLCmdBeginRenderPass, 64, 32); + this.bindPipelineStateCmdPool = new WebGLGFXCommandPool(WebGLCmdBindPipelineState, 64, 32); + this.bindBindingLayoutCmdPool = new WebGLGFXCommandPool(WebGLCmdBindBindingLayout, 64, 32); + this.bindInputAssemblerCmdPool = new WebGLGFXCommandPool(WebGLCmdBindInputAssembler, 64, 32); + this.drawCmdPool = new WebGLGFXCommandPool(WebGLCmdDraw, 64, 32); + this.updateBufferCmdPool = new WebGLGFXCommandPool(WebGLCmdUpdateBuffer, 64, 32); + this.copyBufferToTextureCmdPool = new WebGLGFXCommandPool(WebGLCmdCopyBufferToTexture, 64, 32); } public initialize(info: GFXCommandAllocatorInfo) : boolean { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 46b4ec0946..897437d9bd 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,6 +1,6 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXBuiltinAttributeBindings } from "../define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXGetAttributeBinding } from "../define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; @@ -719,6 +719,29 @@ export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebu gpuFramebuffer.gpuDepthStencilView.gpuTexture.glTexture, gpuFramebuffer.gpuDepthStencilView.baseLevel); } + + let status = gl.checkFramebufferStatus(WebGLRenderingContext.FRAMEBUFFER); + if (status !== WebGLRenderingContext.FRAMEBUFFER_COMPLETE) { + switch (status) { + case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { + console.error("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + break; + } + case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { + console.error("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + break; + } + case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { + console.error("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); + break; + } + case WebGLRenderingContext.FRAMEBUFFER_UNSUPPORTED: { + console.error("glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); + break; + } + default: ; + } + } } } } @@ -818,9 +841,8 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG varName = info.name; } - let glLoc = GFXBuiltinAttributeBindings[varName]; - - if(glLoc >= 0) { + let glLoc = GFXGetAttributeBinding(varName); + if (glLoc >= 0) { gl.bindAttribLocation(gpuShader.glProgram, glLoc, varName); }/* else { //glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); @@ -1010,9 +1032,17 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput let glType = GFXFormatToWebGLType(attrib.format, device); let size = WebGLGetTypeSize(glType); + let glLoc = -1; + if (attrib.binding) { + glLoc = attrib.binding; + } else { + glLoc = GFXGetAttributeBinding(attrib.name); + } + gpuInputAssembler.glAttribs[i] = { + name: attrib.name, glBuffer: gpuBuffer.glBuffer, - glLoc: attrib.binding? attrib.binding : -1, + glLoc: glLoc, glType: glType, size: size, count: GFXFormatInfos[attrib.format].count, @@ -1817,55 +1847,65 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLCmd.DRAW: { - if (gpuInputAssembler) { + if (gpuInputAssembler && gpuShader) { let cmd = cmdPackage.drawCmds[drawCmdIdx++]; for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { device.stateCache.glCurrentAttribLocs[a] = false; } - for (let a = 0; a < gpuInputAssembler.glAttribs.length; ++a) { - let glAttrib = gpuInputAssembler.glAttribs[a]; + for (let n = 0; n < gpuShader.glInputs.length; ++n) { + let glInput = gpuShader.glInputs[n]; + let glAttrib: WebGLAttrib | null = null; - if (device.stateCache.glArrayBuffer !== glAttrib.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, glAttrib.glBuffer); - device.stateCache.glArrayBuffer = glAttrib.glBuffer; - } - - for (let c = 0; c < glAttrib.componentCount; ++c) { - let glLoc = glAttrib.glLoc + c; - let offset = glAttrib.offset + glAttrib.size * c; - - if (!device.stateCache.glEnabledAttribLocs[a]) { - gl.enableVertexAttribArray(glLoc); - device.stateCache.glEnabledAttribLocs[a] = true; + for (let a = 0; a < gpuInputAssembler.glAttribs.length; ++a) { + if (gpuInputAssembler.glAttribs[a].name === glInput.name) { + glAttrib = gpuInputAssembler.glAttribs[a]; + break; } - device.stateCache.glCurrentAttribLocs[a] = true; - - gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, offset); - } - } - - for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { - if (device.stateCache.glEnabledAttribLocs[a] != device.stateCache.glCurrentAttribLocs[a]) { - gl.disableVertexAttribArray(a); - device.stateCache.glEnabledAttribLocs[a] = false; - } - } - - if (gpuInputAssembler.gpuIndexBuffer && cmd.indexCount > 0) { - let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; - - if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - let offset = cmd.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, cmd.indexCount, gpuInputAssembler.glIndexType, offset); - } else { - gl.drawArrays(glPrimitive, cmd.firstVertex, cmd.vertexCount); - } + if (glAttrib) { + if (device.stateCache.glArrayBuffer !== glAttrib.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, glAttrib.glBuffer); + device.stateCache.glArrayBuffer = glAttrib.glBuffer; + } + + for (let c = 0; c < glAttrib.componentCount; ++c) { + let glLoc = glAttrib.glLoc + c; + let offset = glAttrib.offset + glAttrib.size * c; + + if (!device.stateCache.glEnabledAttribLocs[glLoc] && glLoc >= 0) { + gl.enableVertexAttribArray(glLoc); + device.stateCache.glEnabledAttribLocs[glLoc] = true; + } + device.stateCache.glCurrentAttribLocs[glLoc] = true; + + gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, offset); + } + } + + if (gpuInputAssembler.gpuIndexBuffer && cmd.indexCount > 0) { + let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + let offset = cmd.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, cmd.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, cmd.firstVertex, cmd.vertexCount); + } + + for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { + if (device.stateCache.glEnabledAttribLocs[a] != device.stateCache.glCurrentAttribLocs[a]) { + gl.disableVertexAttribArray(a); + device.stateCache.glEnabledAttribLocs[a] = false; + } + } + } // if } break; } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index aeeedf932b..3f4516adc2 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -480,6 +480,9 @@ export class WebGLGFXDevice extends GFXDevice { return gpuTextureView; } + public emitCmdDestroyGPUTextureView(gpuTextureView: WebGLGPUTextureView) { + } + public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { let gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, @@ -490,19 +493,21 @@ export class WebGLGFXDevice extends GFXDevice { return gpuRenderPass; } - public emitCmdDestroyGPURenderPass(renderPass: WebGLGPURenderPass) { + public emitCmdDestroyGPURenderPass(gpuRenderPass: WebGLGPURenderPass) { } public emitCmdCreateGPUFramebuffer(info: GFXFramebufferInfo): WebGLGPUFramebuffer { let renderPass = info.renderPass; - let gpuColorViews: (WebGLGPUTextureView | null)[] = new Array(); + let gpuColorViews: WebGLGPUTextureView[] = []; if (info.colorViews) { for (let i = 0; i < info.colorViews.length; ++i) { let webGLColorView = info.colorViews[i]; - gpuColorViews[i] = webGLColorView.gpuTextureView; + if(webGLColorView.gpuTextureView) { + gpuColorViews.push(webGLColorView.gpuTextureView); + } } } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 8a3877d582..1133d9bfd2 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -94,7 +94,7 @@ export class WebGLGPURenderPass extends WebGLGPUObject { export class WebGLGPUFramebuffer extends WebGLGPUObject { gpuRenderPass: WebGLGPURenderPass; - gpuColorViews: (WebGLGPUTextureView | null)[] = []; + gpuColorViews: WebGLGPUTextureView[] = []; gpuDepthStencilView: WebGLGPUTextureView | null = null; isOffscreen?: boolean = false; @@ -228,6 +228,7 @@ export class WebGLGPUBindingLayout extends WebGLGPUObject { }; export class WebGLAttrib { + name: string = ""; glBuffer: WebGLBuffer = 0; glLoc: number = 0; glType: GLenum = 0; diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index bda7373d77..9c9061185e 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -10,12 +10,21 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { } public initialize(info: GFXInputAssemblerInfo): boolean { + + if(info.vertexBuffers.length === 0) { + console.error("GFXInputAssemblerInfo.vertexBuffers is null."); + return false; + } this._attributes = info.attributes; this._vertexBuffers = info.vertexBuffers; - + if (info.indexBuffer) { this._indexBuffer = info.indexBuffer; + this._indexCount = this._indexBuffer.size / this._indexBuffer.stride; + } else { + let vertBuff = this._vertexBuffers[0]; + this._vertexCount = vertBuff.size / vertBuff.stride; } if (info.isIndirect) { diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts index 51debcfc44..c98fc4d510 100644 --- a/cocos/gfx/webgl/webgl-texture-view.ts +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -5,50 +5,53 @@ import { WebGLGFXDevice } from './webgl-device'; export class WebGLGFXTextureView extends GFXTextureView { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXTextureViewInfo) : boolean { + public initialize(info: GFXTextureViewInfo): boolean { this._texture = info.texture; this._type = info.type; this._format = info.format; this._format = info.format; - if(info.baseLevel) { + if (info.baseLevel) { this._baseLevel = info.baseLevel; } - if(info.levelCount) { + if (info.levelCount) { this._levelCount = info.levelCount; } - if(info.baseLayer) { + if (info.baseLayer) { this._baseLayer = info.baseLayer; } - if(info.layerCount) { + if (info.layerCount) { this._layerCount = info.layerCount; } - this.webGLDevice.emitCmdCreateGPUTextureView(info); + this._gpuTextureView = this.webGLDevice.emitCmdCreateGPUTextureView(info); return true; } public destroy() { - this._gpuTextureView = null; + if (this._gpuTextureView) { + this.webGLDevice.emitCmdDestroyGPUTextureView(this._gpuTextureView); + this._gpuTextureView = null; + } this._texture = null; } - public get webGLDevice() : WebGLGFXDevice { + public get webGLDevice(): WebGLGFXDevice { return this._device; } - public get gpuTextureView() : WebGLGPUTextureView | null { + public get gpuTextureView(): WebGLGPUTextureView | null { return this._gpuTextureView; } - private _gpuTextureView : WebGLGPUTextureView | null = null; + private _gpuTextureView: WebGLGPUTextureView | null = null; }; diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index f07a612024..47b1caf56e 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -54,6 +54,11 @@ export class WebGLGFXWindow extends GFXWindow { }, }); + if(!this._renderPass) { + this.destroy(); + return false; + } + this._colorTex = this._device.createTexture({ type : GFXTextureType.TEX2D, usage : GFXTextureUsageBit.COLOR_ATTACHMENT, @@ -66,16 +71,24 @@ export class WebGLGFXWindow extends GFXWindow { flags : GFXTextureFlagBit.NONE, }); - if(this._colorTex) { - this._colorTexView = this._device.createTextureView({ - texture : this._colorTex, - type : GFXTextureViewType.TV2D, - format : this._colorFmt, - baseLevel : 0, - levelCount : 1, - baseLayer : 0, - layerCount : 1, - }); + if(!this._colorTex) { + this.destroy(); + return false; + } + + this._colorTexView = this._device.createTextureView({ + texture : this._colorTex, + type : GFXTextureViewType.TV2D, + format : this._colorFmt, + baseLevel : 0, + levelCount : 1, + baseLayer : 0, + layerCount : 1, + }); + + if(!this._colorTexView) { + this.destroy(); + return false; } this._depthStencilTex = this._device.createTexture({ @@ -90,25 +103,36 @@ export class WebGLGFXWindow extends GFXWindow { flags : GFXTextureFlagBit.NONE, }); - if(this._depthStencilTex) { - this._depthStencilTexView = this._device.createTextureView({ - texture : this._depthStencilTex, - type : GFXTextureViewType.TV2D, - format : this._depthStencilFmt, - baseLevel : 0, - levelCount : 1, - baseLayer : 0, - layerCount : 1, - }); + if(!this._depthStencilTex) { + this.destroy(); + return false; } - if(this._colorTexView && this._renderPass && this._depthStencilTexView) { - this._framebuffer = this._device.createFramebuffer({ - renderPass: this._renderPass, - colorViews: [this._colorTexView], - depthStencilView: this._depthStencilTexView, - isOffscreen: false, - }); + this._depthStencilTexView = this._device.createTextureView({ + texture : this._depthStencilTex, + type : GFXTextureViewType.TV2D, + format : this._depthStencilFmt, + baseLevel : 0, + levelCount : 1, + baseLayer : 0, + layerCount : 1, + }); + + if(!this._depthStencilTexView) { + this.destroy(); + return false; + } + + this._framebuffer = this._device.createFramebuffer({ + renderPass: this._renderPass, + colorViews: [this._colorTexView], + depthStencilView: this._depthStencilTexView, + isOffscreen: false, + }); + + if(!this._framebuffer) { + this.destroy(); + return false; } return true; From 4e92e1e28d236d9e69615c8ac6db756aabe2a51e Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 3 Jan 2019 13:25:16 +0800 Subject: [PATCH 025/267] fix gfx bugs, pipeline is ready to work --- cocos/gfx/device.ts | 41 +++++++ cocos/gfx/shader.ts | 6 +- cocos/gfx/webgl/webgl-buffer.ts | 2 +- cocos/gfx/webgl/webgl-commands.ts | 84 +++++++++------ cocos/gfx/webgl/webgl-device.ts | 129 ++++++++++++++++------- cocos/gfx/webgl/webgl-framebuffer.ts | 6 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 1 - cocos/gfx/webgl/webgl-input-assembler.ts | 4 +- cocos/gfx/webgl/webgl-pipeline-layout.ts | 5 +- cocos/gfx/webgl/webgl-render-pass.ts | 4 +- cocos/gfx/webgl/webgl-sampler.ts | 26 ++--- cocos/gfx/webgl/webgl-shader.ts | 10 +- cocos/gfx/webgl/webgl-state-cache.ts | 2 +- cocos/gfx/webgl/webgl-texture-view.ts | 8 +- cocos/gfx/webgl/webgl-texture.ts | 33 ++++-- cocos/gfx/webgl/webgl-window.ts | 21 ++-- cocos/gfx/window.ts | 10 +- cocos/pipeline/forward/forward-flow.ts | 2 +- cocos/pipeline/forward/forward-stage.ts | 2 +- cocos/pipeline/forward/test-stage.ts | 20 ++-- cocos/pipeline/render-stage.ts | 22 ++-- cocos/renderer/scene/render-scene.ts | 2 +- playground/simple.html | 26 ++++- 23 files changed, 309 insertions(+), 157 deletions(-) diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 05ddb6e098..d6541c632b 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -56,13 +56,54 @@ export abstract class GFXDevice { return this._cmdAllocator; } + public get renderer(): string { + return this._renderer; + } + + public get vendor(): string { + return this._vendor; + } + public get maxVertexAttributes(): number { return this._maxVertexAttributes; } + public get maxVertexUniformVectors(): number { + return this._maxVertexUniformVectors; + } + + public get maxFragmentUniformVectors(): number { + return this._maxFragmentUniformVectors; + } + + public get maxTextureUnits(): number { + return this._maxTextureUnits; + } + + public get maxVertexTextureUnits(): number { + return this._maxVertexTextureUnits; + } + + public get depthBits(): number { + return this._depthBits; + } + + public get stencilBits(): number { + return this._stencilBits; + } + protected _deviceName : string = ""; + protected _renderer : string = ""; + protected _vendor : string = ""; + protected _version : string = ""; protected _queue : GFXQueue | null = null; protected _mainWindow : GFXWindow | null = null; protected _cmdAllocator: GFXCommandAllocator | null = null; protected _maxVertexAttributes : number = 0; + protected _maxVertexUniformVectors : number = 0; + protected _maxFragmentUniformVectors : number = 0; + protected _maxTextureUnits : number = 0; + protected _maxVertexTextureUnits : number = 0; + protected _depthBits : number = 0; + protected _stencilBits : number = 0; }; diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index d21ac8aaf5..356c8f0dba 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -1,5 +1,6 @@ import { GFXDevice } from './device'; import { GFXType, GFXShaderType } from './define'; +import { GFXInputAttribute } from './input-assembler'; export interface GFXShaderMacro { macro: string; @@ -37,7 +38,6 @@ export interface GFXShaderInfo { stages: GFXShaderStage[]; //bindings: GFXBinding[]; - // blocks are used for being compatible with single uniforms blocks?: GFXUniformBlock[]; samplers?: GFXUniformSampler[]; }; @@ -55,6 +55,6 @@ export abstract class GFXShader { protected _name: string = ""; protected _stages: GFXShaderStage[] = []; //protected _bindings: GFXBinding[] = []; - protected _blocks?: GFXUniformBlock[]; - protected _samplers?: GFXUniformSampler[]; + protected _blocks: GFXUniformBlock[] = []; // blocks are used for being compatible with single uniforms + protected _samplers: GFXUniformSampler[] = []; }; diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index c79dcf7ebd..f9e5cf21a8 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -16,7 +16,7 @@ export class WebGLGFXBuffer extends GFXBuffer { this._memUsage = info.memUsage; this._size = info.size; - if(info.stride) { + if(info.stride !== undefined) { this._stride = info.stride; } this._stride = Math.max(this._stride, 1); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 897437d9bd..3402c4c3eb 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -826,6 +826,26 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } } + // bind attributes + /* + if(gpuShader.attributes !== undefined) { + for(let a = 0; a < gpuShader.attributes.length; ++a) { + let attrib = gpuShader.attributes[a]; + let glLoc = -1; + + if(attrib.binding !== undefined && attrib.binding >= 0) { + glLoc = attrib.binding; + } else { + glLoc = GFXGetAttributeBinding(attrib.name); + } + + if(glLoc >= 0) { + gl.bindAttribLocation(gpuShader.glProgram, glLoc, attrib.name); + } + } + } + */ + // parse inputs let activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); @@ -841,13 +861,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG varName = info.name; } - let glLoc = GFXGetAttributeBinding(varName); - if (glLoc >= 0) { - gl.bindAttribLocation(gpuShader.glProgram, glLoc, varName); - }/* else { - //glLoc = gl.getAttribLocation(gpuShader.glProgram, info.name); - }*/ - + let glLoc = gl.getAttribLocation(gpuShader.glProgram, varName); let type = WebGLTypeToGFXType(info.type); let stride = WebGLGetTypeSize(info.type); @@ -1024,7 +1038,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput for (let i = 0; i < gpuInputAssembler.attributes.length; ++i) { let attrib = gpuInputAssembler.attributes[i]; - let stream = attrib.stream ? attrib.stream : 0; + let stream = attrib.stream !== undefined ? attrib.stream : 0; //if (stream < gpuInputAssembler.gpuVertexBuffers.length) { let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; @@ -1042,13 +1056,12 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput gpuInputAssembler.glAttribs[i] = { name: attrib.name, glBuffer: gpuBuffer.glBuffer, - glLoc: glLoc, glType: glType, size: size, count: GFXFormatInfos[attrib.format].count, stride: gpuBuffer.stride, componentCount: WebGLGetComponentCount(glType), - isInstanced: attrib.isInstanced ? attrib.isInstanced : false, + isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false, offset: offsets[stream], }; @@ -1073,7 +1086,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput for (let j = 0; j < gpuInputAssembler.attributes.length; ++j) { let attrib = gpuInputAssembler.attributes[j]; - let stream = attrib.stream ? attrib.stream : 0; + let stream = attrib.stream !== undefined ? attrib.stream : 0; if (glInput.name === attrib.name && stream < gpuInputAssembler.gpuVertexBuffers.length) { @@ -1124,7 +1137,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG if (cmd.gpuFramebuffer) { if (device.stateCache.glFramebuffer !== cmd.gpuFramebuffer.glFramebuffer) { - gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, cmd.gpuFramebuffer.glFramebuffer); + let glFBO = (cmd.gpuFramebuffer.glFramebuffer !== 0? cmd.gpuFramebuffer.glFramebuffer : null); + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, glFBO); device.stateCache.glFramebuffer = cmd.gpuFramebuffer.glFramebuffer; } @@ -1850,7 +1864,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG if (gpuInputAssembler && gpuShader) { let cmd = cmdPackage.drawCmds[drawCmdIdx++]; - for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { + for (let a = 0; a < device.maxVertexAttributes; ++a) { device.stateCache.glCurrentAttribLocs[a] = false; } @@ -1872,7 +1886,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } for (let c = 0; c < glAttrib.componentCount; ++c) { - let glLoc = glAttrib.glLoc + c; + let glLoc = glInput.glLoc + c; let offset = glAttrib.offset + glAttrib.size * c; if (!device.stateCache.glEnabledAttribLocs[glLoc] && glLoc >= 0) { @@ -1884,28 +1898,28 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, offset); } } - - if (gpuInputAssembler.gpuIndexBuffer && cmd.indexCount > 0) { - let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; - - if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; - } - - let offset = cmd.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, cmd.indexCount, gpuInputAssembler.glIndexType, offset); - } else { - gl.drawArrays(glPrimitive, cmd.firstVertex, cmd.vertexCount); - } - - for (let a = 0; a < GFX_MAX_VERTEX_ATTRIBUTES; ++a) { - if (device.stateCache.glEnabledAttribLocs[a] != device.stateCache.glCurrentAttribLocs[a]) { - gl.disableVertexAttribArray(a); - device.stateCache.glEnabledAttribLocs[a] = false; - } - } } // if + + if (gpuInputAssembler.gpuIndexBuffer && cmd.indexCount > 0) { + let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + + let offset = cmd.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, cmd.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, cmd.firstVertex, cmd.vertexCount); + } + + for (let a = 0; a < device.maxVertexAttributes; ++a) { + if (device.stateCache.glEnabledAttribLocs[a] != device.stateCache.glCurrentAttribLocs[a]) { + gl.disableVertexAttribArray(a); + device.stateCache.glEnabledAttribLocs[a] = false; + } + } } break; } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 3f4516adc2..4697c6b81f 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -31,7 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType } from '../define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat } from '../define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -109,12 +109,32 @@ export class WebGLGFXDevice extends GFXDevice { this._WEBGL_debug_renderer_info = this._webGLRC.getExtension("WEBGL_debug_renderer_info"); if (this._WEBGL_debug_renderer_info) { - let renderer = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); - console.info("RENDERER: " + renderer); - - let vendor = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); - console.info("VENDOR: " + vendor); + this._renderer = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); + this._vendor = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); + } else { + this._renderer = this._webGLRC.getParameter(WebGLRenderingContext.RENDERER); + this._vendor = this._webGLRC.getParameter(WebGLRenderingContext.VENDOR); } + + this._version = this._webGLRC.getParameter(WebGLRenderingContext.VERSION); + this._maxVertexAttributes = this._webGLRC.getParameter(WebGLRenderingContext.MAX_VERTEX_ATTRIBS); + this._maxVertexUniformVectors = this._webGLRC.getParameter(WebGLRenderingContext.MAX_VERTEX_UNIFORM_VECTORS); + this._maxFragmentUniformVectors = this._webGLRC.getParameter(WebGLRenderingContext.MAX_FRAGMENT_UNIFORM_VECTORS); + this._maxTextureUnits = this._webGLRC.getParameter(WebGLRenderingContext.MAX_TEXTURE_IMAGE_UNITS); + this._maxVertexTextureUnits = this._webGLRC.getParameter(WebGLRenderingContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + this._depthBits = this._webGLRC.getParameter(WebGLRenderingContext.DEPTH_BITS); + this._stencilBits = this._webGLRC.getParameter(WebGLRenderingContext.STENCIL_BITS); + + console.info("RENDERER: " + this._renderer); + console.info("VENDOR: " + this._vendor); + console.info("VERSION: " + this._version); + console.info("MAX_VERTEX_ATTRIBS: " + this._maxVertexAttributes); + console.info("MAX_VERTEX_UNIFORM_VECTORS: " + this._maxVertexUniformVectors); + console.info("MAX_FRAGMENT_UNIFORM_VECTORS: " + this._maxFragmentUniformVectors); + console.info("MAX_TEXTURE_IMAGE_UNITS: " + this._maxTextureUnits); + console.info("MAX_VERTEX_TEXTURE_IMAGE_UNITS: " + this._maxVertexTextureUnits); + console.info("DEPTH_BITS: " + this._depthBits); + console.info("STENCIL_BITS: " + this._stencilBits); this._extensions = this._webGLRC.getSupportedExtensions(); /* @@ -146,6 +166,22 @@ export class WebGLGFXDevice extends GFXDevice { this._ANGLE_instanced_arrays = this._webGLRC.getExtension("ANGLE_instanced_arrays"); this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); + + let depthStencilFmt; + + if(this._depthBits === 24) { + if(this._stencilBits === 8) { + depthStencilFmt = GFXFormat.D24S8; + } else { + depthStencilFmt = GFXFormat.D24; + } + } else { + if(this._stencilBits === 8) { + depthStencilFmt = GFXFormat.D16S8; + } else { + depthStencilFmt = GFXFormat.D16; + } + } // create primary window this._mainWindow = this.createWindow({ @@ -154,6 +190,8 @@ export class WebGLGFXDevice extends GFXDevice { top: this._webGLRC.canvas.offsetTop, width: this._webGLRC.drawingBufferWidth, height: this._webGLRC.drawingBufferHeight, + colorFmt: GFXFormat.RGBA8, + depthStencilFmt: depthStencilFmt, }); this._cmdAllocator = this.createCommandAllocator({}); @@ -486,8 +524,8 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { let gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, - colorAttachments: info.colorAttachments? info.colorAttachments : [], - depthStencilAttachment: info.depthStencilAttachment? info.depthStencilAttachment : null, + colorAttachments: info.colorAttachments ? info.colorAttachments : [], + depthStencilAttachment: info.depthStencilAttachment ? info.depthStencilAttachment : null, } return gpuRenderPass; @@ -500,42 +538,59 @@ export class WebGLGFXDevice extends GFXDevice { let renderPass = info.renderPass; - let gpuColorViews: WebGLGPUTextureView[] = []; + let isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; + if (isOffscreen) { - if (info.colorViews) { - for (let i = 0; i < info.colorViews.length; ++i) { - let webGLColorView = info.colorViews[i]; - if(webGLColorView.gpuTextureView) { - gpuColorViews.push(webGLColorView.gpuTextureView); + let gpuColorViews: WebGLGPUTextureView[] = []; + + if (info.colorViews) { + for (let i = 0; i < info.colorViews.length; ++i) { + let webGLColorView = info.colorViews[i]; + if (webGLColorView.gpuTextureView) { + gpuColorViews.push(webGLColorView.gpuTextureView); + } } } + + let gpuDepthStencilView: WebGLGPUTextureView | null = null; + + if (info.depthStencilView) { + gpuDepthStencilView = (info.depthStencilView).gpuTextureView; + } + + let gpuFramebuffer: WebGLGPUFramebuffer = { + objType: WebGLGPUObjectType.FRAMEBUFFER, + gpuRenderPass: renderPass.gpuRenderPass, + gpuColorViews: gpuColorViews, + gpuDepthStencilView: gpuDepthStencilView, + isOffscreen: info.isOffscreen, + glFramebuffer: 0, + }; + + // TODO: Async + WebGLCmdFuncCreateFramebuffer(this, gpuFramebuffer); + + return gpuFramebuffer; + + } else { + let gpuFramebuffer: WebGLGPUFramebuffer = { + objType: WebGLGPUObjectType.FRAMEBUFFER, + gpuRenderPass: renderPass.gpuRenderPass, + gpuColorViews: [], + gpuDepthStencilView: null, + isOffscreen: info.isOffscreen, + glFramebuffer: 0, + }; + + return gpuFramebuffer; } - - let gpuDepthStencilView: WebGLGPUTextureView | null = null; - - if (info.depthStencilView) { - gpuDepthStencilView = (info.depthStencilView).gpuTextureView; - } - - let gpuFramebuffer: WebGLGPUFramebuffer = { - objType: WebGLGPUObjectType.FRAMEBUFFER, - gpuRenderPass: renderPass.gpuRenderPass, - gpuColorViews: gpuColorViews, - gpuDepthStencilView: gpuDepthStencilView, - isOffscreen: info.isOffscreen, - glFramebuffer: 0, - }; - - // TODO: Async - WebGLCmdFuncCreateFramebuffer(this, gpuFramebuffer); - - return gpuFramebuffer; } public emitCmdDestroyGPUFramebuffer(gpuFramebuffer: WebGLGPUFramebuffer) { - - // TODO: Async - WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); + if (gpuFramebuffer.isOffscreen) { + // TODO: Async + WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); + } } public emitCmdCreateGPUSampler(info: GFXSamplerInfo): WebGLGPUSampler { diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index eaec3dca2d..9ea8bd8d62 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -13,12 +13,12 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { this._renderPass = info.renderPass; - if(info.colorViews) { + if(info.colorViews !== undefined) { this._colorViews = info.colorViews; } - this._depthStencilView = info.depthStencilView? info.depthStencilView : null; - this._isOffscreen = info.isOffscreen? info.isOffscreen : true; + this._depthStencilView = info.depthStencilView !== undefined? info.depthStencilView : null; + this._isOffscreen = info.isOffscreen !== undefined? info.isOffscreen : true; this._gpuFramebuffer = this.webGLDevice.emitCmdCreateGPUFramebuffer(info); diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 1133d9bfd2..ca45a0bff6 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -230,7 +230,6 @@ export class WebGLGPUBindingLayout extends WebGLGPUObject { export class WebGLAttrib { name: string = ""; glBuffer: WebGLBuffer = 0; - glLoc: number = 0; glType: GLenum = 0; size: number = 0; count: number = 0; diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index 9c9061185e..e74a2d8b99 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -19,7 +19,7 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { this._attributes = info.attributes; this._vertexBuffers = info.vertexBuffers; - if (info.indexBuffer) { + if (info.indexBuffer !== undefined) { this._indexBuffer = info.indexBuffer; this._indexCount = this._indexBuffer.size / this._indexBuffer.stride; } else { @@ -27,7 +27,7 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { this._vertexCount = vertBuff.size / vertBuff.stride; } - if (info.isIndirect) { + if (info.isIndirect !== undefined) { this._isIndirect = info.isIndirect; } diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts index 85f92c6cb2..e42563dc34 100644 --- a/cocos/gfx/webgl/webgl-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -1,8 +1,7 @@ import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUPipelineLayout } from './webgl-gpu-objects'; -import { GFXPipelineLayout } from '../pipeline-layout'; -import { GFXPipelineLayoutInfo } from '../binding-layout'; +import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../pipeline-layout'; export class WebGLGFXPipelineLayout extends GFXPipelineLayout { @@ -14,7 +13,7 @@ export class WebGLGFXPipelineLayout extends GFXPipelineLayout { this._layouts = info.layouts; - if(info.pushConstantsRanges) { + if(info.pushConstantsRanges !== undefined) { this._pushConstantsRanges = info.pushConstantsRanges; } diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts index b907ce4982..90d778ae39 100644 --- a/cocos/gfx/webgl/webgl-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -11,11 +11,11 @@ export class WebGLGFXRenderPass extends GFXRenderPass { public initialize(info: GFXRenderPassInfo): boolean { - if (info.colorAttachments) { + if (info.colorAttachments !== undefined) { this._colorInfos = info.colorAttachments; } - if (info.depthStencilAttachment) { + if (info.depthStencilAttachment !== undefined) { this._depthStencilInfo = info.depthStencilAttachment; } diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts index 575ca6fce7..b4f57c19c7 100644 --- a/cocos/gfx/webgl/webgl-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -13,55 +13,55 @@ export class WebGLGFXSampler extends GFXSampler { public initialize(info : GFXSamplerInfo) : boolean { - if(info.name) { + if(info.name !== undefined) { this._state.name = info.name; } - if(info.minFilter) { + if(info.minFilter !== undefined) { this._state.minFilter = info.minFilter; } - if(info.magFilter) { + if(info.magFilter !== undefined) { this._state.magFilter = info.magFilter; } - if(info.mipFilter) { + if(info.mipFilter !== undefined) { this._state.mipFilter = info.mipFilter; } - if(info.addressU) { + if(info.addressU !== undefined) { this._state.addressU = info.addressU; } - if(info.addressV) { + if(info.addressV !== undefined) { this._state.addressV = info.addressV; } - if(info.addressW) { + if(info.addressW !== undefined) { this._state.addressW = info.addressW; } - if(info.maxAnisotropy) { + if(info.maxAnisotropy !== undefined) { this._state.maxAnisotropy = info.maxAnisotropy; } - if(info.cmpFunc) { + if(info.cmpFunc !== undefined) { this._state.cmpFunc = info.cmpFunc; } - if(info.borderColor) { + if(info.borderColor !== undefined) { this._state.borderColor = info.borderColor; } - if(info.minLOD) { + if(info.minLOD !== undefined) { this._state.minLOD = info.minLOD; } - if(info.maxLOD) { + if(info.maxLOD !== undefined) { this._state.maxLOD = info.maxLOD; } - if(info.mipLODBias) { + if(info.mipLODBias !== undefined) { this._state.mipLODBias = info.mipLODBias; } diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts index ea478eff1d..a0fe6ad917 100644 --- a/cocos/gfx/webgl/webgl-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -13,8 +13,14 @@ export class WebGLGFXShader extends GFXShader { this._name = info.name; this._stages = info.stages; - this._blocks = info.blocks; - this._samplers = info.samplers; + + if(info.blocks !== undefined) { + this._blocks = info.blocks; + } + + if(info.samplers !== undefined) { + this._samplers = info.samplers; + } this._gpuShader = this.webGLDevice.emitCmdCreateGPUShader(info); diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index 5a6eecea2e..f3763492f9 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -19,7 +19,7 @@ export class WebGLStateCache { texUnit : number = 0; glTex2DUnits : WebGLTexUnit[]; glTexCubeUnits : WebGLTexUnit[]; - glFramebuffer : WebGLFramebuffer = 0; + glFramebuffer : WebGLFramebuffer = -1; viewport : GFXViewport; scissorRect : GFXRect; rs : GFXRasterizerState; diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts index c98fc4d510..aa9e0a289a 100644 --- a/cocos/gfx/webgl/webgl-texture-view.ts +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -16,19 +16,19 @@ export class WebGLGFXTextureView extends GFXTextureView { this._format = info.format; this._format = info.format; - if (info.baseLevel) { + if (info.baseLevel !== undefined) { this._baseLevel = info.baseLevel; } - if (info.levelCount) { + if (info.levelCount !== undefined) { this._levelCount = info.levelCount; } - if (info.baseLayer) { + if (info.baseLayer !== undefined) { this._baseLayer = info.baseLayer; } - if (info.layerCount) { + if (info.layerCount !== undefined) { this._layerCount = info.layerCount; } diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index 56c2293505..fbef91e69d 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -6,21 +6,34 @@ import { GFXFormatSurfaceSize, GFXTextureFlagBit } from '../define'; export class WebGLGFXTexture extends GFXTexture { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { super(device); } - public initialize(info : GFXTextureInfo) : boolean { + public initialize(info: GFXTextureInfo): boolean { this._type = info.type; this._usage = info.usage; this._format = info.format; this._width = info.width; this._height = info.height; - this._depth = info.depth? info.depth : 1; - this._arrayLayer = info.arrayLayer? info.arrayLayer : 1; - this._mipLevel = info.mipLevel? info.mipLevel : 1; - this._flags = info.flags? info.flags : GFXTextureFlagBit.NONE; + + if (info.depth !== undefined) { + this._depth = info.depth; + } + + if (info.arrayLayer !== undefined) { + this._arrayLayer = info.arrayLayer; + } + + if (info.mipLevel !== undefined) { + this._mipLevel = info.mipLevel; + } + + if (info.flags !== undefined) { + this._flags = info.flags; + } + this._size = GFXFormatSurfaceSize(this._format, this.width, this.height, this.depth, this.mipLevel) * this._arrayLayer; if (this._flags & GFXTextureFlagBit.BAKUP_BUFFER) { @@ -34,19 +47,19 @@ export class WebGLGFXTexture extends GFXTexture { public destroy() { - if(this._gpuTexture) { + if (this._gpuTexture) { this.webGLDevice.emitCmdDestroyGPUTexture(this._gpuTexture); this._gpuTexture = null; } } - public get webGLDevice() : WebGLGFXDevice { + public get webGLDevice(): WebGLGFXDevice { return this._device; } - public get gpuTexture() : WebGLGPUTexture { + public get gpuTexture(): WebGLGPUTexture { return this._gpuTexture; } - private _gpuTexture : WebGLGPUTexture | null = null; + private _gpuTexture: WebGLGPUTexture | null = null; }; diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index 47b1caf56e..742c43264a 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -25,13 +25,8 @@ export class WebGLGFXWindow extends GFXWindow { this._width = info.width; this._height = info.height; - this._colorFmt = GFXFormat.RGBA8; - - if(this.webGLDevice.WEBGL_depth_texture) { - this._depthStencilFmt = GFXFormat.D24S8; - } else { - this._depthStencilFmt = GFXFormat.D16S8; - } + this._colorFmt = info.colorFmt; + this._depthStencilFmt = info.depthStencilFmt; this._renderPass = this._device.createRenderPass({ colorAttachments: [{ @@ -59,6 +54,7 @@ export class WebGLGFXWindow extends GFXWindow { return false; } + /* this._colorTex = this._device.createTexture({ type : GFXTextureType.TEX2D, usage : GFXTextureUsageBit.COLOR_ATTACHMENT, @@ -122,11 +118,12 @@ export class WebGLGFXWindow extends GFXWindow { this.destroy(); return false; } - + */ + this._framebuffer = this._device.createFramebuffer({ renderPass: this._renderPass, - colorViews: [this._colorTexView], - depthStencilView: this._depthStencilTexView, + //colorViews: [this._colorTexView], + //depthStencilView: this._depthStencilTexView, isOffscreen: false, }); @@ -139,6 +136,7 @@ export class WebGLGFXWindow extends GFXWindow { } public destroy() { + /* if(this._depthStencilTexView) { this._depthStencilTexView.destroy(); this._depthStencilTexView = null; @@ -158,7 +156,8 @@ export class WebGLGFXWindow extends GFXWindow { this._colorTex.destroy(); this._colorTex = null; } - + */ + if(this._framebuffer) { this._framebuffer.destroy(); this._framebuffer = null; diff --git a/cocos/gfx/window.ts b/cocos/gfx/window.ts index f4f60e6ee3..81b9681634 100644 --- a/cocos/gfx/window.ts +++ b/cocos/gfx/window.ts @@ -11,6 +11,8 @@ export interface GFXWindowInfo { top?: number; width: number; height: number; + colorFmt: GFXFormat; + depthStencilFmt: GFXFormat; }; export abstract class GFXWindow { @@ -55,9 +57,9 @@ export abstract class GFXWindow { protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; protected _renderPass: GFXRenderPass | null = null; - protected _colorTex: GFXTexture | null = null; - protected _colorTexView: GFXTextureView | null = null; - protected _depthStencilTex: GFXTexture | null = null; - protected _depthStencilTexView: GFXTextureView | null = null; + //protected _colorTex: GFXTexture | null = null; + //protected _colorTexView: GFXTextureView | null = null; + //protected _depthStencilTex: GFXTexture | null = null; + //protected _depthStencilTexView: GFXTextureView | null = null; protected _framebuffer: GFXFramebuffer | null = null; }; diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 7c68d890da..21bbecf346 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -14,7 +14,7 @@ export class ForwardFlow extends RenderFlow { public initialize(info: RenderFlowInfo): boolean { - if (info.name) { + if (info.name !== undefined) { this._name = info.name; } diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index a89647a1e8..ef33409370 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -14,7 +14,7 @@ export class ForwardStage extends RenderStage { public initialize(info: RenderStageInfo): boolean { - if(info.name) { + if(info.name !== undefined) { this._name = info.name; } diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 375d7bf03b..6e3a0e57b1 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -3,7 +3,7 @@ import { RenderFlow } from "../render-flow"; import { GFXCommandBuffer } from "../../gfx/command-buffer"; import { RenderView } from "../render-view"; import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode } from "../../gfx/define"; +import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat } from "../../gfx/define"; import { GFXInputAssembler } from "../../gfx/input-assembler"; import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; import { GFXShader } from "../../gfx/shader"; @@ -11,19 +11,19 @@ import { GFXRenderPass } from "../../gfx/render-pass"; import { GFXPipelineLayout } from "../../gfx/pipeline-layout"; import { GFXBindingLayout } from "../../gfx/binding-layout"; -let _shader_vs =` +let _shader_vs = +`#version 100 attribute vec2 a_position; attribute vec2 a_texCoord; void main() { gl_Position = vec4(a_position, 0.0, 1.0); -} -`; +}`; -let _shader_fs =` +let _shader_fs = +`#version 100 void main() { - gl_FragColor = vec4(0.3, 0.3, 0.8, 1.0); -}\n -`; + gl_FragColor = vec4(0.6, 0.3, 0.3, 1.0); +}`; export class TestStage extends RenderStage { @@ -33,7 +33,7 @@ export class TestStage extends RenderStage { public initialize(info: RenderStageInfo): boolean { - if (info.name) { + if (info.name !== undefined) { this._name = info.name; } @@ -61,7 +61,7 @@ export class TestStage extends RenderStage { this._shader = this._device.createShader({ name: "test", - stages: [vsStage, fsStage], + stages: [vsStage, fsStage] }); if (!this._shader) { return false; diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index 90011e91fa..f739f39e61 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -25,13 +25,8 @@ export abstract class RenderStage { } this._device = this._flow.pipeline.root.device; - - this._clearColors = new Array(GFX_MAX_ATTACHMENTS); - for (let i = 0; i < GFX_MAX_ATTACHMENTS; ++i) { - this._clearColors[i] = { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }; - } - - this._renderArea = {left: 0, top: 0, width: 0, height: 0}; + this._clearColors = [{ r: 0.3, g: 0.6, b: 0.9, a: 1.0 }]; + this._renderArea = { left: 0, top: 0, width: 0, height: 0 }; } public abstract initialize(info: RenderStageInfo): boolean; @@ -42,9 +37,16 @@ export abstract class RenderStage { } - public setClearColor(idx: number, color: GFXColor) { - console.assert(idx < GFX_MAX_ATTACHMENTS); - this._clearColors[idx] = color; + public setClearColor(color: GFXColor) { + if (this._clearColors.length > 0) { + this._clearColors[0] = color; + } else { + this._clearColors.push(color); + } + } + + public setClearColors(colors: GFXColor[]) { + this._clearColors = colors; } public setClearDepth(depth: number) { diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 5f27e1de57..56f95eed2c 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -36,7 +36,7 @@ export class RenderScene { } public createNode(info: SceneNodeInfo): Node { - let node = new Node(name); + let node = new Node(info.name); this._nodes.set(node.uuid, node); return node; } diff --git a/playground/simple.html b/playground/simple.html index 7442f8e105..8fbfb431d2 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -28,7 +28,27 @@ From 5d3a88ab8ad3c1bd02d9970ea6f1a94a5a165a59 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 3 Jan 2019 16:02:07 +0800 Subject: [PATCH 026/267] effect --- cocos/3d/assets/effect-asset.ts | 78 +++---- cocos/3d/assets/material.js | 2 +- cocos/3d/builtin/effects.js | 70 +++--- cocos/3d/builtin/init.js | 126 +++++------ cocos/core/game.js | 14 +- cocos/gfx/define.ts | 1 + cocos/gfx/pipeline-state.ts | 106 ++++----- cocos/gfx/webgl/webgl-commands.ts | 193 ++++++++-------- cocos/renderer/core/effect.ts | 342 ++++++++++++++--------------- cocos/renderer/core/pass.ts | 103 ++++----- cocos/renderer/core/program-lib.js | 2 +- cocos/renderer/core/technique.ts | 46 ++-- 12 files changed, 546 insertions(+), 537 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index b268b8f979..84689d613d 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -2,56 +2,51 @@ import Asset from '../../assets/CCAsset'; import { ccclass, property } from '../../core/data/class-decorator'; import { PassInfo } from '../../renderer/core/pass'; -const effects: { [name: string]: EffectAsset } = {}; - -interface TechniqueInfo { +export interface TechniqueInfo { passes: PassInfo[]; queue?: number; priority?: number; lod?: number; } - -interface PropertyMap { - [name: string]: { - type: number, - value: number | number[] | null, - }; +export interface PropertyInfo { + type?: number; + value?: number | number[] | null; + displayName?: string; + tech?: number; + pass?: number; } -interface ShaderInfo { +export interface UniformInfo { name: string; - vert: string; frag: string; - vert1: string; frag1: string; - defines: Array<{ - name: string; - type: string; - defines: string[]; - }>; - uniforms: Array<{ - name: string; - type: string; - binding: number; - defines: string[]; - } | { - blockName: string; - binding: number; - defines: string[]; - members: Array< { name: string, type: number } > - }>; - attributes: Array<{ - name: string; - type: string; - defines: string[]; - }>; - extensions: Array<{ - name: string; - define: string; - }>; + type: number; + bindingType: number; + binding: number; + defines: string[]; + members?: Array< { name: string, type: number } >; } +export interface DefineInfo { + name: string; + type: string; + defines: string[]; +} +export interface ExtensionInfo { + name: string; + define: string; +} +export interface ShaderInfo { + name: string; + vert: string; + frag: string; + defines: DefineInfo[]; + uniforms: UniformInfo[]; + extensions: ExtensionInfo[]; +} + +const effects: { [name: string]: EffectAsset } = {}; @ccclass('cc.EffectAsset') -class EffectAsset extends Asset { - public static register(asset: EffectAsset) {effects[asset.name] = asset; } +export class EffectAsset extends Asset { + public static register(asset: EffectAsset) { effects[asset.name] = asset; } public static remove(name: string) { if (effects[name]) { delete effects[name]; return; } for (const n in effects) { @@ -76,17 +71,16 @@ class EffectAsset extends Asset { public techniques: TechniqueInfo[] = []; @property - public properties: PropertyMap = {}; + public properties: { [name: string]: PropertyInfo } = {}; @property public shaders: ShaderInfo[] = []; public onLoaded() { - const lib = cc.game._renderer._programLib; + const lib = cc.game._programLib; this.shaders.forEach((s) => lib.define(s)); EffectAsset.register(this); } } -export default EffectAsset; cc.EffectAsset = EffectAsset; diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js index 64e59e5c6a..c57b1a4f30 100644 --- a/cocos/3d/assets/material.js +++ b/cocos/3d/assets/material.js @@ -27,7 +27,7 @@ import { ccclass, property } from "../../core/data/class-decorator"; import Asset from "../../assets/CCAsset"; import TextureBase from '../../assets/texture-base'; import Effect from '../../renderer/core/effect'; -import EffectAsset from './effect-asset'; +import { EffectAsset } from './effect-asset'; @ccclass('cc.Material') class Material extends Asset { diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index d24467dbcf..0374c43b4a 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,30 +1,28 @@ export default [ { "name": "builtin-effect-unlit", - "techniques": [{"queue":0,"lod":100,"passes":[{"stage":1,"cullMode":1029,"depthTest":true,"depthWrite":true,"program":"aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9"}],"priority":0}], - "properties": {"color":{"type":9,"value":[1,1,1,1]},"mainTiling":{"type":5,"value":[1,1]},"mainOffset":{"type":5,"value":[0,0]},"mainTexture":{"type":13,"value":null}}, + "techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "7781d6cc411d5facce7fc3d4aeb5349e804ddd9a58c002017c53682b"}], "priority": 0}], + "properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": null}}, "shaders": [ { - "name": "aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9", - "vert": "\nattribute vec3 a_position;\nuniform mat4 _model;\nuniform mat4 _viewProj;\n#if USE_TEXTURE\n attribute vec2 a_texCoord1;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if USE_JOINTS_TEXTURE\nuniform sampler2D _u_jointsTexture;\nuniform float _u_jointsTextureSize;\nmat4 getBoneMatrix(const in float i) {\n float size = _u_jointsTextureSize;\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(_u_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(_u_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(_u_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(_u_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nuniform mat4 _u_jointMatrices[128];\nmat4 getBoneMatrix(const in float i) {\n return _u_jointMatrices[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 ;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_SKINNING\n pos = skinMatrix() * pos;\n #endif\n pos = _viewProj * _model * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord1 * 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", + "name": "7781d6cc411d5facce7fc3d4aeb5349e804ddd9a58c002017c53682b", + "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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_texCoord1;\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_texCoord1 * 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"}, - {"name": "USE_SKINNING", "type": "boolean"}, - {"name": "USE_JOINTS_TEXTURE", "type": "boolean"}, - {"name": "USE_COLOR", "type": "boolean"} + {"name": "USE_TEXTURE", "type": "boolean", "defines": []}, + {"name": "CC_USE_SKINNING", "type": "boolean", "defines": []}, + {"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]}, + {"name": "USE_COLOR", "type": "boolean", "defines": []} ], "uniforms": [ - {"name": "mainTiling", "type": 5, "defines": ["USE_TEXTURE"]}, - {"name": "mainOffset", "type": 5, "defines": ["USE_TEXTURE"]}, - {"name": "mainTexture", "type": 13, "defines": ["USE_TEXTURE"]}, - {"name": "color", "type": 7, "defines": ["USE_COLOR"]} - ], - "attributes": [ - {"name": "a_position", "type": 6, "defines": []}, - {"name": "a_texCoord1", "type": 5, "defines": ["USE_TEXTURE"]}, - {"name": "a_weights", "type": 7, "defines": ["USE_SKINNING"]}, - {"name": "a_joints", "type": 7, "defines": ["USE_SKINNING"]} + {"name": "TexCoords", "type": 0, "bindingType": 1, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ + {"name": "mainTiling", "type": 14}, + {"name": "mainOffset", "type": 14} + ]}, + {"name": "mainTexture", "type": 29, "bindingType": 2, "defines": ["USE_TEXTURE"], "binding": 1}, + {"name": "Constant", "type": 0, "bindingType": 1, "defines": ["USE_COLOR"], "binding": 2, "members": [ + {"name": "color", "type": 16} + ]} ], "extensions": [] } @@ -32,24 +30,38 @@ export default [ }, { "name": "builtin-effect-skybox", - "techniques": [{"queue":0,"lod":200,"passes":[{"stage":1,"cullMode":0,"program":"c4056e849fac08f88d82336386873a650bc636f4349623fecbf96c52"}],"priority":-1000}], - "properties": {"cubeMap":{"type":14,"value":null}}, + "techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "e4ea21ace566a0976909c9b0d082bf97c4a115f78bafe08d6c5edec7"}], "priority": -1000}], + "properties": {"cubeMap": {"type": 32, "value": null}}, "shaders": [ { - "name": "c4056e849fac08f88d82336386873a650bc636f4349623fecbf96c52", - "vert": "\n attribute vec3 a_position;\n uniform mat4 _view;\n uniform mat4 _proj;\n varying vec3 viewDir;\n void main() {\n mat4 rotView = mat4(mat3(_view));\n vec4 clipPos = _proj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n", + "name": "e4ea21ace566a0976909c9b0d082bf97c4a115f78bafe08d6c5edec7", + "vert": "\n attribute vec3 a_position;\n \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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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 rotView = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\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"} + {"name": "USE_RGBE_CUBEMAP", "type": "boolean", "defines": []} ], "uniforms": [ - {"name": "cubeMap", "type": 14, "defines": []} - ], - "attributes": [ - {"name": "a_position", "type": 6, "defines": []} + {"name": "cubeMap", "type": 32, "bindingType": 2, "defines": [], "binding": 0} ], "extensions": [] } ] - } + }, + { + "name": "builtin-effect-sprite", + "techniques": [{"queue": 2, "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "program": "b28a508b291d9314faba527c0f13b99420d5feebd86bd4d38554b256"}], "priority": 0}], + "properties": {"mainTexture": {"type": 29, "value": null}}, + "shaders": [ + { + "name": "b28a508b291d9314faba527c0f13b99420d5feebd86bd4d38554b256", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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": [], + "uniforms": [ + {"name": "mainTexture", "type": 29, "bindingType": 2, "defines": [], "binding": 0} + ], + "extensions": [] + } + ] + }, ]; diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index 6cc622f6f0..bf263c1e9f 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -2,74 +2,74 @@ import Texture2D from '../../assets/texture-2d'; import TextureCube from '../assets/texture-cube'; import ImageAsset from '../../assets/image-asset'; import Material from '../assets/material'; -import EffectAsset from '../assets/effect-asset'; +import { EffectAsset } from '../assets/effect-asset'; import effects from './effects'; let builtinResMgr = { // this should be called after renderer initialized initBuiltinRes: function(device) { builtinResMgr.device = device; - let canvas = document.createElement('canvas'); - let context = canvas.getContext('2d'); + // let canvas = document.createElement('canvas'); + // let context = canvas.getContext('2d'); - // ============================ - // builtin textures - // ============================ + // // ============================ + // // builtin textures + // // ============================ - // default texture canvas fill - canvas.width = canvas.height = 128; - context.fillStyle = '#ddd'; - context.fillRect(0, 0, 128, 128); - context.fillStyle = '#555'; - context.fillRect(0, 0, 64, 64); - context.fillStyle = '#555'; - context.fillRect(64, 64, 64, 64); + // // default texture canvas fill + // canvas.width = canvas.height = 128; + // context.fillStyle = '#ddd'; + // context.fillRect(0, 0, 128, 128); + // context.fillStyle = '#555'; + // context.fillRect(0, 0, 64, 64); + // context.fillStyle = '#555'; + // context.fillRect(64, 64, 64, 64); - const canvasImage = new ImageAsset(canvas); + // const canvasImage = new ImageAsset(canvas); - // default-texture - let defaultTexture = new Texture2D(); - defaultTexture.setMipFilter(Texture2D.Filter.LINEAR); - defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); - defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - defaultTexture._uuid = 'default-texture'; - defaultTexture.image = canvasImage; + // // default-texture + // let defaultTexture = new Texture2D(); + // defaultTexture.setMipFilter(Texture2D.Filter.LINEAR); + // defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); + // defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + // defaultTexture._uuid = 'default-texture'; + // defaultTexture.image = canvasImage; - // default-texture-cube - let defaultTextureCube = new TextureCube(); - defaultTextureCube._uuid = 'default-texture-cube'; - defaultTextureCube.image = { - front: canvasImage, - back: canvasImage, - left: canvasImage, - right: canvasImage, - top: canvasImage, - bottom: canvasImage, - }; + // // default-texture-cube + // let defaultTextureCube = new TextureCube(); + // defaultTextureCube._uuid = 'default-texture-cube'; + // defaultTextureCube.image = { + // front: canvasImage, + // back: canvasImage, + // left: canvasImage, + // right: canvasImage, + // top: canvasImage, + // bottom: canvasImage, + // }; - // black texture canvas fill - canvas.width = canvas.height = 2; - context.fillStyle = '#000'; - context.fillRect(0, 0, 2, 2); + // // black texture canvas fill + // canvas.width = canvas.height = 2; + // context.fillStyle = '#000'; + // context.fillRect(0, 0, 2, 2); - // black-texture - let blackTexture = new Texture2D(); - blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - blackTexture._uuid = 'black-texture'; - defaultTexture.image = canvasImage; + // // black-texture + // let blackTexture = new Texture2D(); + // blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + // blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + // blackTexture._uuid = 'black-texture'; + // defaultTexture.image = canvasImage; - // white texture canvas fill - canvas.width = canvas.height = 2; - context.fillStyle = '#fff'; - context.fillRect(0, 0, 2, 2); + // // white texture canvas fill + // canvas.width = canvas.height = 2; + // context.fillStyle = '#fff'; + // context.fillRect(0, 0, 2, 2); - // white-texture - let whiteTexture = new Texture2D(); - blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - whiteTexture._uuid = 'white-texture'; - defaultTexture.image = canvasImage; + // // white-texture + // let whiteTexture = new Texture2D(); + // blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + // blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + // whiteTexture._uuid = 'white-texture'; + // defaultTexture.image = canvasImage; // essential builtin effects let efxs = effects.map(e => { @@ -78,18 +78,18 @@ let builtinResMgr = { }); // default material - let defaultMtl = new Material(); - defaultMtl._uuid = 'default-material'; - defaultMtl.effectAsset = efxs[0]; - defaultMtl.define('USE_COLOR', true); - defaultMtl.setProperty('color', cc.color('#FF00FF')); + // let defaultMtl = new Material(); + // defaultMtl._uuid = 'default-material'; + // defaultMtl.effectAsset = efxs[0]; + // defaultMtl.define('USE_COLOR', true); + // defaultMtl.setProperty('color', cc.color('#FF00FF')); let builtins = { - [defaultTexture._uuid]: defaultTexture, - [defaultTextureCube._uuid]: defaultTextureCube, - [blackTexture._uuid]: blackTexture, - [whiteTexture._uuid]: whiteTexture, - [defaultMtl._uuid]: defaultMtl + // [defaultTexture._uuid]: defaultTexture, + // [defaultTextureCube._uuid]: defaultTextureCube, + // [blackTexture._uuid]: blackTexture, + // [whiteTexture._uuid]: whiteTexture, + // [defaultMtl._uuid]: defaultMtl }; return Object.assign(builtinResMgr, builtins); }, diff --git a/cocos/core/game.js b/cocos/core/game.js index 4f875a8ecc..1a00132f84 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -31,6 +31,7 @@ import { addon } from './utils/js'; import renderer from '../renderer'; import builtinResMgr from '../3d/builtin/init'; +import ProgramLib from '../renderer/core/program-lib'; /** * @module cc @@ -371,7 +372,7 @@ var game = { // Init engine this._initEngine(); - //this._initBuiltins(); + this._initBuiltins(); // Log engine version console.log('Cocos3D v' + cc.ENGINE_VERSION); @@ -816,11 +817,12 @@ var game = { }, _initBuiltins: function() { - let builtins = builtinResMgr.initBuiltinRes(this._renderContext); - this._renderer.setBuiltins({ - defaultTexture: builtins['default-texture']._texture, - defaultTextureCube: builtins['default-texture-cube']._texture, - }); + this._programLib = new ProgramLib(this._gfxDevice); + builtinResMgr.initBuiltinRes(this._gfxDevice); + // this._renderer.setBuiltins({ + // defaultTexture: builtins['default-texture']._texture, + // defaultTextureCube: builtins['default-texture-cube']._texture, + // }); }, _initEvents: function () { diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 68de6cba03..3ed1bb1e33 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -51,6 +51,7 @@ export enum GFXType { FLOAT2, FLOAT3, FLOAT4, + COLOR4, MAT2, MAT2X3, MAT2X4, diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index fbb24740e6..e371b7dcb1 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -32,75 +32,75 @@ export class GFXRasterizerState { }; export class GFXDepthStencilState { - isDepthTest: boolean = true; - isWriteDepth: boolean = true; + depthTest: boolean = true; + depthWrite: boolean = true; depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; - isFrontStencilTest: boolean = false; - frontStencilFunc: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - frontStencilReadMask: number = 0xffffffff; - frontStencilWriteMask: number = 0xffffffff; - frontStencilFailOp: GFXStencilOp = GFXStencilOp.KEEP; - frontStencilDepthFailOp: GFXStencilOp = GFXStencilOp.KEEP; - frontStencilPassOp: GFXStencilOp = GFXStencilOp.KEEP; - frontStencilRef: number = 1; - isBackStencilTest: boolean = false; - backStencilFunc: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - backStencilReadMask: number = 0xffffffff; - backStencilWriteMask: number = 0xffffffff; - backStencilFailOp: GFXStencilOp = GFXStencilOp.KEEP; - backStencilDepthFailOp: GFXStencilOp = GFXStencilOp.KEEP; - backStencilPassOp: GFXStencilOp = GFXStencilOp.KEEP; - backStencilRef: number = 1; + stencilTestFront: boolean = false; + stencilFuncFront: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + stencilReadMaskFront: number = 0xffffffff; + stencilWriteMaskFront: number = 0xffffffff; + stencilFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; + stencilZFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; + stencilPassOpFront: GFXStencilOp = GFXStencilOp.KEEP; + stencilRefFront: number = 1; + stencilTestBack: boolean = false; + stencilFuncBack: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + stencilReadMaskBack: number = 0xffffffff; + stencilWriteMaskBack: number = 0xffffffff; + stencilFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; + stencilZFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; + stencilPassOpBack: GFXStencilOp = GFXStencilOp.KEEP; + stencilRefBack: number = 1; public compare(state: GFXDepthStencilState): boolean { - return (this.isDepthTest === state.isDepthTest) && - (this.isWriteDepth === state.isWriteDepth) && + return (this.depthTest === state.depthTest) && + (this.depthWrite === state.depthWrite) && (this.depthFunc === state.depthFunc) && - (this.isFrontStencilTest === state.isFrontStencilTest) && - (this.frontStencilFunc === state.frontStencilFunc) && - (this.frontStencilReadMask === state.frontStencilReadMask) && - (this.frontStencilWriteMask === state.frontStencilWriteMask) && - (this.frontStencilFailOp === state.frontStencilFailOp) && - (this.frontStencilDepthFailOp === state.frontStencilDepthFailOp) && - (this.frontStencilPassOp === state.frontStencilPassOp) && - (this.frontStencilRef === state.frontStencilRef) && - (this.isBackStencilTest === state.isBackStencilTest) && - (this.backStencilFunc === state.backStencilFunc) && - (this.backStencilReadMask === state.backStencilReadMask) && - (this.backStencilWriteMask === state.backStencilWriteMask) && - (this.backStencilFailOp === state.backStencilFailOp) && - (this.backStencilDepthFailOp === state.backStencilDepthFailOp) && - (this.backStencilPassOp === state.backStencilPassOp) && - (this.backStencilRef === state.backStencilRef); + (this.stencilTestFront === state.stencilTestFront) && + (this.stencilFuncFront === state.stencilFuncFront) && + (this.stencilReadMaskFront === state.stencilReadMaskFront) && + (this.stencilWriteMaskFront === state.stencilWriteMaskFront) && + (this.stencilFailOpFront === state.stencilFailOpFront) && + (this.stencilZFailOpFront === state.stencilZFailOpFront) && + (this.stencilPassOpFront === state.stencilPassOpFront) && + (this.stencilRefFront === state.stencilRefFront) && + (this.stencilTestBack === state.stencilTestBack) && + (this.stencilFuncBack === state.stencilFuncBack) && + (this.stencilReadMaskBack === state.stencilReadMaskBack) && + (this.stencilWriteMaskBack === state.stencilWriteMaskBack) && + (this.stencilFailOpBack === state.stencilFailOpBack) && + (this.stencilZFailOpBack === state.stencilZFailOpBack) && + (this.stencilPassOpBack === state.stencilPassOpBack) && + (this.stencilRefBack === state.stencilRefBack); } }; export class GFXBlendTarget { - isBlend: boolean = false; - srcBlend: GFXBlendFactor = GFXBlendFactor.ONE; - dstBlend: GFXBlendFactor = GFXBlendFactor.ZERO; - blendOp: GFXBlendOp = GFXBlendOp.ADD; - srcAlphaBlend: GFXBlendFactor = GFXBlendFactor.ONE; - dstAlphaBlend: GFXBlendFactor = GFXBlendFactor.ZERO; - alphBlendOp: GFXBlendOp = GFXBlendOp.ADD; - colorWriteMask: GFXColorMask = GFXColorMask.ALL; + blend: boolean = false; + blendSrc: GFXBlendFactor = GFXBlendFactor.ONE; + blendDst: GFXBlendFactor = GFXBlendFactor.ZERO; + blendEq: GFXBlendOp = GFXBlendOp.ADD; + blendSrcAlpha: GFXBlendFactor = GFXBlendFactor.ONE; + blendDstAlpha: GFXBlendFactor = GFXBlendFactor.ZERO; + blendAlphaEq: GFXBlendOp = GFXBlendOp.ADD; + blendColorMask: GFXColorMask = GFXColorMask.ALL; public compare(state: GFXBlendTarget): boolean { - return (this.isBlend === state.isBlend) && - (this.srcBlend === state.srcBlend) && - (this.dstBlend === state.dstBlend) && - (this.blendOp === state.blendOp) && - (this.srcAlphaBlend === state.srcAlphaBlend) && - (this.dstAlphaBlend === state.dstAlphaBlend) && - (this.alphBlendOp === state.alphBlendOp) && - (this.colorWriteMask === state.colorWriteMask); + return (this.blend === state.blend) && + (this.blendSrc === state.blendSrc) && + (this.blendDst === state.blendDst) && + (this.blendEq === state.blendEq) && + (this.blendSrcAlpha === state.blendSrcAlpha) && + (this.blendDstAlpha === state.blendDstAlpha) && + (this.blendAlphaEq === state.blendAlphaEq) && + (this.blendColorMask === state.blendColorMask); } }; export class GFXBlendState { isA2C: boolean = false; isIndepend: boolean = false; - factor: number[] = [0, 0, 0, 0]; + blendColor: number[] = [0, 0, 0, 0]; targets: GFXBlendTarget[] = [new GFXBlendTarget]; } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 3402c4c3eb..293f079092 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -202,6 +202,7 @@ function GFXTypeToWebGLType(type: GFXType): GLenum { case GFXType.FLOAT2: return WebGLRenderingContext.FLOAT_VEC2; case GFXType.FLOAT3: return WebGLRenderingContext.FLOAT_VEC3; case GFXType.FLOAT4: return WebGLRenderingContext.FLOAT_VEC4; + case GFXType.COLOR4: return WebGLRenderingContext.FLOAT_VEC4; case GFXType.MAT2: return WebGLRenderingContext.FLOAT_MAT2; case GFXType.MAT3: return WebGLRenderingContext.FLOAT_MAT3; case GFXType.MAT4: return WebGLRenderingContext.FLOAT_MAT4; @@ -1181,7 +1182,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case GFXLoadOp.LOAD: break; // GL default behaviour case GFXLoadOp.CLEAR: { - if (device.stateCache.bs.targets[0].colorWriteMask !== GFXColorMask.ALL) { + if (device.stateCache.bs.targets[0].blendColorMask !== GFXColorMask.ALL) { gl.colorMask(true, true, true, true); } @@ -1208,7 +1209,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case GFXLoadOp.LOAD: break; // GL default behaviour case GFXLoadOp.CLEAR: { - if (!device.stateCache.dss.isWriteDepth) { + if (!device.stateCache.dss.depthWrite) { gl.depthMask(true); } @@ -1231,11 +1232,11 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case GFXLoadOp.LOAD: break; // GL default behaviour case GFXLoadOp.CLEAR: { - if (!device.stateCache.dss.frontStencilWriteMask) { + if (!device.stateCache.dss.stencilWriteMaskFront) { gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0xFFFFFFFF); } - if (!device.stateCache.dss.backStencilWriteMask) { + if (!device.stateCache.dss.stencilWriteMaskBack) { gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0xFFFFFFFF); } @@ -1268,7 +1269,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG // restore states if (clears & WebGLRenderingContext.COLOR_BUFFER_BIT) { - let colorMask = device.stateCache.bs.targets[0].colorWriteMask; + let colorMask = device.stateCache.bs.targets[0].blendColorMask; if (colorMask !== GFXColorMask.ALL) { let r = (colorMask & GFXColorMask.R) != GFXColorMask.NONE; let g = (colorMask & GFXColorMask.G) != GFXColorMask.NONE; @@ -1279,16 +1280,16 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } if ((clears & WebGLRenderingContext.DEPTH_BUFFER_BIT) && - !device.stateCache.dss.isWriteDepth) { + !device.stateCache.dss.depthWrite) { gl.depthMask(false); } if (clears & WebGLRenderingContext.STENCIL_BUFFER_BIT) { - if (!device.stateCache.dss.frontStencilWriteMask) { + if (!device.stateCache.dss.stencilWriteMaskFront) { gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0); } - if (!device.stateCache.dss.backStencilWriteMask) { + if (!device.stateCache.dss.stencilWriteMaskBack) { gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0); } } @@ -1370,18 +1371,18 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let dss = cmd.gpuPipelineState.dss; if (dss) { - if (device.stateCache.dss.isDepthTest !== dss.isDepthTest) { - if (dss.isDepthTest) { + if (device.stateCache.dss.depthTest !== dss.depthTest) { + if (dss.depthTest) { gl.enable(WebGLRenderingContext.DEPTH_TEST); } else { gl.disable(WebGLRenderingContext.DEPTH_TEST); } - device.stateCache.dss.isDepthTest = dss.isDepthTest; + device.stateCache.dss.depthTest = dss.depthTest; } - if (device.stateCache.dss.isWriteDepth !== dss.isWriteDepth) { - gl.depthMask(dss.isWriteDepth); - device.stateCache.dss.isWriteDepth = dss.isWriteDepth; + if (device.stateCache.dss.depthWrite !== dss.depthWrite) { + gl.depthMask(dss.depthWrite); + device.stateCache.dss.depthWrite = dss.depthWrite; } if (device.stateCache.dss.depthFunc !== dss.depthFunc) { @@ -1390,86 +1391,86 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // front - if ((device.stateCache.dss.isFrontStencilTest !== dss.isFrontStencilTest) || - (device.stateCache.dss.isBackStencilTest !== dss.isBackStencilTest)) { - if (dss.isFrontStencilTest || dss.isBackStencilTest) { + if ((device.stateCache.dss.stencilTestFront !== dss.stencilTestFront) || + (device.stateCache.dss.stencilTestBack !== dss.stencilTestBack)) { + if (dss.stencilTestFront || dss.stencilTestBack) { gl.enable(WebGLRenderingContext.STENCIL_TEST); } else { gl.disable(WebGLRenderingContext.STENCIL_TEST); } - device.stateCache.dss.isFrontStencilTest = dss.isFrontStencilTest; - device.stateCache.dss.isBackStencilTest = dss.isBackStencilTest; + device.stateCache.dss.stencilTestFront = dss.stencilTestFront; + device.stateCache.dss.stencilTestBack = dss.stencilTestBack; } - if ((device.stateCache.dss.frontStencilFunc !== dss.frontStencilFunc) || - (device.stateCache.dss.frontStencilRef !== dss.frontStencilRef) || - (device.stateCache.dss.frontStencilReadMask !== dss.frontStencilReadMask)) { + if ((device.stateCache.dss.stencilFuncFront !== dss.stencilFuncFront) || + (device.stateCache.dss.stencilRefFront !== dss.stencilRefFront) || + (device.stateCache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront)) { gl.stencilFuncSeparate( WebGLRenderingContext.FRONT, - WebGLCmpFuncs[dss.frontStencilFunc], - dss.frontStencilRef, - dss.frontStencilReadMask); + WebGLCmpFuncs[dss.stencilFuncFront], + dss.stencilRefFront, + dss.stencilReadMaskFront); - device.stateCache.dss.frontStencilFunc = dss.frontStencilFunc; - device.stateCache.dss.frontStencilRef = dss.frontStencilRef; - device.stateCache.dss.frontStencilReadMask = dss.frontStencilReadMask; + device.stateCache.dss.stencilFuncFront = dss.stencilFuncFront; + device.stateCache.dss.stencilRefFront = dss.stencilRefFront; + device.stateCache.dss.stencilReadMaskFront = dss.stencilReadMaskFront; } - if ((device.stateCache.dss.frontStencilFailOp !== dss.frontStencilFailOp) || - (device.stateCache.dss.frontStencilDepthFailOp !== dss.frontStencilDepthFailOp) || - (device.stateCache.dss.frontStencilPassOp !== dss.frontStencilPassOp)) { + if ((device.stateCache.dss.stencilFailOpFront !== dss.stencilFailOpFront) || + (device.stateCache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront) || + (device.stateCache.dss.stencilPassOpFront !== dss.stencilPassOpFront)) { gl.stencilOpSeparate( WebGLRenderingContext.FRONT, - WebGLStencilOps[dss.frontStencilFailOp], - WebGLStencilOps[dss.frontStencilDepthFailOp], - WebGLStencilOps[dss.frontStencilPassOp]); + WebGLStencilOps[dss.stencilFailOpFront], + WebGLStencilOps[dss.stencilZFailOpFront], + WebGLStencilOps[dss.stencilPassOpFront]); - device.stateCache.dss.frontStencilFailOp = dss.frontStencilFailOp; - device.stateCache.dss.frontStencilDepthFailOp = dss.frontStencilDepthFailOp; - device.stateCache.dss.frontStencilPassOp = dss.frontStencilPassOp; + device.stateCache.dss.stencilFailOpFront = dss.stencilFailOpFront; + device.stateCache.dss.stencilZFailOpFront = dss.stencilZFailOpFront; + device.stateCache.dss.stencilPassOpFront = dss.stencilPassOpFront; } - if (device.stateCache.dss.frontStencilWriteMask !== dss.frontStencilWriteMask) { - gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, dss.frontStencilWriteMask); - device.stateCache.dss.frontStencilWriteMask = dss.frontStencilWriteMask; + if (device.stateCache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) { + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, dss.stencilWriteMaskFront); + device.stateCache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront; } // back - if ((device.stateCache.dss.backStencilFunc !== dss.backStencilFunc) || - (device.stateCache.dss.backStencilRef !== dss.backStencilRef) || - (device.stateCache.dss.backStencilReadMask !== dss.backStencilReadMask)) { + if ((device.stateCache.dss.stencilFuncBack !== dss.stencilFuncBack) || + (device.stateCache.dss.stencilRefBack !== dss.stencilRefBack) || + (device.stateCache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack)) { gl.stencilFuncSeparate( WebGLRenderingContext.BACK, - WebGLCmpFuncs[dss.backStencilFunc], - dss.backStencilRef, - dss.backStencilReadMask); + WebGLCmpFuncs[dss.stencilFuncBack], + dss.stencilRefBack, + dss.stencilReadMaskBack); - device.stateCache.dss.backStencilFunc = dss.backStencilFunc; - device.stateCache.dss.backStencilRef = dss.backStencilRef; - device.stateCache.dss.backStencilReadMask = dss.backStencilReadMask; + device.stateCache.dss.stencilFuncBack = dss.stencilFuncBack; + device.stateCache.dss.stencilRefBack = dss.stencilRefBack; + device.stateCache.dss.stencilReadMaskBack = dss.stencilReadMaskBack; } - if ((device.stateCache.dss.backStencilFailOp !== dss.backStencilFailOp) || - (device.stateCache.dss.backStencilDepthFailOp !== dss.backStencilDepthFailOp) || - (device.stateCache.dss.backStencilPassOp !== dss.backStencilPassOp)) { + if ((device.stateCache.dss.stencilFailOpBack !== dss.stencilFailOpBack) || + (device.stateCache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack) || + (device.stateCache.dss.stencilPassOpBack !== dss.stencilPassOpBack)) { gl.stencilOpSeparate( WebGLRenderingContext.BACK, - WebGLStencilOps[dss.backStencilFailOp], - WebGLStencilOps[dss.backStencilDepthFailOp], - WebGLStencilOps[dss.backStencilPassOp]); + WebGLStencilOps[dss.stencilFailOpBack], + WebGLStencilOps[dss.stencilZFailOpBack], + WebGLStencilOps[dss.stencilPassOpBack]); - device.stateCache.dss.backStencilFailOp = dss.backStencilFailOp; - device.stateCache.dss.backStencilDepthFailOp = dss.backStencilDepthFailOp; - device.stateCache.dss.backStencilPassOp = dss.backStencilPassOp; + device.stateCache.dss.stencilFailOpBack = dss.stencilFailOpBack; + device.stateCache.dss.stencilZFailOpBack = dss.stencilZFailOpBack; + device.stateCache.dss.stencilPassOpBack = dss.stencilPassOpBack; } - if (device.stateCache.dss.backStencilWriteMask !== dss.backStencilWriteMask) { - gl.stencilMaskSeparate(WebGLRenderingContext.BACK, dss.backStencilWriteMask); - device.stateCache.dss.backStencilWriteMask = dss.backStencilWriteMask; + if (device.stateCache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) { + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, dss.stencilWriteMaskBack); + device.stateCache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack; } } // depth-stencil state @@ -1486,66 +1487,66 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG device.stateCache.bs.isA2C = bs.isA2C; } - if ((device.stateCache.bs.factor[0] !== bs.factor[0]) || - (device.stateCache.bs.factor[1] !== bs.factor[1]) || - (device.stateCache.bs.factor[2] !== bs.factor[2]) || - (device.stateCache.bs.factor[3] !== bs.factor[3])) { + if ((device.stateCache.bs.blendColor[0] !== bs.blendColor[0]) || + (device.stateCache.bs.blendColor[1] !== bs.blendColor[1]) || + (device.stateCache.bs.blendColor[2] !== bs.blendColor[2]) || + (device.stateCache.bs.blendColor[3] !== bs.blendColor[3])) { - gl.blendColor(bs.factor[0], bs.factor[1], bs.factor[2], bs.factor[3]); + gl.blendColor(bs.blendColor[0], bs.blendColor[1], bs.blendColor[2], bs.blendColor[3]); - device.stateCache.bs.factor[0] = bs.factor[0]; - device.stateCache.bs.factor[1] = bs.factor[1]; - device.stateCache.bs.factor[2] = bs.factor[2]; - device.stateCache.bs.factor[3] = bs.factor[3]; + device.stateCache.bs.blendColor[0] = bs.blendColor[0]; + device.stateCache.bs.blendColor[1] = bs.blendColor[1]; + device.stateCache.bs.blendColor[2] = bs.blendColor[2]; + device.stateCache.bs.blendColor[3] = bs.blendColor[3]; } let target0 = bs.targets[0]; let catchTarget0 = device.stateCache.bs.targets[0]; - if (catchTarget0.isBlend !== target0.isBlend) { - if (target0.isBlend) { + if (catchTarget0.blend !== target0.blend) { + if (target0.blend) { gl.enable(WebGLRenderingContext.BLEND); } else { gl.disable(WebGLRenderingContext.BLEND); } - catchTarget0.isBlend = target0.isBlend; + catchTarget0.blend = target0.blend; } - if ((catchTarget0.blendOp !== target0.blendOp) || - (catchTarget0.alphBlendOp !== target0.alphBlendOp)) { + if ((catchTarget0.blendEq !== target0.blendEq) || + (catchTarget0.blendAlphaEq !== target0.blendAlphaEq)) { - gl.blendEquationSeparate(WebGLBlendOps[target0.blendOp], WebGLBlendOps[target0.alphBlendOp]); + gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]); - catchTarget0.blendOp = target0.blendOp; - catchTarget0.alphBlendOp = target0.alphBlendOp; + catchTarget0.blendEq = target0.blendEq; + catchTarget0.blendAlphaEq = target0.blendAlphaEq; } - if ((catchTarget0.srcBlend !== target0.srcBlend) || - (catchTarget0.dstBlend !== target0.dstBlend) || - (catchTarget0.srcAlphaBlend !== target0.srcAlphaBlend) || - (catchTarget0.dstAlphaBlend !== target0.dstAlphaBlend)) { + if ((catchTarget0.blendSrc !== target0.blendSrc) || + (catchTarget0.blendDst !== target0.blendDst) || + (catchTarget0.blendSrcAlpha !== target0.blendSrcAlpha) || + (catchTarget0.blendDstAlpha !== target0.blendDstAlpha)) { gl.blendFuncSeparate( - WebGLBlendFactors[target0.srcBlend], - WebGLBlendFactors[target0.dstBlend], - WebGLBlendFactors[target0.srcAlphaBlend], - WebGLBlendFactors[target0.dstAlphaBlend]); + WebGLBlendFactors[target0.blendSrc], + WebGLBlendFactors[target0.blendDst], + WebGLBlendFactors[target0.blendSrcAlpha], + WebGLBlendFactors[target0.blendDstAlpha]); - catchTarget0.srcBlend = target0.srcBlend; - catchTarget0.dstBlend = target0.dstBlend; - catchTarget0.srcAlphaBlend = target0.srcAlphaBlend; - catchTarget0.dstAlphaBlend = target0.dstAlphaBlend; + catchTarget0.blendSrc = target0.blendSrc; + catchTarget0.blendDst = target0.blendDst; + catchTarget0.blendSrcAlpha = target0.blendSrcAlpha; + catchTarget0.blendDstAlpha = target0.blendDstAlpha; } - if (catchTarget0.colorWriteMask !== target0.colorWriteMask) { + if (catchTarget0.blendColorMask !== target0.blendColorMask) { gl.colorMask( - (target0.colorWriteMask & GFXColorMask.R) !== GFXColorMask.NONE, - (target0.colorWriteMask & GFXColorMask.G) !== GFXColorMask.NONE, - (target0.colorWriteMask & GFXColorMask.B) !== GFXColorMask.NONE, - (target0.colorWriteMask & GFXColorMask.A) !== GFXColorMask.NONE); + (target0.blendColorMask & GFXColorMask.R) !== GFXColorMask.NONE, + (target0.blendColorMask & GFXColorMask.G) !== GFXColorMask.NONE, + (target0.blendColorMask & GFXColorMask.B) !== GFXColorMask.NONE, + (target0.blendColorMask & GFXColorMask.A) !== GFXColorMask.NONE); - catchTarget0.colorWriteMask = target0.colorWriteMask; + catchTarget0.blendColorMask = target0.blendColorMask; } } // blend state } diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 4fc99c7b54..fbb02f7b7c 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -1,28 +1,27 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import EffectAsset from '../../3d/assets/effect-asset'; +import { EffectAsset, PropertyInfo, ShaderInfo, UniformInfo } from '../../3d/assets/effect-asset'; import { CCObject } from '../../core/data'; import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; -import enums from '../enums'; +import { GFXType } from '../../gfx/define'; import Texture2D from '../gfx/texture-2d'; import TextureCube from '../gfx/texture-cube'; import { Pass } from './pass'; import Technique from './technique'; const _typeMap = { - [enums.PARAM_INT]: 'Number', - [enums.PARAM_INT2]: Vec2, - [enums.PARAM_INT3]: Vec3, - [enums.PARAM_INT4]: Vec4, - [enums.PARAM_FLOAT]: 'Number', - [enums.PARAM_FLOAT2]: Vec2, - [enums.PARAM_FLOAT3]: Vec3, - [enums.PARAM_FLOAT4]: Vec4, - [enums.PARAM_COLOR3]: Color, - [enums.PARAM_COLOR4]: Color, - [enums.PARAM_MAT4]: Mat4, - [enums.PARAM_TEXTURE_2D]: Texture2D, - [enums.PARAM_TEXTURE_CUBE]: TextureCube, + [GFXType.INT]: 'Number', + [GFXType.INT2]: Vec2, + [GFXType.INT3]: Vec3, + [GFXType.INT4]: Vec4, + [GFXType.FLOAT]: 'Number', + [GFXType.FLOAT2]: Vec2, + [GFXType.FLOAT3]: Vec3, + [GFXType.FLOAT4]: Vec4, + [GFXType.COLOR4]: Color, + [GFXType.MAT4]: Mat4, + [GFXType.SAMPLER2D]: Texture2D, + [GFXType.SAMPLER_CUBE]: TextureCube, number: 'Number', boolean: 'Boolean', default: CCObject, @@ -33,180 +32,42 @@ const typeCheck = (value: any, type: number) => { switch (typeof value) { case 'object': return (value === null) || (value instanceof instanceType); case 'number': return instanceType === 'Number'; + case 'boolean': return instanceType === 'Boolean'; default: return false; } }; let _globalTechLod = 600; -const _ctorMap = { - ['Number']: (v?: number) => v || 0, - ['Boolean']: (v?: boolean) => v || false, - [Vec2]: (v?: number[]) => v ? new Vec2(v[0], v[1]) : new Vec2(), - [Vec3]: (v?: number[]) => v ? new Vec3(v[0], v[1], v[2]) : new Vec3(), - [Vec4]: (v?: number[]) => v ? new Vec4(v[0], v[1], v[2], v[3]) : new Vec4(), - [Color]: (v?: number[]) => v ? new Color(v[0] * 255, v[1] * 255, v[2] * 255, - (v[3] || 1) * 255) : new Color(), - [Mat4]: (v?: number[]) => v ? new Mat4( - v[0], v[1], v[2], v[3], - v[4], v[5], v[6], v[7], - v[8], v[9], v[10], v[11], - v[12], v[13], v[14], v[15] - ) : new Mat4(), - [Texture2D]: () => null, - [TextureCube]: () => null, - [CCObject]: () => null, -}; -const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; +type PropValue = number | boolean | Vec2 | Vec3 | Vec4 | Color | Mat4 | Texture2D | TextureCube | null; +interface PropertyMap { [name: string]: { type: number, value: PropValue }; } +interface DefineMap { [name: string]: number | boolean; } +interface DependencyMap { [name: string]: string; } -const getInvolvedPrograms = (effect: EffectAsset) => { - const programs: Programs = {}; - const lib = cc.game._renderer._programLib; - effect.techniques.forEach((tech) => { - tech.passes.forEach((pass) => { - programs[pass.program] = lib.getTemplate(pass.program); - }); - }); - return programs; -}; - -const parseProperties = (() => { - function genPropInfo(displayName: string, type: number, value: any) { - return { - type, - displayName, - instanceType: getInstanceType(type), - value: getInstanceCtor(type)(value), - }; - } - return (effect: EffectAsset, programs: Programs) => { - const props = {}; - // properties may be specified in the shader too - for (const p of Object.keys(programs)) { - programs[p].uniforms.forEach((prop) => { - if (!prop.property) { return; } - props[prop.name] = genPropInfo(prop.displayName, prop.type, prop.value); - }); - } - for (const prop of Object.keys(effect.properties)) { - const propInfo = effect.properties[prop]; - let uniformInfo; - // always try getting the type from shaders first - if (propInfo.tech !== undefined && propInfo.pass !== undefined) { - const pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program; - uniformInfo = programs[pname].uniforms.find((u) => u.name === prop); - } else { - for (const p of Object.keys(programs)) { - uniformInfo = programs[p].uniforms.find((u) => u.name === prop); - if (uniformInfo) { break; } - } - } - // the property is not defined in all the shaders used in techs - if (!uniformInfo) { - console.warn(`illegal property: ${prop}`); - continue; - } - // TODO: different param with same name for different passes - props[prop] = genPropInfo( - propInfo.displayName || uniformInfo.displayName, - propInfo.type || uniformInfo.type, - propInfo.value || uniformInfo.value); - } - return props; - }; -})(); - -const parseEffect = (effect: EffectAsset) => { - // techniques - const techNum = effect.techniques.length; - const programs = getInvolvedPrograms(effect); - const techniques = new Array(techNum); - let tech; - for (let j = 0; j < techNum; ++j) { - tech = effect.techniques[j]; - const passNum = tech.passes.length; - const passes = new Array(passNum); - for (let k = 0; k < passNum; ++k) { - const passInfo = tech.passes[k]; - passInfo.device = cc.game._renderContext; - passes[k] = Pass.create(passInfo); - } - techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); - } - // uniforms - const props = parseProperties(effect, programs); - const uniforms = {}; - for (const pn of Object.keys(programs)) { - programs[pn].uniforms.forEach((u) => { - const prop = props[u.name]; - uniforms[u.name] = { - type: prop ? prop.type : u.type, - value: prop ? prop.value : getInstanceCtor(u.type)(u.value), - }; - }); - } - - return new Effect(effect.name, techniques, programs, uniforms); -}; - -let parseForInspector = (effect: EffectAsset) => {}; - -if (CC_EDITOR) { - parseForInspector = (effect: EffectAsset) => { - const programs = getInvolvedPrograms(effect); - const props = parseProperties(effect, programs); - const defines = {}; - for (const pn of Object.keys(programs)) { - programs[pn].uniforms.forEach((u) => { - const prop = props[u.name]; - if (!prop) { return; } - prop.defines = u.defines; - }); - programs[pn].defines.forEach((define) => { - defines[define.name] = { - instanceType: getInstanceType(define.type), - value: getInstanceCtor(define.type)(), - defines: define.defines, - }; - }); - } - return { props, defines }; - }; -} - -interface PropertyMap { - [name: string]: { type: number, value: any }; -} -interface DefineMap { - [name: string]: number | boolean; -} -interface DependencyMap { - [define: string]: string; -} -interface ProgramInfo { - uniforms: Array< { name: string, type: string } >; - defines: Array< { name: string, type: string } >; - extensions: Array< { name: string, define: string } >; -} -interface Programs { - [name: string]: ProgramInfo; -} +interface ProgramMap { [name: string]: ShaderInfo; } class Effect { - public static parseEffect = parseEffect; - public static parseForInspector = parseForInspector; + public static parseEffect(effect: EffectAsset, programs: ProgramMap) { return new Effect(); } + public static parseForInspector(effect: EffectAsset) { return { props: {}, defines: {} }; } public static setGlobalLod(lod: number) { _globalTechLod = lod; } protected _name: string = ''; protected _techniques: Technique[] = []; protected _properties: PropertyMap = {}; - protected _programs: Programs = {}; protected _defines: DefineMap = {}; protected _dependencies: DependencyMap = {}; + protected _maxLOD: number = 0; protected _activeTechIdx: number = 0; + protected _programs: ProgramMap = {}; - constructor(name: string, techniques: Technique[], programs: Programs, properties: PropertyMap = {}, lod = -1) { + constructor( + name: string = '', + techniques: Technique[] = [new Technique()], + programs: ProgramMap = {}, + properties: PropertyMap = {}, + lod = -1 + ) { this._name = name; this._techniques = techniques; this._properties = properties; @@ -288,24 +149,153 @@ class Effect { const lod = this._maxLOD === -1 ? _globalTechLod : this._maxLOD; this._activeTechIdx = 0; for (let i = 0; i < this._techniques.length; i++) { - if (this._techniques[i]._lod <= lod) { + if (this._techniques[i].LOD <= lod) { this._activeTechIdx = i; break; } } - // defines this._defines = {}; this._techniques[this._activeTechIdx].passes.forEach((pass) => - this._programs[pass._programName].defines.forEach((def) => - this._defines[def.name] = getInstanceCtor(def.type)())); - + this._programs[pass.programName].defines.forEach((def) => + this._defines[def.name] = def.type === 'number' ? 0 : false)); // extensions this._dependencies = {}; - this._techniques[this._activeTechIdx].passes.forEach((pass) => this._programs[pass._programName].extensions + this._techniques[this._activeTechIdx].passes.forEach((pass) => this._programs[pass.programName].extensions .filter((ext) => ext.define).forEach((ext) => this._dependencies[ext.define] = ext.name)); } } +type DefaultValue = number | boolean | number[] | null; +const _ctorMap = { + Number: (v?: DefaultValue) => v || 0, + Boolean: (v?: DefaultValue) => v || false, + [Vec2]: (v?: DefaultValue) => Array.isArray(v) ? new Vec2(v[0], v[1]) : new Vec2(), + [Vec3]: (v?: DefaultValue) => Array.isArray(v) ? new Vec3(v[0], v[1], v[2]) : new Vec3(), + [Vec4]: (v?: DefaultValue) => Array.isArray(v) ? new Vec4(v[0], v[1], v[2], v[3]) : new Vec4(), + [Color]: (v?: DefaultValue) => Array.isArray(v) ? new Color(v[0] * 255, v[1] * 255, v[2] * 255, + (v[3] || 1) * 255) : new Color(), + [Mat4]: (v?: DefaultValue) => Array.isArray(v) ? new Mat4( + v[0], v[1], v[2], v[3], + v[4], v[5], v[6], v[7], + v[8], v[9], v[10], v[11], + v[12], v[13], v[14], v[15] + ) : new Mat4(), + [Texture2D]: () => null, + [TextureCube]: () => null, + [CCObject]: () => null, +}; +const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; + +const getInvolvedPrograms = (effect: EffectAsset) => { + const programs: ProgramMap = {}; + const lib = cc.game._programLib; + effect.techniques.forEach((tech) => { + tech.passes.forEach((pass) => { + programs[pass.program] = lib.getTemplate(pass.program); + }); + }); + return programs; +}; + +interface ExtractedPropInfo { + type: number; + instanceType: object | string; + value: number | boolean | object; + defines: string[]; + displayName?: string; +} +const parseProperties = (() => { + function genPropInfo(propInfo: PropertyInfo, uniformInfo: UniformInfo): ExtractedPropInfo { + const type = propInfo.type || uniformInfo.type; + return { + type, + instanceType: getInstanceType(type), + value: getInstanceCtor(type)(propInfo.value), + displayName: propInfo.displayName, + defines: uniformInfo.defines, + }; + } + return (effect: EffectAsset, programs: ProgramMap) => { + const props: { [name: string]: ExtractedPropInfo } = {}; + for (const prop of Object.keys(effect.properties)) { + const propInfo = effect.properties[prop]; + let uniformInfo: UniformInfo | undefined; + // always try getting the type from shaders first + if (propInfo.tech !== undefined && propInfo.pass !== undefined) { + const pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program; + uniformInfo = programs[pname].uniforms.find((u) => u.name === prop); + } else { + for (const p of Object.keys(programs)) { + uniformInfo = programs[p].uniforms.find((u) => u.name === prop); + if (uniformInfo) { break; } + } + } + // the property is not defined in all the shaders used in techs + if (!uniformInfo) { + console.warn(`illegal property: ${prop}`); + continue; + } + // TODO: different param with same name for different passes + props[prop] = genPropInfo(propInfo, uniformInfo); + } + return props; + }; +})(); + +Effect.parseEffect = (effect: EffectAsset) => { + // techniques + const techNum = effect.techniques.length; + const techniques = new Array(techNum); + const programs = getInvolvedPrograms(effect); + for (let j = 0; j < techNum; ++j) { + const tech = effect.techniques[j]; + const passNum = tech.passes.length; + const passes: Pass[] = new Array(passNum); + for (let k = 0; k < passNum; ++k) { + const passInfo = tech.passes[k]; + passInfo.device = cc.game._gfxDevice; + passInfo.bindingLayoutInfo = programs[passInfo.program].uniforms.map((u) => { + return { name: u.name, type: u.bindingType, binding: u.binding }; + }); + passes[k] = Pass.create(passInfo); + } + techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); + } + // uniforms + const props = parseProperties(effect, programs); + const uniforms = {}; + for (const pn of Object.keys(programs)) { + programs[pn].uniforms.forEach((u) => { + const prop = props[u.name]; + uniforms[u.name] = { + type: prop ? prop.type : u.type, + value: prop ? prop.value : getInstanceCtor(u.type)(), + }; + }); + } + + return new Effect(effect.name, techniques, programs, uniforms); +}; + +if (CC_EDITOR) { + Effect.parseForInspector = (effect: EffectAsset) => { + const programs = getInvolvedPrograms(effect); + const props = parseProperties(effect, programs); + const defines: { [name: string]: ExtractedPropInfo } = {}; + for (const pn of Object.keys(programs)) { + programs[pn].defines.forEach((define) => { + defines[define.name] = { + type: (define.type === 'number' ? GFXType.INT : GFXType.BOOL), + instanceType: getInstanceType(define.type), + value: getInstanceCtor(define.type)(), + defines: define.defines, + }; + }); + } + return { props, defines }; + }; +} + export default Effect; cc.Effect = Effect; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index dd7d8619aa..1782923d86 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,65 +1,70 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { GFXBindingLayoutInfo } from '../../gfx/binding-layout'; +import { GFXBinding } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXPrimitiveMode } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; -import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, GFXInputState, - GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; -import { GFXColorAttachment, GFXDepthStencilAttachment } from '../../gfx/render-pass'; +import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, + GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state'; import { GFXSampler } from '../../gfx/sampler'; import { PassStage } from './constants'; export interface PassInfo { - device: GFXDevice; - program: string; - primitive?: GFXPrimitiveMode; - stage?: PassStage; - inputState?: GFXInputState; - rasterizerState?: GFXRasterizerState; - depthStencilState?: GFXDepthStencilState; - blendState?: GFXBlendState; - blendTarget?: GFXBlendTarget; - bindingLayoutInfo?: GFXBindingLayoutInfo; - colorAttachment?: GFXColorAttachment; - depthStencilAttachment?: GFXDepthStencilAttachment; + // generated part + device: GFXDevice; + bindingLayoutInfo: GFXBinding[]; + program: string; + // effect-writer part + primitive?: GFXPrimitiveMode; + stage?: PassStage; + rasterizerState?: GFXRasterizerState; + depthStencilState?: GFXDepthStencilState; + blendState?: GFXBlendState; } export class Pass { - public static create(info: PassInfo) { - const pass = new Pass(); - const device = pass._device = info.device; - pass._programName = info.program; - pass._stage = info.stage || PassStage.DEFAULT; + public static create(info: PassInfo) { + const pass = new Pass(); + const device = pass._device = info.device; + pass._programName = info.program; + pass._stage = info.stage || PassStage.DEFAULT; - // pipeline state - const shader = device.createShader({ name: info.program, stages: [] }); - if (!shader) { console.error('create shader failed'); return; } - const bindingLayout = device.createBindingLayout(info.bindingLayoutInfo || { bindings: [] }); - if (!bindingLayout) { console.error('create binding layout failed'); return; } - const layout = device.createPipelineLayout({ layouts: [bindingLayout] }); - if (!layout) { console.error('create pipeline layout failed'); return; } - const renderPass = device.createRenderPass({ - colorAttachments: [Object.assign(new GFXColorAttachment(), info.colorAttachment)], - depthStencilAttachment: Object.assign(new GFXDepthStencilAttachment(), info.depthStencilAttachment), - }); - if (!renderPass) { console.error('create render pass failed'); return; } - const bs = Object.assign(new GFXBlendState(), info.blendState); - Object.assign(bs.targets[0], info.blendTarget); + // pipeline state + const shader = device.createShader({ name: info.program, stages: [] }); + if (!shader) { console.error('create shader failed'); return pass; } + const bindingLayout = device.createBindingLayout({ bindings: info.bindingLayoutInfo }); + if (!bindingLayout) { console.error('create binding layout failed'); return pass; } + const layout = device.createPipelineLayout({ layouts: [bindingLayout] }); + if (!layout) { console.error('create pipeline layout failed'); return pass; } + const renderPass = cc.director.root.pipeline.getRenderPass(pass._stage); + if (!renderPass) { console.error('create render pass failed'); return pass; } + const bs = new GFXBlendState(); + if (info.BlendState) { + const bsInfo = Object.assign({}, info.BlendState); + if (bsInfo.targets) { + bsInfo.targets.forEach((t, i) => Object.assign( + bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); + } + delete bsInfo.targets; + Object.assign(bs, bsInfo); + } - pass._pipelineState = device.createPipelineState({ - primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, - is: Object.assign(new GFXInputState(), info.inputState), - rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), - dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState), - bs, shader, layout, renderPass, - }); - } + pass._pipelineState = device.createPipelineState({ + primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, + rs: Object.assign(new GFXRasterizerState(), info.RasterizerState), + dss: Object.assign(new GFXDepthStencilState(), info.DepthStencilState), + is: new GFXInputState(), bs, + shader, layout, renderPass, + }); + return pass; + } - protected _device: GFXDevice | null = null; - protected _programName: string = ''; - protected _stage: PassStage = PassStage.DEFAULT; - protected _pipelineState: GFXPipelineState | null = null; - protected _buffers: GFXBuffer[] = []; - protected _samplers: GFXSampler[] = []; + get programName() { return this._programName; } + + protected _device: GFXDevice | null = null; + protected _programName: string = ''; + protected _stage: PassStage = PassStage.DEFAULT; + protected _pipelineState: GFXPipelineState | null = null; + protected _buffers: GFXBuffer[] = []; + protected _samplers: GFXSampler[] = []; } diff --git a/cocos/renderer/core/program-lib.js b/cocos/renderer/core/program-lib.js index 46923aad4f..ebb6207d1d 100644 --- a/cocos/renderer/core/program-lib.js +++ b/cocos/renderer/core/program-lib.js @@ -10,7 +10,7 @@ function _generateDefines(device, defs, deps) { let d = defs[def]; let result = typeof d === 'number' ? d : d ? 1 : 0; // fallback if extension dependency not supported - if (result && deps[def] && !device.ext(deps[def])) { + if (result && deps[def] && !device[deps[def]]) { console.warn(`${deps[def]} not supported on this platform, disabled ${def}`); result = 0; } diff --git a/cocos/renderer/core/technique.ts b/cocos/renderer/core/technique.ts index 1b0a2baf81..e119e4b0a9 100644 --- a/cocos/renderer/core/technique.ts +++ b/cocos/renderer/core/technique.ts @@ -5,29 +5,33 @@ import { Pass } from './pass'; let _genID = 0; export default class Technique { - protected _id: number = -1; - protected _renderQueue: number = RenderQueue.OPAQUE; - protected _priority: number = 0; - protected _lod: number = -1; - protected _passes: Pass[] = []; + protected _id: number = -1; + protected _renderQueue: number = RenderQueue.OPAQUE; + protected _priority: number = 0; + protected _lod: number = -1; + protected _passes: Pass[] = []; - constructor(renderQueue = RenderQueue.OPAQUE, priority = 0, lod = -1, passes = []) { - this._id = _genID++; - this._renderQueue = renderQueue; - this._priority = priority; - this._lod = lod; - this._passes = passes; - } + constructor(renderQueue = RenderQueue.OPAQUE, priority = 0, lod = -1, passes: Pass[] = []) { + this._id = _genID++; + this._renderQueue = renderQueue; + this._priority = priority; + this._lod = lod; + this._passes = passes; + } - public setRenderQueue(renderQueue: number) { - this._renderQueue = renderQueue; - } + public setRenderQueue(renderQueue: number) { + this._renderQueue = renderQueue; + } - get renderQueue() { - return this._renderQueue; - } + get LOD() { + return this._lod; + } - get passes() { - return this._passes; - } + get renderQueue() { + return this._renderQueue; + } + + get passes() { + return this._passes; + } } From e1cc6d91d4d224c9ddb9860876db3c15f6f973d4 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 4 Jan 2019 01:03:52 +0800 Subject: [PATCH 027/267] fix gfx bugs and complete texture loading --- cocos/gfx/binding-layout.ts | 3 +- cocos/gfx/command-buffer.ts | 30 +- cocos/gfx/define.ts | 50 ++-- cocos/gfx/device.ts | 5 + cocos/gfx/sampler.ts | 2 +- cocos/gfx/shader.ts | 27 +- cocos/gfx/webgl/webgl-binding-layout.ts | 13 +- cocos/gfx/webgl/webgl-command-buffer.ts | 6 +- cocos/gfx/webgl/webgl-commands.ts | 368 +++++++++++++----------- cocos/gfx/webgl/webgl-device.ts | 160 +++++++---- cocos/gfx/webgl/webgl-state-cache.ts | 4 +- cocos/pipeline/forward/test-stage.ts | 145 +++++++++- playground/simple.html | 83 +++--- 13 files changed, 563 insertions(+), 333 deletions(-) diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index f09d4d591b..f49d35927a 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -30,7 +30,8 @@ export abstract class GFXBindingLayout { } public abstract initialize(info : GFXBindingLayoutInfo) : boolean; - public abstract destroy() : void; + public abstract destroy(); + public abstract update(); public bindBuffer(binding: number, buffer: GFXBuffer) { for (let i = 0; i < this._bindingUnits.length; ++i) { diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index fd50e99947..c131262d9d 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -9,36 +9,36 @@ import { GFXFramebuffer } from './framebuffer'; import { GFXColor, GFXRect, GFXCommandBufferType, GFXBufferTextureCopy, GFXTextureLayout } from './define'; export interface GFXCommandBufferInfo { - allocator : GFXCommandAllocator; - type : GFXCommandBufferType; + allocator: GFXCommandAllocator; + type: GFXCommandBufferType; }; export abstract class GFXCommandBuffer { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXCommandBufferInfo) : boolean; + public abstract initialize(info: GFXCommandBufferInfo): boolean; public abstract destroy(); public abstract begin(); public abstract end(); - public abstract beginRenderPass(framebuffer : GFXFramebuffer, renderArea : GFXRect, clearColors : GFXColor[], clearDepth: number, clearStencil : number); + public abstract beginRenderPass(framebuffer: GFXFramebuffer, renderArea: GFXRect, clearColors: GFXColor[], clearDepth: number, clearStencil: number); public abstract endRenderPass(); - public abstract bindPipelineState(pipelineState : GFXPipelineState); - public abstract bindBindingLayout(bindingLayout : GFXBindingLayout); - public abstract bindInputAssembler(inputAssembler : GFXInputAssembler); - 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[]); - public abstract execute(cmdBuffs : GFXCommandBuffer[]); + public abstract bindPipelineState(pipelineState: GFXPipelineState); + public abstract bindBindingLayout(bindingLayout: GFXBindingLayout); + public abstract bindInputAssembler(inputAssembler: GFXInputAssembler); + 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[]); + public abstract execute(cmdBuffs: GFXCommandBuffer[]); public get type(): number { return this._type; } - protected _device : GFXDevice; - protected _allocator : GFXCommandAllocator | null = null; - protected _type : GFXCommandBufferType = GFXCommandBufferType.PRIMARY; + protected _device: GFXDevice; + protected _allocator: GFXCommandAllocator | null = null; + protected _type: GFXCommandBufferType = GFXCommandBufferType.PRIMARY; }; diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 68de6cba03..cbb9bcfa31 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -447,28 +447,40 @@ export interface GFXColor { a: number; } -export interface GFXTextureSubres { - baseMipLevel: number; - levelCount: number; - baseArrayLayer: number; - layerCount: number; +export interface GFXOffset { + x: number; + y: number; + z: number; } -export interface GFXTextureCopy { - srcSubres: GFXTextureSubres; - srcOffset: number[]; - dstSubres: GFXTextureSubres; - dstOffset: number[]; - extent: number[]; +export interface GFXExtent { + width: number; + height: number; + depth: number; } -export interface GFXBufferTextureCopy { - buffOffset: number; - buffStride: number; - buffTexHeight: number; - texOffset: number[]; - texExtent: number[]; - texSubres: GFXTextureSubres; +export class GFXTextureSubres { + baseMipLevel: number = 0; + levelCount: number = 1; + baseArrayLayer: number = 0; + layerCount: number = 1; +} + +export class GFXTextureCopy { + srcSubres: GFXTextureSubres = new GFXTextureSubres; + srcOffset: GFXOffset = { x: 0, y: 0, z: 0 }; + dstSubres: GFXTextureSubres = new GFXTextureSubres; + dstOffset: GFXOffset = { x: 0, y: 0, z: 0 }; + extent: GFXExtent = { width: 0, height: 0, depth: 0 }; +} + +export class GFXBufferTextureCopy { + buffOffset: number = 0; + buffStride: number = 0; + buffTexHeight: number = 0; + texOffset: GFXOffset = { x: 0, y: 0, z: 0 }; + texExtent: GFXExtent = { width: 0, height: 0, depth: 0 }; + texSubres: GFXTextureSubres = new GFXTextureSubres; } export interface GFXFormatInfo { @@ -695,7 +707,7 @@ export function GFXGetTypeSize(type: GFXType): number { } } -export function GFXGetAttributeBinding(name: string) : number { +export function GFXGetAttributeBinding(name: string): number { if (name === GFX_ATTRIBUTE_POSITION) { return 6; } else if (name === GFX_ATTRIBUTE_COLOR) { diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index d6541c632b..38c9da9bad 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -44,6 +44,10 @@ export abstract class GFXDevice { public abstract createWindow(info: GFXWindowInfo) : GFXWindow | null; public abstract present(); + public get canvas(): HTMLCanvasElement { + return this._canvas; + } + public get queue(): GFXQueue { return this._queue; } @@ -92,6 +96,7 @@ export abstract class GFXDevice { return this._stencilBits; } + protected _canvas: HTMLCanvasElement | null = null; protected _deviceName : string = ""; protected _renderer : string = ""; protected _vendor : string = ""; diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index 994c6ea4e0..c7f8fc38d4 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -21,7 +21,7 @@ export class GFXSamplerState { name : string = ""; minFilter : GFXFilter = GFXFilter.LINEAR; magFilter : GFXFilter = GFXFilter.LINEAR; - mipFilter : GFXFilter = GFXFilter.LINEAR; + mipFilter : GFXFilter = GFXFilter.NONE; addressU : GFXAddress = GFXAddress.WRAP; addressV : GFXAddress = GFXAddress.WRAP; addressW : GFXAddress = GFXAddress.WRAP; diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index 356c8f0dba..764ebfb6dc 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -1,6 +1,5 @@ import { GFXDevice } from './device'; import { GFXType, GFXShaderType } from './define'; -import { GFXInputAttribute } from './input-assembler'; export interface GFXShaderMacro { macro: string; @@ -13,24 +12,24 @@ export interface GFXShaderStage { macros?: GFXShaderMacro[]; }; -export interface GFXUniform { - name: string; - type: GFXType; - count: number; +export class GFXUniform { + name: string = ""; + type: GFXType = GFXType.UNKNOWN; + count: number = 1; }; -export interface GFXUniformBlock { - binding: number; - name: string; +export class GFXUniformBlock { + binding: number = -1; + name: string = ""; //instance : string; - uniforms: GFXUniform[]; + uniforms: GFXUniform[] = []; }; -export interface GFXUniformSampler { - binding: number; - name: string; - type: GFXType; - count: number; +export class GFXUniformSampler { + binding: number = -1; + name: string = ""; + type: GFXType = GFXType.UNKNOWN; + count: number = 1; }; export interface GFXShaderInfo { diff --git a/cocos/gfx/webgl/webgl-binding-layout.ts b/cocos/gfx/webgl/webgl-binding-layout.ts index 9e67558ca8..76343d2154 100644 --- a/cocos/gfx/webgl/webgl-binding-layout.ts +++ b/cocos/gfx/webgl/webgl-binding-layout.ts @@ -14,10 +14,14 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { this._bindingUnits = new Array(info.bindings.length); for (let i = 0; i < info.bindings.length; ++i) { let binding = info.bindings[i]; - let bindingUnit = this._bindingUnits[i]; - bindingUnit.binding = binding.binding; - bindingUnit.type = binding.type; - bindingUnit.name = binding.name; + this._bindingUnits[i] = { + binding: binding.binding, + type: binding.type, + name: binding.name, + buffer: null, + texView: null, + sampler: null, + }; } this._gpuBindingLayout = this.webGLDevice.emitCmdCreateGPUBindingLayout(info); @@ -35,7 +39,6 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { public update() { if (this._gpuBindingLayout) { this.webGLDevice.emitCmdUpdateGPUBindingLayout(this._gpuBindingLayout, this._bindingUnits); - this._gpuBindingLayout = null; } } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 09746d9d34..73397df6a1 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,7 +1,7 @@ import { GFXDevice } from '../device'; import { GFXCommandBuffer, GFXCommandBufferInfo } from '../command-buffer'; import { GFXBuffer } from '../buffer'; -import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; +import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture, WebGLGFXBufferTextureCopy } from './webgl-commands'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGFXBuffer } from './webgl-buffer'; @@ -116,14 +116,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset : number) { + public updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset?: number) { let gpuBuffer = (buffer).gpuBuffer; if(gpuBuffer) { let cmd = (this._allocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { cmd.gpuBuffer = gpuBuffer; cmd.buffer = data; - cmd.offset = offset; + cmd.offset = (offset !== undefined? offset : 0); this.cmdPackage.updateBufferCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 3402c4c3eb..f94e8e096e 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,6 +1,6 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXGetAttributeBinding } from "../define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXGetAttributeBinding, GFXTextureSubres } from "../define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; @@ -329,8 +329,8 @@ export enum WebGLCmd { BEGIN_RENDER_PASS, END_RENDER_PASS, BIND_PIPELINE_STATE, - BIND_INPUT_ASSEMBLER, BIND_BINDING_LAYOUT, + BIND_INPUT_ASSEMBLER, DRAW, UPDATE_BUFFER, COPY_BUFFER_TO_TEXTURE, @@ -413,6 +413,22 @@ export class WebGLCmdUpdateBuffer extends WebGLCmdObject { } }; +export class WebGLGFXTextureSubres { + baseMipLevel: number = 0; + levelCount: number = 1; + baseArrayLayer: number = 0; + layerCount: number = 1; +} + +export class WebGLGFXBufferTextureCopy { + buffOffset: number = 0; + buffStride: number = 0; + buffTexHeight: number = 0; + texOffset: number[] = [0, 0, 0]; + texExtent: number[] = [0, 0, 0]; + texSubres: WebGLGFXTextureSubres = new WebGLGFXTextureSubres; +} + export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { gpuBuffer: WebGLGPUBuffer | null = null; @@ -851,29 +867,29 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG gpuShader.glInputs = new Array(activeAttribCount); for (let i = 0; i < activeAttribCount; ++i) { - let info = gl.getActiveAttrib(gpuShader.glProgram, i); - if (info) { + let attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i); + if (attribInfo) { let varName: string; - let nameOffset = info.name.indexOf('['); + let nameOffset = attribInfo.name.indexOf('['); if (nameOffset !== -1) { - varName = info.name.substr(0, nameOffset); + varName = attribInfo.name.substr(0, nameOffset); } else { - varName = info.name; + varName = attribInfo.name; } let glLoc = gl.getAttribLocation(gpuShader.glProgram, varName); - let type = WebGLTypeToGFXType(info.type); - let stride = WebGLGetTypeSize(info.type); + let type = WebGLTypeToGFXType(attribInfo.type); + let stride = WebGLGetTypeSize(attribInfo.type); gpuShader.glInputs[i] = { binding: glLoc, name: varName, type: type, stride: stride, - count: info.size, - size: stride * info.size, + count: attribInfo.size, + size: stride * attribInfo.size, - glType: info.type, + glType: attribInfo.type, glLoc: glLoc, }; } @@ -892,17 +908,25 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG for (let u = 0; u < block.uniforms.length; ++u) { let uniform = block.uniforms[u]; - let glUniform = glBlock.glUniforms[u]; + let glType = GFXTypeToWebGLType(uniform.type); + let stride = WebGLGetTypeSize(glType); + let size = stride * uniform.count; - glUniform.name = uniform.name; - glUniform.type = uniform.type; - glUniform.glType = GFXTypeToWebGLType(glUniform.type); - glUniform.stride = WebGLGetTypeSize(glUniform.glType); - glUniform.count = uniform.count; - glUniform.size = glUniform.stride * uniform.count; - glUniform.offset = glBlock.size; + glBlock.glUniforms[u] = { + binding: -1, + name: uniform.name, + type: uniform.type, + stride: stride, + count: uniform.count, + size: size, + offset: glBlock.size, - glBlock.size += glUniform.size; + glType: glType, + glLoc: -1, + bufferView: null, + } + + glBlock.size += size; } glBlock.buffer = new ArrayBuffer(glBlock.size); @@ -938,11 +962,14 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG for (let i = 0; i < gpuShader.samplers.length; ++i) { let sampler = gpuShader.samplers[i]; - let glSampler = gpuShader.glSamplers[i]; - glSampler.binding = sampler.binding; - glSampler.name = sampler.name; - glSampler.type = sampler.type; - glSampler.glType = GFXTypeToWebGLType(glSampler.type); + gpuShader.glSamplers[i] = { + binding: sampler.binding, + name: sampler.name, + type: sampler.type, + units: [], + glType: GFXTypeToWebGLType(sampler.type), + glLoc: -1, + } } } @@ -951,22 +978,20 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG let unitIdx = 0; for (let i = 0; i < activeUniformCount; ++i) { - let info = gl.getActiveUniform(gpuShader.glProgram, i); - if (info) { - let glLoc = gl.getUniformLocation(gpuShader.glProgram, info.name); + let uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); + if (uniformInfo) { + let glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); if (glLoc) { let varName: string; - let nameOffset = info.name.indexOf('['); + let nameOffset = uniformInfo.name.indexOf('['); if (nameOffset !== -1) { - varName = info.name.substr(0, nameOffset); + varName = uniformInfo.name.substr(0, nameOffset); } else { - varName = info.name; + varName = uniformInfo.name; } - let type = WebGLTypeToGFXType(info.type); - - let isSampler = (type === WebGLRenderingContext.SAMPLER_2D) || - (type === WebGLRenderingContext.SAMPLER_CUBE); + let isSampler = (uniformInfo.type === WebGLRenderingContext.SAMPLER_2D) || + (uniformInfo.type === WebGLRenderingContext.SAMPLER_CUBE); if (!isSampler) { //let stride = WebGLGetTypeSize(info.type); @@ -992,16 +1017,15 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG for (let s = 0; s < gpuShader.glSamplers.length; ++s) { let glSampler = gpuShader.glSamplers[s]; if (glSampler.name === varName) { - //let varSize = stride * info.size; + //let varSize = stride * uniformInfo.size; - glSampler.units = new Array(info.size); - for (let t = 0; t < glSampler.units.length; ++t) { - glSampler.units[t] = unitIdx + t; + for (let t = 0; t < uniformInfo.size; ++t) { + glSampler.units.push(unitIdx + t); } glSampler.glLoc = glLoc; - unitIdx += info.size; + unitIdx += uniformInfo.size; break; } @@ -1044,7 +1068,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; let glType = GFXFormatToWebGLType(attrib.format, device); - let size = WebGLGetTypeSize(glType); + let size = GFXFormatInfos[attrib.format].size; let glLoc = -1; if (attrib.binding) { @@ -1115,60 +1139,56 @@ export function WebGLCmdFuncDestroyInputAssembler(device: WebGLGFXDevice, gpuInp export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { let gl = device.gl; - - let beginRenderPassCmdIdx = 0; - let bindPipelineStateCmdIdx = 0; - let bindBindingLayoutCmdIdx = 0; - let bindInputAssemblerCmdIdx = 0; - let drawCmdIdx = 0; - let updateBufferCmdIdx = 0; - let copyBufferToTextureCmdIdx = 0; + let cmdIds = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 let gpuShader: WebGLGPUShader | null = null; let gpuInputAssembler: WebGLGPUInputAssembler | null = null; let glPrimitive = WebGLRenderingContext.TRIANGLES; for (let i = 0; i < cmdPackage.cmds.length; ++i) { + let cmd = cmdPackage.cmds[i]; + let cmdId = cmdIds[cmd]++; + switch (cmdPackage.cmds[i]) { case WebGLCmd.BEGIN_RENDER_PASS: { - let cmd = cmdPackage.beginRenderPassCmds[beginRenderPassCmdIdx++]; + let cmd0 = cmdPackage.beginRenderPassCmds[cmdId]; let clears: GLbitfield = 0; - if (cmd.gpuFramebuffer) { - if (device.stateCache.glFramebuffer !== cmd.gpuFramebuffer.glFramebuffer) { - let glFBO = (cmd.gpuFramebuffer.glFramebuffer !== 0? cmd.gpuFramebuffer.glFramebuffer : null); + if (cmd0.gpuFramebuffer) { + if (device.stateCache.glFramebuffer !== cmd0.gpuFramebuffer.glFramebuffer) { + let glFBO = (cmd0.gpuFramebuffer.glFramebuffer !== 0? cmd0.gpuFramebuffer.glFramebuffer : null); gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, glFBO); - device.stateCache.glFramebuffer = cmd.gpuFramebuffer.glFramebuffer; + device.stateCache.glFramebuffer = cmd0.gpuFramebuffer.glFramebuffer; } - if (device.stateCache.viewport.left !== cmd.renderArea.left || - device.stateCache.viewport.top !== cmd.renderArea.top || - device.stateCache.viewport.width !== cmd.renderArea.width || - device.stateCache.viewport.height !== cmd.renderArea.height) { + if (device.stateCache.viewport.left !== cmd0.renderArea.left || + device.stateCache.viewport.top !== cmd0.renderArea.top || + device.stateCache.viewport.width !== cmd0.renderArea.width || + device.stateCache.viewport.height !== cmd0.renderArea.height) { - gl.viewport(cmd.renderArea.left, cmd.renderArea.top, cmd.renderArea.width, cmd.renderArea.height); + gl.viewport(cmd0.renderArea.left, cmd0.renderArea.top, cmd0.renderArea.width, cmd0.renderArea.height); - device.stateCache.viewport.left = cmd.renderArea.left; - device.stateCache.viewport.top = cmd.renderArea.top; - device.stateCache.viewport.width = cmd.renderArea.width; - device.stateCache.viewport.height = cmd.renderArea.height; + device.stateCache.viewport.left = cmd0.renderArea.left; + device.stateCache.viewport.top = cmd0.renderArea.top; + device.stateCache.viewport.width = cmd0.renderArea.width; + device.stateCache.viewport.height = cmd0.renderArea.height; } - if (device.stateCache.scissorRect.left !== cmd.renderArea.left || - device.stateCache.scissorRect.top !== cmd.renderArea.top || - device.stateCache.scissorRect.width !== cmd.renderArea.width || - device.stateCache.scissorRect.height !== cmd.renderArea.height) { + if (device.stateCache.scissorRect.left !== cmd0.renderArea.left || + device.stateCache.scissorRect.top !== cmd0.renderArea.top || + device.stateCache.scissorRect.width !== cmd0.renderArea.width || + device.stateCache.scissorRect.height !== cmd0.renderArea.height) { - gl.scissor(cmd.renderArea.left, cmd.renderArea.top, cmd.renderArea.width, cmd.renderArea.height); + gl.scissor(cmd0.renderArea.left, cmd0.renderArea.top, cmd0.renderArea.width, cmd0.renderArea.height); - device.stateCache.scissorRect.left = cmd.renderArea.left; - device.stateCache.scissorRect.top = cmd.renderArea.top; - device.stateCache.scissorRect.width = cmd.renderArea.width; - device.stateCache.scissorRect.height = cmd.renderArea.height; + device.stateCache.scissorRect.left = cmd0.renderArea.left; + device.stateCache.scissorRect.top = cmd0.renderArea.top; + device.stateCache.scissorRect.width = cmd0.renderArea.width; + device.stateCache.scissorRect.height = cmd0.renderArea.height; } - let curGPURenderPass = cmd.gpuFramebuffer.gpuRenderPass; + let curGPURenderPass = cmd0.gpuFramebuffer.gpuRenderPass; let invalidateAttachments: GLenum[] = [0, 0, 0, 0]; let numInvalidAttach = 0; @@ -1185,7 +1205,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.colorMask(true, true, true, true); } - let clearColor = cmd.clearColors[0]; + let clearColor = cmd0.clearColors[0]; gl.clearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); clears |= WebGLRenderingContext.COLOR_BUFFER_BIT; @@ -1212,7 +1232,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.depthMask(true); } - gl.clearDepth(cmd.clearDepth); + gl.clearDepth(cmd0.clearDepth); clears |= WebGLRenderingContext.DEPTH_BUFFER_BIT; @@ -1239,7 +1259,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0xFFFFFFFF); } - gl.clearStencil(cmd.clearStencil); + gl.clearStencil(cmd0.clearStencil); clears |= WebGLRenderingContext.STENCIL_BUFFER_BIT; break; @@ -1303,24 +1323,24 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLCmd.BIND_PIPELINE_STATE: { - let cmd = cmdPackage.bindPipelineStateCmds[bindPipelineStateCmdIdx++]; - if (cmd.gpuPipelineState) { + let cmd2 = cmdPackage.bindPipelineStateCmds[cmdId]; + if (cmd2.gpuPipelineState) { - glPrimitive = cmd.gpuPipelineState.glPrimitive; + glPrimitive = cmd2.gpuPipelineState.glPrimitive; - if (cmd.gpuPipelineState.gpuShader) { + if (cmd2.gpuPipelineState.gpuShader) { - let glProgram = cmd.gpuPipelineState.gpuShader.glProgram; + let glProgram = cmd2.gpuPipelineState.gpuShader.glProgram; if (device.stateCache.glProgram !== glProgram) { gl.useProgram(glProgram); device.stateCache.glProgram = glProgram; } - gpuShader = cmd.gpuPipelineState.gpuShader; + gpuShader = cmd2.gpuPipelineState.gpuShader; } // rasterizer state - let rs = cmd.gpuPipelineState.rs; + let rs = cmd2.gpuPipelineState.rs; if (rs) { if (device.stateCache.rs.cullMode !== rs.cullMode) { @@ -1367,7 +1387,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // rasterizater state // depth-stencil state - let dss = cmd.gpuPipelineState.dss; + let dss = cmd2.gpuPipelineState.dss; if (dss) { if (device.stateCache.dss.isDepthTest !== dss.isDepthTest) { @@ -1474,7 +1494,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // depth-stencil state // blend state - let bs = cmd.gpuPipelineState.bs; + let bs = cmd2.gpuPipelineState.bs; if (bs) { if (device.stateCache.bs.isA2C !== bs.isA2C) { @@ -1554,10 +1574,10 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLCmd.BIND_BINDING_LAYOUT: { - let cmd = cmdPackage.bindBindingLayoutCmds[bindBindingLayoutCmdIdx++]; - if (cmd.gpuBindingLayout && gpuShader) { - for (let n = 0; n < cmd.gpuBindingLayout.gpuBindings.length; ++n) { - let gpuBinding = cmd.gpuBindingLayout.gpuBindings[n]; + let cmd3 = cmdPackage.bindBindingLayoutCmds[cmdId]; + if (cmd3.gpuBindingLayout && gpuShader) { + for (let n = 0; n < cmd3.gpuBindingLayout.gpuBindings.length; ++n) { + let gpuBinding = cmd3.gpuBindingLayout.gpuBindings[n]; switch (gpuBinding.type) { case GFXBindingType.UNIFORM_BUFFER: { @@ -1766,7 +1786,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case GFXBindingType.SAMPLER: { - if (gpuBinding.gpuSampler && gpuBinding.gpuTexView && gpuBinding.gpuTexView.gpuTexture) { + if (gpuBinding.gpuSampler && gpuBinding.gpuTexView) { let glSampler: WebGLGPUUniformSampler | null = null; @@ -1784,7 +1804,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let texUnit = glSampler.units[u]; if (device.stateCache.texUnit !== texUnit) { - gl.activeTexture(WebGLRenderingContext.TEXTURE0 + u); + gl.activeTexture(WebGLRenderingContext.TEXTURE0 + texUnit); device.stateCache.texUnit == texUnit; } @@ -1856,14 +1876,14 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLCmd.BIND_INPUT_ASSEMBLER: { - let cmd = cmdPackage.bindInputAssemblerCmds[bindInputAssemblerCmdIdx++]; - gpuInputAssembler = cmd.gpuInputAssembler; + let cmd4 = cmdPackage.bindInputAssemblerCmds[cmdId]; + gpuInputAssembler = cmd4.gpuInputAssembler; break; } case WebGLCmd.DRAW: { - if (gpuInputAssembler && gpuShader) { - let cmd = cmdPackage.drawCmds[drawCmdIdx++]; + let cmd5: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; + if (gpuInputAssembler && gpuShader) { for (let a = 0; a < device.maxVertexAttributes; ++a) { device.stateCache.glCurrentAttribLocs[a] = false; } @@ -1887,7 +1907,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let c = 0; c < glAttrib.componentCount; ++c) { let glLoc = glInput.glLoc + c; - let offset = glAttrib.offset + glAttrib.size * c; + let attribOffset = glAttrib.offset + glAttrib.size * c; if (!device.stateCache.glEnabledAttribLocs[glLoc] && glLoc >= 0) { gl.enableVertexAttribArray(glLoc); @@ -1895,12 +1915,12 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } device.stateCache.glCurrentAttribLocs[glLoc] = true; - gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, offset); + gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, attribOffset); } } } // if - if (gpuInputAssembler.gpuIndexBuffer && cmd.indexCount > 0) { + if (gpuInputAssembler.gpuIndexBuffer && cmd5.indexCount > 0) { let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { @@ -1908,10 +1928,10 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - let offset = cmd.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, cmd.indexCount, gpuInputAssembler.glIndexType, offset); + let offset = cmd5.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, cmd5.indexCount, gpuInputAssembler.glIndexType, offset); } else { - gl.drawArrays(glPrimitive, cmd.firstVertex, cmd.vertexCount); + gl.drawArrays(glPrimitive, cmd5.firstVertex, cmd5.vertexCount); } for (let a = 0; a < device.maxVertexAttributes; ++a) { @@ -1924,63 +1944,70 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLCmd.UPDATE_BUFFER: { - let cmd = cmdPackage.updateBufferCmds[updateBufferCmdIdx++]; - if (cmd.gpuBuffer) { - switch (cmd.gpuBuffer.glTarget) { + let cmd6 = cmdPackage.updateBufferCmds[cmdId]; + if (cmd6.gpuBuffer) { + + if(cmd6.buffer && cmd6.gpuBuffer.bufferView) { + cmd6.gpuBuffer.bufferView.set(new Uint8Array(cmd6.buffer), cmd6.offset); + } + + switch (cmd6.gpuBuffer.glTarget) { case WebGLRenderingContext.ARRAY_BUFFER: { - if (device.stateCache.glArrayBuffer !== cmd.gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, cmd.gpuBuffer.glBuffer); - device.stateCache.glArrayBuffer = cmd.gpuBuffer.glBuffer; + if (device.stateCache.glArrayBuffer !== cmd6.gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, cmd6.gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = cmd6.gpuBuffer.glBuffer; + } + + if (cmd6.buffer) { + gl.bufferSubData(cmd6.gpuBuffer.glTarget, cmd6.offset, cmd6.buffer); } break; } case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { - if (device.stateCache.glElementArrayBuffer !== cmd.gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, cmd.gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = cmd.gpuBuffer.glBuffer; + if (device.stateCache.glElementArrayBuffer !== cmd6.gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, cmd6.gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = cmd6.gpuBuffer.glBuffer; + } + + if (cmd6.buffer) { + gl.bufferSubData(cmd6.gpuBuffer.glTarget, cmd6.offset, cmd6.buffer); } break; } - default: { - console.error("Unsupported GFXBufferType, update buffer failed."); - continue; - } - } - - if (cmd.buffer) { - gl.bufferSubData(cmd.gpuBuffer.glTarget, cmd.offset, cmd.buffer); + default: ; } } break; } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { - let cmd = cmdPackage.copyBufferToTextureCmds[copyBufferToTextureCmdIdx++]; - if (cmd.gpuBuffer && cmd.gpuBuffer.bufferView && cmd.gpuTexture) { - switch (cmd.gpuTexture.glTarget) { + let cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; + if (cmd7.gpuBuffer && cmd7.gpuBuffer.bufferView && cmd7.gpuTexture) { + + switch (cmd7.gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { - let texUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; - if (texUnit.glTexture !== cmd.gpuTexture.glTexture) { - gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, cmd.gpuTexture.glTexture); - texUnit.glTexture = cmd.gpuTexture.glTexture; + let glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== cmd7.gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, cmd7.gpuTexture.glTexture); + glTexUnit.glTexture = cmd7.gpuTexture.glTexture; } - let isCompressed = GFXFormatInfos[cmd.gpuTexture.format].isCompressed; + let isCompressed = GFXFormatInfos[cmd7.gpuTexture.format].isCompressed; if (!isCompressed) { - for (let r = 0; r < cmd.regions.length; ++r) { - let region = cmd.regions[r]; - let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + for (let r = 0; r < cmd7.regions.length; ++r) { + let region = cmd7.regions[r]; + let buffOffset = region.buffOffset; + region.buffTexHeight * region.buffStride; - let w = region.texExtent[0]; - let h = region.texExtent[1]; + let w = region.texExtent.width; + let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); + let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); + let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, - region.texOffset[0], region.texOffset[1], w, h, - cmd.gpuTexture.glFormat, cmd.gpuTexture.glType, data); + region.texOffset.x, region.texOffset.y, w, h, + cmd7.gpuTexture.glFormat, cmd7.gpuTexture.glType, data); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -1988,20 +2015,20 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } } } else { - for (let r = 0; r < cmd.regions.length; ++r) { - let region = cmd.regions[r]; + for (let r = 0; r < cmd7.regions.length; ++r) { + let region = cmd7.regions[r]; let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - let w = region.texExtent[0]; - let h = region.texExtent[1]; + let w = region.texExtent.width; + let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); + let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); + let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, - region.texOffset[0], region.texOffset[1], w, h, - cmd.gpuTexture.glFormat, data); + region.texOffset.x, region.texOffset.y, w, h, + cmd7.gpuTexture.glFormat, data); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -2012,29 +2039,32 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLRenderingContext.TEXTURE_CUBE_MAP: { - let texUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; - if (texUnit.glTexture !== cmd.gpuTexture.glTexture) { - gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, cmd.gpuTexture.glTexture); - texUnit.glTexture = cmd.gpuTexture.glTexture; + let glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== cmd7.gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, cmd7.gpuTexture.glTexture); + glTexUnit.glTexture = cmd7.gpuTexture.glTexture; } - let isCompressed = GFXFormatInfos[cmd.gpuTexture.format].isCompressed; + let isCompressed = GFXFormatInfos[cmd7.gpuTexture.format].isCompressed; if (!isCompressed) { - for (let r = 0; r < cmd.regions.length; ++r) { - let region = cmd.regions[r]; + for (let r = 0; r < cmd7.regions.length; ++r) { + let region = cmd7.regions[r]; let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + let w = region.texExtent.width; + let h = region.texExtent.height; + for (let f = 0; f < 6; ++f) { - let w = region.texExtent[0]; - let h = region.texExtent[1]; + let w = region.texExtent.width; + let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); + let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); + let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, - region.texOffset[0], region.texOffset[1], w, h, - cmd.gpuTexture.glFormat, cmd.gpuTexture.glType, data); + region.texOffset.x, region.texOffset.y, w, h, + cmd7.gpuTexture.glFormat, cmd7.gpuTexture.glType, data); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -2043,21 +2073,21 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } } } else { - for (let r = 0; r < cmd.regions.length; ++r) { - let region = cmd.regions[r]; + for (let r = 0; r < cmd7.regions.length; ++r) { + let region = cmd7.regions[r]; let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; for (let f = 0; f < 6; ++f) { - let w = region.texExtent[0]; - let h = region.texExtent[1]; + let w = region.texExtent.width; + let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd.gpuTexture.format, w, h, 1); - let data = cmd.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); + let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); + let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, - region.texOffset[0], region.texOffset[1], w, h, - cmd.gpuTexture.glFormat, data); + region.texOffset.x, region.texOffset.y, w, h, + cmd7.gpuTexture.glFormat, data); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -2074,13 +2104,13 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } } - if (cmd.gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { - gl.generateMipmap(cmd.gpuTexture.glTarget); + if (cmd7.gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { + gl.generateMipmap(cmd7.gpuTexture.glTarget); } } break; } - } - } + } // switch + } // for } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 4697c6b81f..7d1197b681 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -18,7 +18,7 @@ import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; import { GFXInputAssemblerInfo, GFXInputAssembler } from '../input-assembler'; import { WebGLGFXShader } from './webgl-shader'; import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../command-allocator'; -import { GFXPipelineStateInfo, GFXPipelineState } from '../pipeline-state'; +import { GFXPipelineStateInfo, GFXPipelineState, GFXRasterizerState } from '../pipeline-state'; import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; import { GFXBindingUnit, GFXBindingLayout, GFXBindingLayoutInfo } from '../binding-layout'; import { WebGLGFXSampler } from './webgl-sampler'; @@ -68,7 +68,7 @@ export class WebGLGFXDevice extends GFXDevice { public initialize(info: GFXDeviceInfo): boolean { - let canvasElm = info.canvasElm; + this._canvas = info.canvasElm; if (info.isAntialias) { this._isAntialias = info.isAntialias; @@ -90,7 +90,7 @@ export class WebGLGFXDevice extends GFXDevice { failIfMajorPerformanceCaveat: false, }; - this._webGLRC = canvasElm.getContext('webgl', webGLCtxAttribs); + this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); } catch (err) { console.error(err); return false; @@ -106,24 +106,25 @@ export class WebGLGFXDevice extends GFXDevice { console.info('WebGL device initialization successed.'); this._deviceName = "WebGL"; + let gl = this._webGLRC; - this._WEBGL_debug_renderer_info = this._webGLRC.getExtension("WEBGL_debug_renderer_info"); + this._WEBGL_debug_renderer_info = gl.getExtension("WEBGL_debug_renderer_info"); if (this._WEBGL_debug_renderer_info) { - this._renderer = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); - this._vendor = this._webGLRC.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); + this._renderer = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); + this._vendor = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); } else { - this._renderer = this._webGLRC.getParameter(WebGLRenderingContext.RENDERER); - this._vendor = this._webGLRC.getParameter(WebGLRenderingContext.VENDOR); + this._renderer = gl.getParameter(WebGLRenderingContext.RENDERER); + this._vendor = gl.getParameter(WebGLRenderingContext.VENDOR); } - - this._version = this._webGLRC.getParameter(WebGLRenderingContext.VERSION); - this._maxVertexAttributes = this._webGLRC.getParameter(WebGLRenderingContext.MAX_VERTEX_ATTRIBS); - this._maxVertexUniformVectors = this._webGLRC.getParameter(WebGLRenderingContext.MAX_VERTEX_UNIFORM_VECTORS); - this._maxFragmentUniformVectors = this._webGLRC.getParameter(WebGLRenderingContext.MAX_FRAGMENT_UNIFORM_VECTORS); - this._maxTextureUnits = this._webGLRC.getParameter(WebGLRenderingContext.MAX_TEXTURE_IMAGE_UNITS); - this._maxVertexTextureUnits = this._webGLRC.getParameter(WebGLRenderingContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - this._depthBits = this._webGLRC.getParameter(WebGLRenderingContext.DEPTH_BITS); - this._stencilBits = this._webGLRC.getParameter(WebGLRenderingContext.STENCIL_BITS); + + this._version = gl.getParameter(WebGLRenderingContext.VERSION); + this._maxVertexAttributes = gl.getParameter(WebGLRenderingContext.MAX_VERTEX_ATTRIBS); + this._maxVertexUniformVectors = gl.getParameter(WebGLRenderingContext.MAX_VERTEX_UNIFORM_VECTORS); + this._maxFragmentUniformVectors = gl.getParameter(WebGLRenderingContext.MAX_FRAGMENT_UNIFORM_VECTORS); + this._maxTextureUnits = gl.getParameter(WebGLRenderingContext.MAX_TEXTURE_IMAGE_UNITS); + this._maxVertexTextureUnits = gl.getParameter(WebGLRenderingContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + this._depthBits = gl.getParameter(WebGLRenderingContext.DEPTH_BITS); + this._stencilBits = gl.getParameter(WebGLRenderingContext.STENCIL_BITS); console.info("RENDERER: " + this._renderer); console.info("VENDOR: " + this._vendor); @@ -136,7 +137,7 @@ export class WebGLGFXDevice extends GFXDevice { console.info("DEPTH_BITS: " + this._depthBits); console.info("STENCIL_BITS: " + this._stencilBits); - this._extensions = this._webGLRC.getSupportedExtensions(); + this._extensions = gl.getSupportedExtensions(); /* if (this._extensions) { for (let i = 0; i < this._extensions.length; ++i) { @@ -145,44 +146,48 @@ export class WebGLGFXDevice extends GFXDevice { } */ - this._EXT_texture_filter_anisotropic = this._webGLRC.getExtension("EXT_texture_filter_anisotropic"); - this._EXT_frag_depth = this._webGLRC.getExtension("EXT_frag_depth"); - this._EXT_shader_texture_lod = this._webGLRC.getExtension("EXT_shader_texture_lod"); - this._EXT_sRGB = this._webGLRC.getExtension("EXT_sRGB"); - this._OES_vertex_array_object = this._webGLRC.getExtension("OES_vertex_array_object"); - this._WEBGL_color_buffer_float = this._webGLRC.getExtension("WEBGL_color_buffer_float"); - this._WEBGL_compressed_texture_astc = this._webGLRC.getExtension("WEBGL_compressed_texture_astc"); - this._WEBGL_compressed_texture_s3tc = this._webGLRC.getExtension("WEBGL_compressed_texture_s3tc"); - this._WEBGL_compressed_texture_s3tc_srgb = this._webGLRC.getExtension("WEBGL_compressed_texture_s3tc_srgb"); - this._WEBGL_debug_shaders = this._webGLRC.getExtension("WEBGL_debug_shaders"); - this._WEBGL_draw_buffers = this._webGLRC.getExtension("WEBGL_draw_buffers"); - this._WEBGL_lose_context = this._webGLRC.getExtension("WEBGL_lose_context"); - this._WEBGL_depth_texture = this._webGLRC.getExtension("WEBGL_depth_texture"); - this._OES_texture_half_float = this._webGLRC.getExtension("OES_texture_half_float"); - this._OES_texture_half_float_linear = this._webGLRC.getExtension("OES_texture_half_float_linear"); - this._OES_texture_float = this._webGLRC.getExtension("OES_texture_float"); - this._OES_standard_derivatives = this._webGLRC.getExtension("OES_standard_derivatives"); - this._OES_element_index_uint = this._webGLRC.getExtension("OES_element_index_uint"); - this._ANGLE_instanced_arrays = this._webGLRC.getExtension("ANGLE_instanced_arrays"); + this._EXT_texture_filter_anisotropic = gl.getExtension("EXT_texture_filter_anisotropic"); + this._EXT_frag_depth = gl.getExtension("EXT_frag_depth"); + this._EXT_shader_texture_lod = gl.getExtension("EXT_shader_texture_lod"); + this._EXT_sRGB = gl.getExtension("EXT_sRGB"); + this._OES_vertex_array_object = gl.getExtension("OES_vertex_array_object"); + this._WEBGL_color_buffer_float = gl.getExtension("WEBGL_color_buffer_float"); + this._WEBGL_compressed_texture_astc = gl.getExtension("WEBGL_compressed_texture_astc"); + this._WEBGL_compressed_texture_s3tc = gl.getExtension("WEBGL_compressed_texture_s3tc"); + this._WEBGL_compressed_texture_s3tc_srgb = gl.getExtension("WEBGL_compressed_texture_s3tc_srgb"); + this._WEBGL_debug_shaders = gl.getExtension("WEBGL_debug_shaders"); + this._WEBGL_draw_buffers = gl.getExtension("WEBGL_draw_buffers"); + this._WEBGL_lose_context = gl.getExtension("WEBGL_lose_context"); + this._WEBGL_depth_texture = gl.getExtension("WEBGL_depth_texture"); + this._OES_texture_half_float = gl.getExtension("OES_texture_half_float"); + this._OES_texture_half_float_linear = gl.getExtension("OES_texture_half_float_linear"); + this._OES_texture_float = gl.getExtension("OES_texture_float"); + this._OES_standard_derivatives = gl.getExtension("OES_standard_derivatives"); + this._OES_element_index_uint = gl.getExtension("OES_element_index_uint"); + this._ANGLE_instanced_arrays = gl.getExtension("ANGLE_instanced_arrays"); + + // init states + this.initStates(gl); - this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); - let depthStencilFmt; - if(this._depthBits === 24) { - if(this._stencilBits === 8) { + if (this._depthBits === 24) { + if (this._stencilBits === 8) { depthStencilFmt = GFXFormat.D24S8; } else { depthStencilFmt = GFXFormat.D24; } } else { - if(this._stencilBits === 8) { + if (this._stencilBits === 8) { depthStencilFmt = GFXFormat.D16S8; } else { depthStencilFmt = GFXFormat.D16; } } + // create queue + this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); + // create primary window this._mainWindow = this.createWindow({ title: this._webGLRC.canvas.title, @@ -598,33 +603,37 @@ export class WebGLGFXDevice extends GFXDevice { let glMinFilter = WebGLRenderingContext.NONE; let glMagFilter = WebGLRenderingContext.NONE; - if (info.minFilter === GFXFilter.LINEAR || info.minFilter === GFXFilter.ANISOTROPIC) { - if (info.mipFilter === GFXFilter.LINEAR || info.mipFilter === GFXFilter.ANISOTROPIC) { + let minFilter = (info.minFilter !== undefined? info.minFilter : GFXFilter.LINEAR); + let magFilter = (info.magFilter !== undefined? info.magFilter : GFXFilter.LINEAR); + let mipFilter = (info.mipFilter !== undefined? info.mipFilter : GFXFilter.NONE); + + if (minFilter === GFXFilter.LINEAR || minFilter === GFXFilter.ANISOTROPIC) { + if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { glMinFilter = WebGLRenderingContext.LINEAR_MIPMAP_LINEAR; - } else if (info.mipFilter === GFXFilter.POINT) { + } else if (mipFilter === GFXFilter.POINT) { glMinFilter = WebGLRenderingContext.LINEAR_MIPMAP_NEAREST; } else { glMinFilter = WebGLRenderingContext.LINEAR; } } else { - if (info.mipFilter === GFXFilter.LINEAR || info.mipFilter === GFXFilter.ANISOTROPIC) { + if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { glMinFilter = WebGLRenderingContext.NEAREST_MIPMAP_LINEAR; - } else if (info.mipFilter === GFXFilter.POINT) { + } else if (mipFilter === GFXFilter.POINT) { glMinFilter = WebGLRenderingContext.NEAREST_MIPMAP_NEAREST; } else { glMinFilter = WebGLRenderingContext.NEAREST; } } - if (info.magFilter === GFXFilter.LINEAR || info.magFilter === GFXFilter.ANISOTROPIC) { + if (magFilter === GFXFilter.LINEAR || magFilter === GFXFilter.ANISOTROPIC) { glMagFilter = WebGLRenderingContext.LINEAR; } else { glMagFilter = WebGLRenderingContext.NEAREST; } - let glWrapS = info.addressU ? WebGLWraps[info.addressU] : GFXAddress.WRAP; - let glWrapT = info.addressV ? WebGLWraps[info.addressV] : GFXAddress.WRAP; - let glWrapR = info.addressW ? WebGLWraps[info.addressW] : GFXAddress.WRAP; + let glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + let glWrapT = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + let glWrapR = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); let gpuSampler: WebGLGPUSampler = { objType: WebGLGPUObjectType.SAMPLER, @@ -722,10 +731,14 @@ export class WebGLGFXDevice extends GFXDevice { let gpuBindings: WebGLGPUBinding[] = new Array(info.bindings.length); for (let i = 0; i < info.bindings.length; ++i) { let binding = info.bindings[i]; - let gpuBinding = gpuBindings[i]; - gpuBinding.binding = binding.binding; - gpuBinding.type = binding.type; - gpuBinding.name = binding.name; + gpuBindings[i] = { + binding: binding.binding, + type: binding.type, + name: binding.name, + gpuBuffer: null, + gpuTexView: null, + gpuSampler: null, + }; } let gpuBindingLayout: WebGLGPUBindingLayout = { @@ -910,6 +923,43 @@ export class WebGLGFXDevice extends GFXDevice { return this._ANGLE_instanced_arrays; } + private initStates(gl: WebGLRenderingContext) { + + gl.activeTexture(WebGLRenderingContext.TEXTURE0); + gl.pixelStorei(WebGLRenderingContext.PACK_ALIGNMENT, 1); + gl.pixelStorei(WebGLRenderingContext.UNPACK_ALIGNMENT, 1); + + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, null); + + // rasteriazer state + gl.enable(WebGLRenderingContext.CULL_FACE); + gl.cullFace(WebGLRenderingContext.BACK); + gl.frontFace(WebGLRenderingContext.CCW); + gl.polygonOffset(0.0, 0.0); + + // depth stencil state + gl.enable(WebGLRenderingContext.DEPTH_TEST); + gl.depthMask(true); + gl.depthFunc(WebGLRenderingContext.LESS); + + gl.stencilFuncSeparate(WebGLRenderingContext.FRONT, WebGLRenderingContext.ALWAYS, 1, 0xffffffff); + gl.stencilOpSeparate(WebGLRenderingContext.FRONT, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP); + gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0xffffffff); + gl.stencilFuncSeparate(WebGLRenderingContext.BACK, WebGLRenderingContext.ALWAYS, 1, 0xffffffff); + gl.stencilOpSeparate(WebGLRenderingContext.BACK, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP); + gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0xffffffff); + + gl.disable(WebGLRenderingContext.STENCIL_TEST); + + // blend state + gl.disable(WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE); + gl.disable(WebGLRenderingContext.BLEND); + gl.blendEquationSeparate(WebGLRenderingContext.FUNC_ADD, WebGLRenderingContext.FUNC_ADD); + gl.blendFuncSeparate(WebGLRenderingContext.ONE, WebGLRenderingContext.ZERO, WebGLRenderingContext.ONE, WebGLRenderingContext.ZERO); + gl.colorMask(true, true, true, true); + gl.blendColor(0.0, 0.0, 0.0, 0.0); + } + private _webGLRC: WebGLRenderingContext | null = null; private _isAntialias: boolean = true; private _isPremultipliedAlpha: boolean = false; diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index f3763492f9..da11d4ae31 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -19,13 +19,13 @@ export class WebGLStateCache { texUnit : number = 0; glTex2DUnits : WebGLTexUnit[]; glTexCubeUnits : WebGLTexUnit[]; - glFramebuffer : WebGLFramebuffer = -1; + glFramebuffer : WebGLFramebuffer = 0; viewport : GFXViewport; scissorRect : GFXRect; rs : GFXRasterizerState; dss : GFXDepthStencilState; bs : GFXBlendState; - glProgram : WebGLProgram = -1; + glProgram : WebGLProgram = 0; glEnabledAttribLocs : boolean[]; glCurrentAttribLocs : boolean[]; diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 6e3a0e57b1..0f57feffd6 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -3,26 +3,46 @@ import { RenderFlow } from "../render-flow"; import { GFXCommandBuffer } from "../../gfx/command-buffer"; import { RenderView } from "../render-view"; import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat } from "../../gfx/define"; +import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXTextureLayout, GFXBufferTextureCopy, GFXAddress, GFXFilter, GFXBindingType, GFXType } from "../../gfx/define"; import { GFXInputAssembler } from "../../gfx/input-assembler"; import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; import { GFXShader } from "../../gfx/shader"; import { GFXRenderPass } from "../../gfx/render-pass"; import { GFXPipelineLayout } from "../../gfx/pipeline-layout"; import { GFXBindingLayout } from "../../gfx/binding-layout"; +import { GFXTexture } from "../../gfx/texture"; +import { GFXTextureView } from "../../gfx/texture-view"; +import { GFXSampler } from "../../gfx/sampler"; -let _shader_vs = -`#version 100 +/* +declare module '*.png' { + const value: any; + export = value; + } +*/ +//declare function require(string): string; +//const image = require('../../../playground/cocos2d-x.png'); + +let _shader_vs = `#version 100 attribute vec2 a_position; attribute vec2 a_texCoord; + +varying vec2 v_texCoord; + void main() { gl_Position = vec4(a_position, 0.0, 1.0); + v_texCoord = a_texCoord; }`; -let _shader_fs = -`#version 100 +let _shader_fs = `#version 100 +precision highp float; +varying vec2 v_texCoord; + +uniform sampler2D u_sampler; + void main() { - gl_FragColor = vec4(0.6, 0.3, 0.3, 1.0); + //gl_FragColor = vec4(0.6, 0.3, 0.3, 1.0); + gl_FragColor = texture2D(u_sampler, v_texCoord); }`; export class TestStage extends RenderStage { @@ -61,14 +81,19 @@ export class TestStage extends RenderStage { this._shader = this._device.createShader({ name: "test", - stages: [vsStage, fsStage] + stages: [vsStage, fsStage], + samplers: [ + {binding: 10, name: "u_sampler", type: GFXType.SAMPLER2D, count: 1 } + ] }); if (!this._shader) { return false; } this._bindingLayout = this._device.createBindingLayout({ - bindings: [], + bindings: [ + { binding: 10, type: GFXBindingType.SAMPLER, name: "u_sampler" }, + ], }); if (!this._bindingLayout) { return false; @@ -98,6 +123,18 @@ export class TestStage extends RenderStage { renderPass: this._framebuffer.renderPass, }); + let imgElms = this._device.canvas.getElementsByTagName("img"); + if (imgElms.length) { + if (!this.loadTexture(imgElms[0])) { + console.error("Load texture failed."); + return false; + } + + this.bindBindings(); + } else { + console.error("Not found image, load texture failed."); + } + return true; } @@ -136,8 +173,8 @@ export class TestStage extends RenderStage { cmdBuff.begin(); cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); - cmdBuff.bindBindingLayout(this._bindingLayout); cmdBuff.bindPipelineState(this._pipelineState); + cmdBuff.bindBindingLayout(this._bindingLayout); cmdBuff.bindInputAssembler(this._pipeline.quadIA); cmdBuff.draw(this._pipeline.quadIA); cmdBuff.endRenderPass(); @@ -146,6 +183,91 @@ export class TestStage extends RenderStage { 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; + //var buffer = image.currentSrc;//arraybuffer object + + let stagingBuffer = this._device.createBuffer({ + usage: GFXBufferUsageBit.TRANSFER_SRC, + memUsage: GFXMemoryUsageBit.HOST, + size: imgBuffer.byteLength, + }); + + if (!stagingBuffer) { + return false; + } + + 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; + } + + let region: GFXBufferTextureCopy = new GFXBufferTextureCopy; + region.texExtent.width = this._texture.width; + region.texExtent.height = this._texture.height; + + let cmdBuff = this._cmdBuff; + cmdBuff.begin(); + cmdBuff.updateBuffer(stagingBuffer, imgBuffer); + cmdBuff.copyBufferToTexture(stagingBuffer, this._texture, GFXTextureLayout.TRANSFER_DST_OPTIMAL, [region]); + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + + 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.bindTextureView(10, this._texView); + this._bindingLayout.bindSampler(10, this._sampler); + this._bindingLayout.update(); + + return true; + } + private _shader: GFXShader | null = null; private _bindingLayout: GFXBindingLayout | null = null; private _pipelineLayout: GFXPipelineLayout | null = null; @@ -153,4 +275,9 @@ export class TestStage extends RenderStage { private _rs: GFXRasterizerState = new GFXRasterizerState; private _dss: GFXDepthStencilState = new GFXDepthStencilState; private _bs: GFXBlendState = new GFXBlendState; + + private _texture: GFXTexture | null = null; + private _texView: GFXTextureView | null = null; + private _sampler: GFXSampler | null = null; + }; diff --git a/playground/simple.html b/playground/simple.html index 8fbfb431d2..a31187dcd1 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -23,7 +23,10 @@ - + + + + - + \ No newline at end of file From 9dffcfbe989dba77dd1f268635403c6df256c045 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 4 Jan 2019 10:29:56 +0800 Subject: [PATCH 028/267] wrap texture loading interface --- cocos/gfx/define.ts | 4 +- cocos/gfx/device.ts | 63 +++--- cocos/gfx/webgl/webgl-commands.ts | 285 ++++++++++++++------------- cocos/gfx/webgl/webgl-device.ts | 34 +++- cocos/pipeline/forward/test-stage.ts | 22 +-- playground/cubetexture.png | Bin 0 -> 95370 bytes 6 files changed, 215 insertions(+), 193 deletions(-) create mode 100644 playground/cubetexture.png diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index cbb9bcfa31..eaa588a83f 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -425,8 +425,8 @@ export enum GFXQueueType { // Interfaces export interface GFXRect { - left: number; - top: number; + x: number; + y: number; width: number; height: number; } diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 38c9da9bad..9bda923c72 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -13,6 +13,7 @@ import { GFXCommandBufferInfo, GFXCommandBuffer } from './command-buffer'; import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './command-allocator'; import { GFXWindowInfo, GFXWindow } from './window'; import { GFXBindingLayoutInfo, GFXBindingLayout } from './binding-layout'; +import { GFXRect } from './define'; export enum GFXFeature { }; @@ -25,25 +26,27 @@ export interface GFXDeviceInfo { export abstract class GFXDevice { - public abstract initialize(info : GFXDeviceInfo) : boolean; - public abstract destroy() : void; - public abstract createBuffer(info: GFXBufferInfo) : GFXBuffer | null; - public abstract createTexture(info: GFXTextureInfo) : GFXTexture | null; - public abstract createTextureView(info: GFXTextureViewInfo) : GFXTextureView | null; - public abstract createSampler(info: GFXSamplerInfo) : GFXSampler | null; - public abstract createBindingLayout(info: GFXBindingLayoutInfo) : GFXBindingLayout | null; - public abstract createShader(info: GFXShaderInfo) : GFXShader | null; - public abstract createInputAssembler(info: GFXInputAssemblerInfo) : GFXInputAssembler | null; - public abstract createRenderPass(info: GFXRenderPassInfo) : GFXRenderPass | null; - public abstract createFramebuffer(info: GFXFramebufferInfo) : GFXFramebuffer | null; - public abstract createPipelineLayout(info: GFXPipelineLayoutInfo) : GFXPipelineLayout | null; - public abstract createPipelineState(info: GFXPipelineStateInfo) : GFXPipelineState | null; + public abstract initialize(info: GFXDeviceInfo): boolean; + public abstract destroy(): void; + public abstract createBuffer(info: GFXBufferInfo): GFXBuffer | null; + public abstract createTexture(info: GFXTextureInfo): GFXTexture | null; + public abstract createTextureView(info: GFXTextureViewInfo): GFXTextureView | null; + public abstract createSampler(info: GFXSamplerInfo): GFXSampler | null; + public abstract createBindingLayout(info: GFXBindingLayoutInfo): GFXBindingLayout | null; + public abstract createShader(info: GFXShaderInfo): GFXShader | null; + public abstract createInputAssembler(info: GFXInputAssemblerInfo): GFXInputAssembler | null; + public abstract createRenderPass(info: GFXRenderPassInfo): GFXRenderPass | null; + public abstract createFramebuffer(info: GFXFramebufferInfo): GFXFramebuffer | null; + public abstract createPipelineLayout(info: GFXPipelineLayoutInfo): GFXPipelineLayout | null; + public abstract createPipelineState(info: GFXPipelineStateInfo): GFXPipelineState | null; public abstract createCommandAllocator(info: GFXCommandAllocatorInfo): GFXCommandAllocator | null; - public abstract createCommandBuffer(info: GFXCommandBufferInfo) : GFXCommandBuffer | null; - public abstract createQueue(info: GFXQueueInfo) : GFXQueue | null; - public abstract createWindow(info: GFXWindowInfo) : GFXWindow | null; + public abstract createCommandBuffer(info: GFXCommandBufferInfo): GFXCommandBuffer | null; + public abstract createQueue(info: GFXQueueInfo): GFXQueue | null; + public abstract createWindow(info: GFXWindowInfo): GFXWindow | null; public abstract present(); - + + public abstract copyBufferToTexture2D(buffer: ArrayBuffer, texture: GFXTexture, rect?: GFXRect); + public get canvas(): HTMLCanvasElement { return this._canvas; } @@ -97,18 +100,18 @@ export abstract class GFXDevice { } protected _canvas: HTMLCanvasElement | null = null; - protected _deviceName : string = ""; - protected _renderer : string = ""; - protected _vendor : string = ""; - protected _version : string = ""; - protected _queue : GFXQueue | null = null; - protected _mainWindow : GFXWindow | null = null; + protected _deviceName: string = ""; + protected _renderer: string = ""; + protected _vendor: string = ""; + protected _version: string = ""; + protected _queue: GFXQueue | null = null; + protected _mainWindow: GFXWindow | null = null; protected _cmdAllocator: GFXCommandAllocator | null = null; - protected _maxVertexAttributes : number = 0; - protected _maxVertexUniformVectors : number = 0; - protected _maxFragmentUniformVectors : number = 0; - protected _maxTextureUnits : number = 0; - protected _maxVertexTextureUnits : number = 0; - protected _depthBits : number = 0; - protected _stencilBits : number = 0; + protected _maxVertexAttributes: number = 0; + protected _maxVertexUniformVectors: number = 0; + protected _maxFragmentUniformVectors: number = 0; + protected _maxTextureUnits: number = 0; + protected _maxVertexTextureUnits: number = 0; + protected _depthBits: number = 0; + protected _stencilBits: number = 0; }; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index f94e8e096e..d837938319 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -348,7 +348,7 @@ export class WebGLCmdObject { export class WebGLCmdBeginRenderPass extends WebGLCmdObject { gpuFramebuffer: WebGLGPUFramebuffer | null = null; - renderArea: GFXRect = { left: 0.0, top: 0.0, width: 0.0, height: 0.0 }; + renderArea: GFXRect = { x: 0, y: 0, width: 0, height: 0 }; clearColors: GFXColor[] = []; clearDepth: number = 1.0; clearStencil: number = 0; @@ -1148,7 +1148,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let i = 0; i < cmdPackage.cmds.length; ++i) { let cmd = cmdPackage.cmds[i]; let cmdId = cmdIds[cmd]++; - + switch (cmdPackage.cmds[i]) { case WebGLCmd.BEGIN_RENDER_PASS: { let cmd0 = cmdPackage.beginRenderPassCmds[cmdId]; @@ -1157,33 +1157,33 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG if (cmd0.gpuFramebuffer) { if (device.stateCache.glFramebuffer !== cmd0.gpuFramebuffer.glFramebuffer) { - let glFBO = (cmd0.gpuFramebuffer.glFramebuffer !== 0? cmd0.gpuFramebuffer.glFramebuffer : null); + let glFBO = (cmd0.gpuFramebuffer.glFramebuffer !== 0 ? cmd0.gpuFramebuffer.glFramebuffer : null); gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, glFBO); device.stateCache.glFramebuffer = cmd0.gpuFramebuffer.glFramebuffer; } - if (device.stateCache.viewport.left !== cmd0.renderArea.left || - device.stateCache.viewport.top !== cmd0.renderArea.top || + if (device.stateCache.viewport.left !== cmd0.renderArea.x || + device.stateCache.viewport.top !== cmd0.renderArea.y || device.stateCache.viewport.width !== cmd0.renderArea.width || device.stateCache.viewport.height !== cmd0.renderArea.height) { - gl.viewport(cmd0.renderArea.left, cmd0.renderArea.top, cmd0.renderArea.width, cmd0.renderArea.height); + gl.viewport(cmd0.renderArea.x, cmd0.renderArea.y, cmd0.renderArea.width, cmd0.renderArea.height); - device.stateCache.viewport.left = cmd0.renderArea.left; - device.stateCache.viewport.top = cmd0.renderArea.top; + device.stateCache.viewport.left = cmd0.renderArea.x; + device.stateCache.viewport.top = cmd0.renderArea.y; device.stateCache.viewport.width = cmd0.renderArea.width; device.stateCache.viewport.height = cmd0.renderArea.height; } - if (device.stateCache.scissorRect.left !== cmd0.renderArea.left || - device.stateCache.scissorRect.top !== cmd0.renderArea.top || + if (device.stateCache.scissorRect.x !== cmd0.renderArea.x || + device.stateCache.scissorRect.y !== cmd0.renderArea.y || device.stateCache.scissorRect.width !== cmd0.renderArea.width || device.stateCache.scissorRect.height !== cmd0.renderArea.height) { - gl.scissor(cmd0.renderArea.left, cmd0.renderArea.top, cmd0.renderArea.width, cmd0.renderArea.height); + gl.scissor(cmd0.renderArea.x, cmd0.renderArea.y, cmd0.renderArea.width, cmd0.renderArea.height); - device.stateCache.scissorRect.left = cmd0.renderArea.left; - device.stateCache.scissorRect.top = cmd0.renderArea.top; + device.stateCache.scissorRect.x = cmd0.renderArea.x; + device.stateCache.scissorRect.y = cmd0.renderArea.y; device.stateCache.scissorRect.width = cmd0.renderArea.width; device.stateCache.scissorRect.height = cmd0.renderArea.height; } @@ -1947,7 +1947,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let cmd6 = cmdPackage.updateBufferCmds[cmdId]; if (cmd6.gpuBuffer) { - if(cmd6.buffer && cmd6.gpuBuffer.bufferView) { + if (cmd6.buffer && cmd6.gpuBuffer.bufferView) { cmd6.gpuBuffer.bufferView.set(new Uint8Array(cmd6.buffer), cmd6.offset); } @@ -1983,130 +1983,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { let cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; if (cmd7.gpuBuffer && cmd7.gpuBuffer.bufferView && cmd7.gpuTexture) { - - switch (cmd7.gpuTexture.glTarget) { - case WebGLRenderingContext.TEXTURE_2D: { - let glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; - if (glTexUnit.glTexture !== cmd7.gpuTexture.glTexture) { - gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, cmd7.gpuTexture.glTexture); - glTexUnit.glTexture = cmd7.gpuTexture.glTexture; - } - - let isCompressed = GFXFormatInfos[cmd7.gpuTexture.format].isCompressed; - if (!isCompressed) { - for (let r = 0; r < cmd7.regions.length; ++r) { - let region = cmd7.regions[r]; - let buffOffset = region.buffOffset; + region.buffTexHeight * region.buffStride; - - let w = region.texExtent.width; - let h = region.texExtent.height; - - for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); - let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); - - gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, - region.texOffset.x, region.texOffset.y, w, h, - cmd7.gpuTexture.glFormat, cmd7.gpuTexture.glType, data); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } else { - for (let r = 0; r < cmd7.regions.length; ++r) { - let region = cmd7.regions[r]; - let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - let w = region.texExtent.width; - let h = region.texExtent.height; - - for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); - let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); - - gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, - region.texOffset.x, region.texOffset.y, w, h, - cmd7.gpuTexture.glFormat, data); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } - break; - } - case WebGLRenderingContext.TEXTURE_CUBE_MAP: { - let glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; - if (glTexUnit.glTexture !== cmd7.gpuTexture.glTexture) { - gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, cmd7.gpuTexture.glTexture); - glTexUnit.glTexture = cmd7.gpuTexture.glTexture; - } - - let isCompressed = GFXFormatInfos[cmd7.gpuTexture.format].isCompressed; - if (!isCompressed) { - for (let r = 0; r < cmd7.regions.length; ++r) { - let region = cmd7.regions[r]; - let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - let w = region.texExtent.width; - let h = region.texExtent.height; - - for (let f = 0; f < 6; ++f) { - let w = region.texExtent.width; - let h = region.texExtent.height; - - for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); - let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); - - gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, - region.texOffset.x, region.texOffset.y, w, h, - cmd7.gpuTexture.glFormat, cmd7.gpuTexture.glType, data); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } - } else { - for (let r = 0; r < cmd7.regions.length; ++r) { - let region = cmd7.regions[r]; - let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - - for (let f = 0; f < 6; ++f) { - let w = region.texExtent.width; - let h = region.texExtent.height; - - for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(cmd7.gpuTexture.format, w, h, 1); - let data = cmd7.gpuBuffer.bufferView.subarray(buffOffset, buffOffset + memSize); - - gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, - region.texOffset.x, region.texOffset.y, w, h, - cmd7.gpuTexture.glFormat, data); - - buffOffset += memSize; - w = Math.max(1, w >> 1); - h = Math.max(1, w >> 1); - } - } - } - } - break; - } - default: { - console.error("Unsupported GL texture type, copy buffer to texture failed."); - continue; - } - } - - if (cmd7.gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { - gl.generateMipmap(cmd7.gpuTexture.glTarget); - } + WebGLCmdFuncCopyBufferToTexture2D(device, cmd7.gpuBuffer.bufferView, cmd7.gpuTexture, cmd7.regions); } break; @@ -2114,3 +1991,135 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // switch } // for } + +export function WebGLCmdFuncCopyBufferToTexture2D( + device: WebGLGFXDevice, + bufferView: Uint8Array, + gpuTexture: WebGLGPUTexture, + regions: GFXBufferTextureCopy[]) { + + let gl = device.gl; + + switch (gpuTexture.glTarget) { + case WebGLRenderingContext.TEXTURE_2D: { + let glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + let isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; + if (!isCompressed) { + for (let r = 0; r < regions.length; ++r) { + let region = regions[r]; + let buffOffset = region.buffOffset; + region.buffTexHeight * region.buffStride; + + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + let data = bufferView.subarray(buffOffset, buffOffset + memSize); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } else { + for (let r = 0; r < regions.length; ++r) { + let region = regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + let data = bufferView.subarray(buffOffset, buffOffset + memSize); + + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + break; + } + case WebGLRenderingContext.TEXTURE_CUBE_MAP: { + let glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + } + + let isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; + if (!isCompressed) { + for (let r = 0; r < regions.length; ++r) { + let region = regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let f = 0; f < 6; ++f) { + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + let data = bufferView.subarray(buffOffset, buffOffset + memSize); + + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, gpuTexture.glType, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + } else { + for (let r = 0; r < regions.length; ++r) { + let region = regions[r]; + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; + + for (let f = 0; f < 6; ++f) { + let w = region.texExtent.width; + let h = region.texExtent.height; + + for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { + let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + let data = bufferView.subarray(buffOffset, buffOffset + memSize); + + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, data); + + buffOffset += memSize; + w = Math.max(1, w >> 1); + h = Math.max(1, w >> 1); + } + } + } + } + break; + } + default: { + console.error("Unsupported GL texture type, copy buffer to texture failed."); + } + } + + if (gpuTexture.flags & GFXTextureFlagBit.GEN_MIPMAP) { + gl.generateMipmap(gpuTexture.glTarget); + } +} diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 7d1197b681..8faf2abb87 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -4,7 +4,7 @@ import { WebGLGFXBuffer } from './webgl-buffer'; import { WebGLGFXQueue } from './webgl-queue'; import { WebGLStateCache } from './webgl-state-cache'; import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; -import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember } from './webgl-commands'; +import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncCopyBufferToTexture2D } from './webgl-commands'; import { GFXTexture, GFXTextureInfo } from '../texture'; import { GFXTextureViewInfo, GFXTextureView } from '../texture-view'; import { GFXRenderPassInfo, GFXRenderPass } from '../render-pass'; @@ -31,7 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat } from '../define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat, GFXBufferTextureCopy, GFXMemoryUsageBit, GFXTextureLayout, GFXTextureSubres, GFXRect } from '../define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -377,6 +377,36 @@ export class WebGLGFXDevice extends GFXDevice { public present() { } + public copyBufferToTexture2D(buffer: ArrayBuffer, texture: GFXTexture, rect?: GFXRect) { + + let bufferView = new Uint8Array(buffer); + + let x, y, w, h; + + if(rect !== undefined) { + x = rect.x; + y = rect.y; + w = rect.width; + h = rect.height; + } else { + x = 0; + y = 0; + w = texture.width; + h = texture.height; + } + + let region: GFXBufferTextureCopy = { + buffOffset: 0, + buffStride: 0, + buffTexHeight: 0, + texOffset: { x: x, y: y, z: 0 }, + texExtent: { width: w, height: h, depth: 1 }, + texSubres: new GFXTextureSubres, + }; + + WebGLCmdFuncCopyBufferToTexture2D(this, bufferView, (texture).gpuTexture, [region]); + } + public get gl(): WebGLRenderingContext { return this._webGLRC; } diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 0f57feffd6..2088bf2cde 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -199,16 +199,6 @@ export class TestStage extends RenderStage { let imgBuffer: ArrayBuffer = imgData.data; //var buffer = image.currentSrc;//arraybuffer object - let stagingBuffer = this._device.createBuffer({ - usage: GFXBufferUsageBit.TRANSFER_SRC, - memUsage: GFXMemoryUsageBit.HOST, - size: imgBuffer.byteLength, - }); - - if (!stagingBuffer) { - return false; - } - this._texture = this._device.createTexture({ type: GFXTextureType.TEX2D, usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, @@ -232,17 +222,7 @@ export class TestStage extends RenderStage { return false; } - let region: GFXBufferTextureCopy = new GFXBufferTextureCopy; - region.texExtent.width = this._texture.width; - region.texExtent.height = this._texture.height; - - let cmdBuff = this._cmdBuff; - cmdBuff.begin(); - cmdBuff.updateBuffer(stagingBuffer, imgBuffer); - cmdBuff.copyBufferToTexture(stagingBuffer, this._texture, GFXTextureLayout.TRANSFER_DST_OPTIMAL, [region]); - cmdBuff.end(); - - this._device.queue.submit([cmdBuff]); + this._device.copyBufferToTexture2D(imgBuffer, this._texture); this._sampler = this._device.createSampler({ minFilter: GFXFilter.LINEAR, diff --git a/playground/cubetexture.png b/playground/cubetexture.png new file mode 100644 index 0000000000000000000000000000000000000000..078b19a569cf1b83fc63024d61ede48e06218fd4 GIT binary patch literal 95370 zcmV)FK)=64Tx0C)kNmUmPX*B8g%%xo{TU6vwc>AklFq%OTkl_mFQv@x1^BM1TV}0C2duqR=S6Xn?LjUp6xrb&~O43j*Nv zEr418u3H3zGns$s|L;SQD-ufpfWpxLJ03rmi*g~#S@{x?OrJ!Vo{}kJ7$ajbnjp%m zGEV!%=70KpVow?KvV}a4moSaFCQKV= zXBIPnpP$8-NG!rR+)R#`$7JVZi#Wn10DSspSrkx`)s~4C+0n+?(b2-z5-tDd^^cpM zz5W?wz5V3zGUCskL5!X++LzcbT23thtSPiMTfS&1I{|204}j|3FPi>70OSh+Xzlyz zdl<5LNtZ}OE>>3g`T3RtKG#xK(9i3CI(+v0d-&=+OWAp!Ysd8Ar*foO5~i%E+?=c& zshF87;&Ay)i~kOm zCIB-Z!^JGdti+UJsxgN!t(Y#%b<8kk67vyD#cE*9urAm@Y#cTXn~yERR$}Y1E!Yd# zo7hq8Ya9;8z!~A3Z~?e@Tn26#t`xT$*Ni)h>&K1Yrto;Y8r}@=h7ZGY@Dh9xekcA2 z{tSKqKZ<`tAQQ9+wgf*y0zpVvOQ<9qCY&Y=5XJ~ILHOG0j2XwBQ%7jM`P2tv~{#P+6CGu9Y;5!2hua>CG_v;z4S?CC1rc%807-x z8s$^ULkxsr$OvR)G0GUn7`GVjR5Vq*RQM{JRGL%DRgX~5SKp(4L49HleU9rK?wsN|$L8GCfHh1tA~lw29MI^|n9|hJ z^w$(=?$kW5IibbS^3=-Es?a*EHLgw5cGnhYS7@Kne#%s4dNH$@Rm?8tq>hG8fR0pW zzfP~tjINRHeBHIW&AJctNO~;2RJ{tlPQ6KeZT(RF<@$~KcMXUJEQ54|9R}S7(}qTd zv4$HA+YFx=sTu_uEj4O1x^GN1_Ap*-Tx)#81ZToB$u!w*a?KPrbudjgtugI0gUuYx z1ZKO<`pvQC&gMe%TJu2*iiMX&o<*a@uqDGX#B!}=o8@yWeX9hktybMuAFUm%v#jf^ z@7XBX1lg>$>9G0T*3_13TVs2}j%w#;x5}>F?uEUXJ>Pzh{cQ)DL#V?BhfaqNj!uqZ z$0o;dCw-@6r(I5iEIKQkRm!^LjCJ;QUgdn!`K^nii^S!a%Wtk0u9>cfU7yS~n#-SC zH+RHM*Nx-0-)+d9>7MMq&wa>4$AjZh>+#4_&y(j_?>XjW;+5fb#Ot}YwYS*2#e16V z!d}5X>x20C`xN{1`YQR(_pSDQ=%?$K=GW*q>F?mb%>QfvHXt})YrtTjW*|4PA#gIt zDQHDdS1=_wD!4lMQHW`XIHV&K4h;(37J7f4!93x-wlEMD7`83!LAX));_x3Ma1r4V zH4%>^Z6cRPc1O{olA;bry^i*dE{nc5-*~=serJq)Okzw!%yg_zYWi`#ol25V;v^kU#wN!mA5MPH z3FFjqrcwe^cBM>m+1wr6XFN|{1#g`1#xLiOrMjh-r#?w@OWT$Wgg6&&5F%x&L(6hXP*!%2{VOVIa)adIsGCtQITk9vCHD^izmgw;`&@D zcVTY3gpU49^+=7S>!rha?s+wNZ}MaEj~6Hw2n%|am@e70WNfM5(r=exmT{MLF4tMU zX8G_6uNC`OLMu~NcCOM}Rk&(&wg2ivYe;J{*Zj2BdTsgISLt?eJQu}$~QLORDCnMIdyYynPb_W zEx0YhEw{FMY&}%2SiZD;WLxOA)(U1tamB0cN!u@1+E?z~LE0hRF;o>&)xJ}I=a!xC ztJAA*)_B)6@6y<{Y1i~_-tK`to_m`1YVIxB`);3L-|hYW`&(-bYby`n4&)tpTo+T< z{VnU;hI;k-lKKw^g$IWYMIP#EaB65ctZ}%k5pI+=jvq-pa_u{x@7kLzn)Wv{noEv? zqtc^Kzfb=D*0JDYoyS?nn|?6(VOI;SrMMMpUD7()mfkkh9^c-7BIrbChiga6kCs0k zJgIZC=9KcOveTr~g{NoFEIl)IR&;jaT-v#j&ZN$J=i|=b=!)p-y%2oi(nY_E=exbS z&s=i5bn>#xz3Ke>~2=f&N;yEFGz-^boBexUH6@}b7V+Mi8+ZXR+R zIyLMw-18{v(Y+Dw$g^K^e|bMz_?Y^*a!h-y;fd{&ljDBl*PbqTI{HlXY-Xb9SH)j< zJvV;-!*8Cy^-RW1j=m7TnEk!M@vZ)ZrhG3SKP)q^_0|A>g1`NgpcN<$S>RmI^^m^yE_xb+L|J=C}HiX!+VbPg6 z_w;^#<@`?hrz(}ou$eWXE9f)oC%gwLK1yMzQmNFlTH9(>sK&EflV`OXep(CHkj-ZK zX+bysw6@}Bt=<9V7s0Iz6c&nQE0xMtEER2LcEP656Vvl&X|Z^0PJ+ z|0lFJEd)?XS|WsgW;mavVTBVjQFj6OlTr4GnY^7Co3W{>S(~1owIjomw*T0q?K?VU zhel@Y#AM!%O%-gH=j`!)$8Gn46LxfH%=R7{x7+qk+RnXm zW+w_}4FGE!K-XMn1`syZrK}wQZV;6Q(lUt#loQ~SO-i7c4xB(L!8-08VpfC*h*2W_ zp}$=XmVZR_jOwxK?4Ya2ima0-|0&Ul~vNZBhlq@+47{H zzLm!=0Nw(CSO93s09z_uu{r^JSI!!`o2{v* z)f&3ctxcAN6;IXISp^`kh?)b384nTJe;N=LfBfK8Jx(pnG$BngB9T6l_={CaF zv^82i0H47wWK)2$7oqA2dC*{yNX z)>8ZNsd+nic-X%4y~pjQTX)(QZyhq*!5aSTMqAwr#Rh;SSr-*90BEUl$uji-Z70;7 zb$4@Lr!{uBLG4>$>2nC^G5}uy3ITc(RKAlux>#Ll+zJyiQ2nJHDS)`9Kn4>a zgVE`Njm@w-ktbdhH&c$RBM2+++siKW!w2kDJ$3fNi&xm?=dM7&*lk@koWT?IE6LBO zr``i+5WrLILtrKFyciMiwJo>z;IQ3x*JF15%{%OKAKa@*W?LFu-Aha zq5xl2QgH%E#DfMtaZ^-SS`=AG0QmL1#jYzZhKDs$uV$qYhCsugxEb?QeFW$W=y}>Y zBY=mp%bX>%0ui;@p!~!^%rC$l2pLQ*py3c^ODrh}Woc7aS7&pxdHdE)514)Ls98s& zz53!Vd&MOy>^a+4+WJ*Ja3tbx$d5h<>I_$qbi`9N&LDuN(u1O!qMlKWjL+EjckHt- zef@rW-@iO+b`KjY8=7tXAm^+^xtZ`K0X=MeHdSP84RC7xKDfl1miNHkcf#&Bz%{c3 z0B{6&qU_7tnrvA|i*>g&T3cfS(td<|jyw{$1bQ8S1yf071f)3}11cl&6!=KXDIMKH z0FpCKkcoB<)g+~LL_xd`%3>wq@o@&F3=$={RC!vq%tGcTkrzxLADAc>9U(X}AXAky zhsC zwj856weO?<8S}^Lfino;$LcO3M=BJlJ#cFK4h`GQw?1T_`|5r6wNLFe>p|MRzS;U( z>H(;D*!wxfN*J(B<3wP*wt=5gf)Q# z5+Z1l{6|Ps*-`>n0jOXy!etvk+YST^kQFWZEB>h}rqhyLuqVW$V*n~j%YoX&az;Yz zcDWOc5#o|oc}YGn0l<&uq5g0I(|8IQNDwJ8z$|`K99SA1n@1$TPQu8X9l3Y6&Fvqt zCIp7#q&+x_jAW=_S6tdMT-gWU_glk~ z4$HAkR^qP+;5Q?AU)|kdYw%y%(P}NQ_D*#H6akzjx>oR-_YvSk*&F3X&k0&lqS~_d zV(CKr@&Pwdexy6m{^Aa_(x6qXe2>11~V5evk0$`3LaM^HEnGB}}=iRwTwm$)6t z7pCC~CRiSf0r1Bj+-Ljm-49X(@lm5Xu;N4GY=<5O8L&I@&X=vVS6;Ev&e^!kWgM!T zZzYmfEH>8njQK-*;0yxzq1{7ZpmqSC$Sg|h`v-UIwQK+74*T=>-ffUK>$$kYI$+&d z2HPA7>e!2~V|Oc)MxX~+WZT=Uan*8bT;9u;U5kg85cZV-)g`1`&zgVL(r)rVCJ zN?H8a#UNTeODF9%>_5Wt0Ob1HFJEcDc-3Y*f9s%cm#V&JI0E&;zgnF^06(m&YS)=X z$k=_~-(~-F-L3ZCci-X3dN1zejC>uF7)mB!gxc3}Ixm|lSsGqF+l~Z()e37E0Px!Z zZusgl0>2_*OL1=+>_sTp#k#)UAxG@JQ+fbG058B7z)DMrEnf=YcR<+%_zryf!LImG z$S1F9@@mDi8I9Fd%qMZ4WYmUvzJx|IMm))#IHI4-TCFlqb;o+BzOw85z%WSQ=*)u4 z4&*mHGiQ5FjN2sJg!!YRHnVHU3XTZ0L;{`C$ObJT;2L%xoh6f!{rbe#(Yr#UPGS?_8E@K^QP%Kjcl9)c24djVji z_OeGUz?Kp)X-&TxT%mYktECh#D#dkojb{=qMyZ-LQL28?@?>dLi5PaOskHKoIs&^) z_v1(Q==N|`0zHFlVE5#_-MN3r_Ki+*=n+6i$|;Vjh>T#C6OuE#kJM0jWoa;0R{Q_O_o}WxxEY?RG8#Lv4Rb)sCfmocXEkfino8wl~Cj>!@y|9FOlk zYS&!*E&Jo&znN%78@Qy)>e;rM0Pr&`(6gfWEW|UgqiNRhnTAHF{VHo*HfVKF_zXh7 zdH}Y_8dk@1H?HhuTdUvNT5>MT6W|M&9dI!P5BiCKEO(g3cqiea=$#+}T>%hB5LJ!U zy=vXH_89-iF$KU;J&`^7$&6a@WfuaCezm|K?b>zF(nT_iv6*?>b8N)+jEr**p^SVW zZ71Na>dB!F&LF>k*k;i4EFTJ$tQFY0D8UglF%}gH+NGTX5W(-he!ac*=g+mR>-xP< z&nycx8c(RsAb{8{wUpxc=#+i&tGC*(|K-<^^o`lzMN2qGpLHp=D1KIJe6*jbho#r4 zxw;}IdwgV|Y3YR@<0gC)2 z5cITiW7qn=hvk666;~>nr`n&$Ex&(_67WX#!|b(T0(z+kax+7u$_H94%Js|+e zKeT&rY;?jNIB?9$3$wP0i|UVaCF09dw2rWIrf00-&@n3G_l;ZabuZm+%X-=#e@K2Uef`d8oc*0bwuA zIOaNF>(&lf1BZV~%x(d^@8M(e?^*yY6_J4eT}o2^9*~HrenbEYlU>w5Nmk8Amgwgh z@N=sBNBIj-pGZajsu?Xrj@DXJ_F7#9emtXHrrJD4zZ_%#QHP7fg{7eUlTiF!2ai}^ z;jq16Aj4&+M*Hr;ihW~R?k94_QDNAz%YnbkEto#s)ax5NvQ!KUuHcUT(eDXO5-M%X zXVG$U>}q&TTnD1W9m8u)*~5}*5#W`pfL>ZEZ~@^Mu>_bx1VbR(;z9w|zGQP8Cw^q# zQA?jVU~k=OcJan;?h!QD1F#IY?whxNcx=`VJi<}pu?ahi?T&gd>lEC;e4hTI@HVjI zV;nfLJ@fYKZ&+*p@eLQ-*(?jB&Ts?X4L_R*zz1LL2Lg2v<+`ujVsCx>wM?XGTYJe8 zw$zwNOvWsvwhH*1`Y9d`xrH2$gY^!x7AW(2(Jbcz=8*~H zdEIEwkx~2S9sBKf2IlQ;S9T*u>7$?P?9hohyKn!Dee3RH_O~}5Ve6v;yPsp1gryhD ziV2WOj!tRD{pb;v1*|bX^0tfY7hiI2xOjAi8~E8n0JT(K`}u$RzR%fbKYY72Z0dD( ze}p5fx;*2oJ`+dl`!r{EGwea9ITlyfvC48w)^Y8&5x|ENaCrdx)KLBc{K67m%-Mdy zdTZfUU5TTxr&9fh3@YTMiSI}N(3c4V;eazhUj5otNPtB^D!WVvawSac@~c(REz|R_ z3H0=dzr17InkZGP(#G^jaem-PCj(=cBFC_3(V?V>7-GCypm#rh{CF^?+=%=5P1yl% z5$g0`g|h*3^Ld-)BGvT73`k(!#!pPxryf2CkWbntU)o@=dBJLHYU%ZKb8rlLH072% zcG=(Fbiy7zif{xW?B=F4_Yf*87>cEPKz_e)(p5>+7z;Z^70*r`y;0bL_1-#b>fO-~+v4^~LgM z>*}qpdlOWDz$O2p`Wd};162|57ZC<__qNzM7p}Kv?(vt{6-a|XBEUP~0vvJ&NM=$J zUWbQd0#cLk!5v_M^)1}vr@pGP;>RQr33%k>Cxq#jc)c-NQkxZyvGF+((ablzJ_QK>Mb1V5c^5 z1IOS7I9~nf|MXmY^_6FHbCPXGHHHrSxAqYg_-Rx>i3s57@5kEp-p;*8>@VK`S^Mbw zZ?d+{Y{_x6?u4GbVr`!hP)m|5b|0wB$WN#F>N~8yXRFn zEuA^re#r)FZfS6~U)zMD{sPJ>`;S{Jua**P+IU9~#34W+s{0>f@^`~gw15Ph?WZe< z;gd3&-aEvP6IEud-NW@0J*ys1=v57^jZT%Ss@CqFH6AtADuBm0wZN@-Q9Honh;ErN zuIez(=KmqC2^YCpScDsx7ZPA8FvUfynaNojJ3eMd_Z+nE9cIffKW$%lOS8S=Wt*)& z*UeTS52qk3R7)o(M(n|dcG)LyIAH(ld*oc-VjGYX=m@gYZtxs{dV7% zci6g%2mH+b6jVpoO&$1wSl!JR0?-S&V(ROf`YqSJjrBd(b2D%P;tsU$kEz2Z2&|C_ zWNgcMtDWsHB7GJ`*Tj|zfQ1W-fSP2sw!O|;0rELmUF{}FDZYeOz(12PED1b-AH|S9 zInN}N0QtwT#J6gM+^f#2<;nb?ET5P#mQ@>XkrP;~OQh_z@zwq(a%%}7f2C;v8|vW_ z$zXUL!4Ywa{?^MzDg5i;#45aH+k*7Jv68W?zcOug69;YUnv6BIwZJ{(=|6<9jqSE# z#R_}T#l7~jO$EzM583~IfUC&q9PcN9xasTO{s#NscO11Z-oMwjE^o6n16>aMS`s`V z5=gj&*cbl?mpSf*M@R)|0%!<56HOEwpm*vowj4^|f`q?oE0X;N!r>B_h*~0KVEcsx zq)VLN-MDSgx|eoX0pV4EXH93-K2CQz!UG#EOg>Tby-25-*QxQOIShVYeV=f{A zj{BDB&@>p;$A#rs3VQ=rqV*`s%*?DU@55OYG0sIX<*)19;3TtNEdrysT@on{-?_E`hht!t4$1zC;| zz5n=JRhRv^y{R-maq1@k0VKd*8QEjSue||C?6l1K7lQ!c$6fvS9Ua*?Vex$jhwS&> z`C)s{yT4#7&gFMC1|Tv!TGOPzn+q=Hjk6+NqwW=VoPdUC3^^o;kBmhKY$$YlYi76jw8m6@gow@ z(rAJufyPl^8{Nf^`#!C4qEK2pDy#+MgR=GAZB6Oir@ZoZq|LjO$b|p|>&bwv{S5ieWbi6OAs&?)paD+w>oe3j$$&q>+ljzji^@0abwM9!9S zbE?0u&ThPG$i8sz9((SF9vkTG@cI?!=Ip@#_Zv37^G0h~+i%&f74$dMqdIn{biSwh zsrY%85rAe616$hhH7h^#{~#8>0uni7nKiGp6a(ez$3Osay{~Nl`MPh}%dh$iq)H36 za(lNOoECd7fEUG=4hTR1?nod3{`!_xmTesb=!FnO_1OaSWrCIqV*5!)8al|=w#I>-6I1POnkDf-nrd)-Z05CHc9R8a??1VAxjQiZs3j~XO!l7Db`Hqjqb zU3RkH59I2xV;q^$UX#s}$02e|6U`Vox~nFQbO28>mVGfyz^@*1)L2Cr0Z{}QK#swh zWNTK4K)s-}Iw`0|=0E^2VSGb@gF`H=vMk4za7OxL{{W!pciTBzd19@#BUuh;Nw5GS z;07VNG`05FcIL&Kw~t!m_=tV^j+_mH(9h|sx5tNO?ZaPs#I_8umB^An2>$r4gEszw zYi(-Zr>&8*UAblJ5aCTm*H#M986)FP1p0ED94}ac%?Ja*}OE)dC*1kqN#(Q-2Vjsy$6eIwD!uB(nwEovV zf3}$=Ld!Cz^3D+;8T5DbJzRo6twpIbldhi0vV7fAk6V$4R5BM90b3ITh2b=h0EI2% zoO&~Be<1@YA*QOTu|~hD7nWeJ`ot(FEen)uHAXc}HR?&0P=k}ae!!tPNmYHS$27Hm zF;PT#3R672OW^4f(-AL+Gm$voUzMSAGU`d zEZP0X8f?olJ*rx2zrn`O$8t+8*#a^`X7$sD1fDGf zz{qJ-i}O~x^Y1M+JI%ndf6Jb_^K_X$%dEZ(^e;gmaZjD?_(T=g{D+T?+VB6j57^c3 z{TJJC!8$w4%d-oR1hMxjN)*C@Spba=`}{%#Ori$%_nRn_6MtbB00bbRUqk?~{gOW8 z#E;C-OA-F%nmF(yK~YkfWLn}1lU%3$LYUehg&V5`f%6Er^p5@vTHn@l0A>OyzOKPm zR2X##g<^&n-W_UBlCk#=uBwNJ1&<&3t6D{UYUEgB`PbTO-O)ehQH#vv7lB^A5#vVS z_HgBmC5FfN)i{KSs%z}@5t2DQ5P;i}2R{g$XN%F>VM}z z&hEVFn7#1)8SCor<68?X1IP88zB@ zo9pdbUMt?Uf6BJD&ROg15nEthmf0B^d1$$1=04g$8I_%ee`#pBuCvUYi z=dZFo<6wAl^ouvXTny}@1HKS|v-G0$u>HAKSbr$L*7^WlFoh%lN=+toKo()?pp5GP z*d@!j+6y8O(yvbM1Of#35kMW{HNu3c*-~Oi3M^Gd^%4%kq@J#3KX*`~4i#h%#(jg- z0u*W%iZwrD=>iv8wDh1{FcEnPL{x5~$WQjFyXs8<|NmB1&Ce~N{?YFw6GyFE-Jlv) z0XwOH{1wju*h2%C5Zu9EQ3dcy?;HdP#Olwm1eiwZujc5apqHUORfe!V(=79d$e5`A zg!I!O43=BXWxMBi&c5^2<95~gW7fTV5G26-D07L3em1xOUlt%Btdv0_xh`9GR+s(q zc}K0l{edq(&|;gHrR~nT7P~jI+RmOEw$Az8wvcY3ju`w*0{{RZ07*naRCycO&2CZQ z8mnIzw#>3iNZ&%9s`OLnc$)MKsRd@#Gp$1BRL1rK{MXP=Y_}kwt>jn{igz>IGY?t$ z=wp^%vIaL0`~)fj|HF?Rus6N!FYSSE?XuP9t+0JO9+_eApGav)oDpM&e%{)OeSBwC^iFJLJ+8;0^O#jA(AKevOJA)4CfILMw5)^*L+gvtG;iHf!T95MF7X@A87LK#lIw<6L84vhTVeT^ z{<0MZH-Qv1;lm{J`KH?8Ose2@)p8)j2=Y4DIcAd1EO^^))`lwMDtXW_aOE(D>6LnY^t68@9?K(YY^`e)7A-qm$$y~XJG zk>y_nJxdgx47B@>EVWIZDiIp7c#+qy5%S9*;9Vzu)yLd-rj()w6e5KDWv$3#0bbJqOQ zzasfSXwXjq5_pCYfCiA+l%KNF&F``D@C{7vHCCA$w+dT0df`Fey{nW5thnQP%Wiss z_;U?;NXM^K1b)5Icg4T^Gn;(y7;FAs+Y9jP6j_X|$?uvUU&jNi0$8FryO`nlXqrLS z)*pnPxVrEY!gYv5<>KvT$SF)%Z9(Y;8X*8DI6#^X6*-kAjSzC zklXz*J>31&*9h()+lM$L)yk1bEsdJddMs4SB~?a1ueQr%dmn@x@~DGznipb+i^_6^ zI>*+a5P*<@9vj)x$D57^m)h%o>$rXH1NYjhvoEwVuMnq;yJ%V~g9Ip4nj8rj$heGO zbJu!%+piDXmbJU=`G3<(Mo@hob^W!TSKI#_%G&zrn?VBWZDHt`J^H=vwk7=;E6&bZ z`)fW365yhd3fF}D309eRJ(EX)HQLO;(#~6~c>8a0hvPgtb@x<{jtMC~qO^r$# zsqKjyEwlR7mTvD0Bb?0K2>cH`yvNS{zus;69mBT#>~1Cv!W==b;`u);JN6*;PlSGA z|DC00OE1^y?7x3P+t>bqeUuD9>|>Rc1j6I4fvCQwcoUC=G;rp>D*dO{YMM6>)1k&8 zF8HRItVM*1v-J(uHG0@Cxa~UI{Mp~Jwrf9P+35#4roP7NXCJpzuHP!H{Z^`PvvM8V zp!Hq60J_BHf8lp*>No%1<}bVwLWSY0r%M9)HV)c_KFa8PadWKuI`eDk$sdH3| zw$MiT%g=QZ7(qY!JCG75n$cgT`%ys^A$x6@#>{0S2=yjm`^UHrtWS(dZW7`rCJ6=n z(o%E8Sr7*)fFr|HmHkmc9OmJo)v~6NJus59M{gOo7hHJ4+7UFD^O6Z1B94|;%tN6j zrBBUK9%0#jTe+^sUVHXF+jD=Jmx}n(F{cMVn_F!cPET9c%mY?z>bBYaqc&f^j_2CG zZ3{<_Tf@c|a90GmmMTq~s;1ZWC+6pwlmR3i!Rf5xtsl4Y$Q=OvAmZH_`UWOiYu_o> zVLYBmfR!irVqal(Ye5pa8$d^r1AUpY`?%zB<(vQ1<{mz716#Z7a0Gr)TEaE?-4wtJ znDG-3#|t`XSn3QX!(7TQslN;OBoolOKOg|#YbL$iN*nXj&^5O5p-x`%6*3A+C5HOR z2N9mTy(0WfL-m_x$L;((zhW0$^J~_3Gsm49r!2L4ou%8_VLPYcCU`plL06@~xgA6kCxcFO<^F8QK8Ub0LTohbLi9?eC6#g96KD^Apk7wwDYV*FFX zHA0FfRcprX@Nfd0O;;T3iYNb=HUK_AoP^61ENk1Zk=+qp-PKFXN?4MqZ~?u%&{~SI zDuBq+?0@O`$NIT}3M`p*+0y9*7_*-s^$a2a+OEb|#*bLx8@~#|-Gm2&H$LlZ zzrxDA`l{P96@)bGt*}JcVTIjyT4v>WmTu-HUgA9T$X?t2%Kv6_j~=)FEnRj5Hco5B zC~Q;z3IzbW^tmW`0De(^3IDPj5zRJqg(U##9QXzF3E&H1MB$$@2}=islPhjDBd0I> zpnWEKE7Z1VfjuX$c}a?iod>~e*?Ffu@1Os`R(|mVmTd#@SFC5fucN9nu#D`4@bZvI zS&CPM*_uW-^R^vSe(bP~{oh}->GL@kA$fxu=LPY*XjL}`orK{EUW((YYFVsi48n}b zWlGhWLL3fHct-yaCwK?}xxapbm&X?<1|aw8AM$WN#+-P{GlmOwN{-^}J^uA9v0C-q zI&8nrb*Rk&_!X0M0KawsDv2rgyto7*098mx!7-!Hgy82bPy0K918pVy#=Wrn!w2lr z^I0}_ZnDbkA*K-5guOw`zbX=-2Uvr__gOPX!!JL7!a7Pv?ejOba1Nl+zQT#o^C!ow zbLvqmwshLa!^75b)<(B-vY>UggH-rp8LS{)_3>;+qCOGJMY84 zY7P1QR$jHvGA(=t4ED05XRlbC`Z5vbM-Pi=8OnFVEF->l@`w%p?)5ft`77CPrvDUC zN(F`={A3SGfGSl5NbHUzKF|AWaS6`!ayJGKcJ-=-Y%K5-(Ue5f?dt zIz?Q7(1H5SIe{fbyYBi%TbkZ$mz)ph$K8+0+mJx7?x{^+7eC_p%%7>%C3^EWCGga&`&@oir8DyD}gir5>wQ)%aMdb|Pp9 zrDV93pTw)`7sHUhRe|1Nkr+zPu)4pBRNMggCvzA_$LIJS;H-^sy3c{1h@$?U-T{A+ z`ioA8P?td%bDRV4Gg*p@cKD(IM-ZADAOW8jNqgs64)pgI?Nc9Vu&pci*yio+EJJxy zU|#Y7#Se(U3#JY!ClI5wL0g5J?c8(fY)kJW_POhtZJaMTALv+ZXC2>Tt(Bv8VrRWI z_GhfSd(!5Qov^yTwKn{o`+2?i&#ZOx3oYHc((6+tTU z5Wq6}73vS$RzcX4f&(baj%GiO0faJYf#)O22p77obl*SPWA~k~yEDAC$G-T419_Of zfm*8v0Z=Aa5aI#&*aM*BFKUkfEsZ=OQ2$8zg$$&LEKHvOyCBV%0swnhN-!xD=HalZ zu&B5+wK;=c;d*Jat>9kzYi|4_8+_y%%Xh7&Eo|Mj@Jx74Uji020SSuhfl_%sTrEzc z-7Z9vX|(j@0o(u9Yi#uSuV#N)>rqupbxYdnr3SnFYAL>=670$;H1@<9On2xfXpfI8 zAP}`BhQ&OBso%wNNEQCQY69w*j{us{Jc+`~PvOzT$~9>9T7m$u#4z~<$}eEnqJX?8 zz?TLBcBLbda{xjHtditWuzlvU zjW)uQ?^E0%S$Fii+)>EeiK7d)j9Z1d(hi&3`-tURR@?OLjBolcxK;Q(c74_;N3>ck z^I1{P00Pj60Zf&-DOaT3O=(TN|6K*y{EWQoI|3SiZb2{4BpfJNXI^%v`}3q6YOtiRU%NqR>B zo{zE;B1n({aYUY-Gf4b2q4Z6FI`R_bpMdh8HNMAw;l{UE_sD%V%ivb>BUFYZN`uZD zP%$c3g3Ixb;|YmC^#%OSU5E?Fau{fCukCvAd+p%!UuzAJFsJL3Nn-xo@aZC}lz>wC zMip(I5=V3^JOX))D>H^`3ZASKLg`6>47d7^*UH_A6MJCefysob*O>C7qKd0AnFitS z8k_MKeCz2$hv6i>ra}YDD}8Ql5@Ik`%|xZG+uB2R&7`WlSGE$l(Zs zP7KqQA!eevT_zT-?|r{tc!GE?HgEvbQ{9pkGq4P9#PmMULO>dDCP0cZe9k1l%Dgxa zi^}Xh0G(Mey4QaG=C@n>+(Db?ImO(j6P0pZlaJ>`?g9-7x&$;{O;uHXs$8Pv*3|W_KfFVD zFcl@bWsfTQRnrj={e*C$-Q(l%?k6Auzs#ViGZho{Rw~s>Pp2IR(T}sXpV2tu>C_#I z@==)!I?MxN=s90c*PFh zy}&mPd5x%%gB`pnQQ|_nDDT?e&a z#z=D;OKW_s`9aIx*T@1Yf+(M2bUFa&)RMHmBp^ILpSGUdgk7~{-fkRewL`Pq$ODkZ z0by~;0(?pBwUyMsAh!T~EtpLl4{Ja;r$a(vy$?bVl_x$a+|SPg5MGBL#MvL~tcUt) zmq2j@$igP#4C0Qw7#f7>qI^+oF+yVddle|hRSEg*lr8HhAns!UtTOn5(n z3{ucrf};FU=+~IqZ$llI+w~W|-Ey5vs4L5g2DSkK1l4hIf~b+6WiSX6ctt;11XL#} z+#V-JtAkg`fc!-H3lNeL^QnkEmCxJ$(Spqk z&D#sl$=J&-@3)t3Z?@O1owhBR5gR%*Z8sk&`~2vv1G&QiOn^X^w-)T{H>GW9QfJRO2T+`{qU4!daWeRj?Jn(blE4J_vjK=*+i zR=>2#diyxaJeje%5yrELy6wpEra-5)t^O9{wUsU5K?)(?#er0*&xCpgmHwcQAhMvefSBVe2nX4MG* z`#AL*f{i=|RzF%u*%6qc!+cocP$6vxOXS0vM6dTYkY}B1gnb+vt%nl)#^e9fwjcbU zH7^|HatPa&?DdyL9h|)f_%)`qr%YQNIq}^9vHdLfeOZv=a8NGI+xK-v`{IT_vdRAS z)=r!ppA4_#uDgVd31%ZNDlABd%KJ5X33M030}@CgFM5aSxOWm3^QxLPk*j{887e`| zae`iBiZ{~HW*<2sBqJE&QO8-vasR}e9h=VEC}S*kUR9rm+tWp;Mkuk6fH)k*+iv%4TxuIQQ_wN;xb?5^@Od$DjJeJ^ zmol3N)3+9_^CFf5OYR1VoMUO0xS^+?Y-|XA`qgQ^3!vG;fL6wjS#i(p?Dyj=K>a0Q zWx$*z7CIOEFN6RKr-`gC2pvr)tK*p%q9=;OFxzOp(bhE%*_XGP{m$;Q?4Idnp3^Sa zi77gGiukZ!HdwaT43unrchP#=7kGrDY#mK}G8=A;OML#RZa?kE8lROQADgVRxspEh zT@OX5r;G+Wk#FW!VUsPEi%SZki7yZUM z$zSynzzcX4M{X@mG-UD@(i=(uKdX5_W4vF8pxksBN}SNLo)&-@pn%%bU4Ey3cw~le z1Hd&AQ(+>&z622aPkPz4?H9V4mT8WFNF=T28kL>jQsEvz#$NJ!L-v_>jN0peVH;fB zQd_osjs4Q{L3_caN9`LoKWgu}cGT|LQ*Uc}k?DxbnPbQ&$k(Y* zC_e>IhojhG=~zkW`0xnwt6MGAaH0L;>&~~2Pv2|*{%x!6^Uu4~T5maIn@1HEm?0XU+8Is&2(S~NT4bjG66d?!R?S(pD=C;aDh(k7U)or zUY=b5W6hRwHceS$`BpnJ+h+Gp_1MzK?zOE`p8)t*5TAPtKt%~^CSjK-ye7GT&XE@o zp*4R-Y(Jbt)TvAZU$xzD`x;(kU+THYR`A*Ix~3fO5P>jDvxot{q`KyMTihj?NeLC^7F5Vf&C{BmjeL&GQBdiTwH^$ z1E+a4xIV|#VTekmzF?czHP{<|3C`@A@7Wt)r#B{+P=_2Ja9M4yd+mTd|B~Hy?U(Mc z-});g|1EX4y+395@5$KTe6Y^`;$3;TF}^}f-Mn+vcGX3d<6klw?|GJ(>C6eZ*t~*ki=MGHSinclHVDLFc z3M`dd63Qm<^t@eSjz$|UahIEqdZ|U6($5#&xh#S>*uVuaopA~8MkxNJFNYI z5AoICUWRGGMFTp?SLCrlvHpQ_11dsX)L-vJWMJ$4DKV(NUs=~pH`e*(?6iHp<2P-z zZ@u*`X|blxR%>i&WCH6YB9Ie*G#kZai1R_FuuGzXHH1fBvC&fcjp6PSBSin`#&krX zL?@|O{-USq<3LZEAf#kW@RL@FYPZ(>qFJM$r0v@O28e4RM{?T_CTENo7 zBeQ%COi!viNO>WO<1kKvLLNc}njc{~uFS|Y$yeKaWpqjcB{iA`iJPdfZsgVzmqJz8b>t8O~Cf)@2>Q~IpUQ@KKXN%Jy zOBE_bo%lz4$#_tv%G2(EO)^P&dANC_ox2gFGk@G}xPF215W9E@Zbu3zh7%^#gUn{B4&yF^2idjUQe?XIKfS|~v9)?;T<&$2z&Z{jwaRACid3qjL;uuTtIsx0?gfLL& z_`OJ?3;%l@uSk+k*?1|L^rs?m0VaGh2-? zCuHw!h!s?O)X6H_{WxZxt{md3F;AB--Dbb{+qc=C10(j4+c(#nekE#I}_{4(Ye zOI?zr+Ou}_t7b#5+i8QZxrn38AGgxjS{}xJZfKbIh#GnN)al~@yoGcQTUv8BeB8oEN|S$ucx7L5fPm!IdJI2>xhXrENWm=xlGtTt!P*miRcL(2 z_gSa&G&K3D@B9qro^9c#y=M3Fvuu%M{`{$*tN^fR69(=Mx?uB!<@9u-P`*9A9fsZdg4{nCBEHN=1+#NfqyjUp}ob)sM zyXgvd2aqQXT(V4zIM&Ahr3-bUH zETQIsSp6btaq{&i;zE#HHZ)l0))s5&*BTirt-jaT2}5WJ0YH`++`W zLyUP@Yx8^S`KbOTO$BbdaITY1WicC7wZ-@Y+e zXgDDW`=lhRnbSZjZxV@hm+8vQfD}|&2Vepe?f@-&;+CZfXB6sVu6WWKe^Gx$PQn~R zd7i3=gR5s+pe|_+2vvI1_QAh9Y_GY>tZ#r9or_b*huC4#i@`eKhb&>)s%5+=owMe; zL-yw%KrXnEM@2S5XdpzPVi?{i+N3qA+c9aokYP#>jIc9MskBki4@9DN7 zUMSvHdVsqf9DpLazbDzlp{H*ix4suIx7Lcx0HXi^AOJ~3K~%LXm~XqmM-vDHpF@63 zCND7bDUPRGo&JMB%FYax;M6PZ(dh$!R*8dvk)9g0-dl62Z;iecYt5WvyVH+k_-tw`?;k#u>3riaPqo+ zCzE#wu)Cl9(YhO6%FkBAWiNC1ql`JR`=I-4g1DSQRbUpnlwW}Df0_egMbRL6UrA^+ zA*7(OBwm&~5bQA8E%oQ{HR3kQY0Zz|PprS>2bx4-J~O%0Ym0L(@efl%VL<~x*wrN` zX#%5L;Zb9y4F65iC;8wfz>oRH_;QQxMYqhDuS}(pAW!cvD%%)O{w{dMLjYV=WSGEC zD2xE%48@TUHAYprvB43(PC^9A_teUIl7MKm4AZhM&C*R@cBVd<3yvvu2O1#Clfktmt48dKKY(QcIyLuc1Pn2AbuwTkz?+b z`Ch>cJkx>iJO%*35$Db#&rec~@2Uq*yE=VK09BolEgacxbD#fnsCYBN6j*#Pu_(KU zgKIFjxM{J{LZ$-#`3Wd!SH^lSXtA#KO{^S{io>jhi2#7m@nYw-?^}lIXx0QupfK#@ zCjp|cvtwutQl$8z>LMLg${*dzC)g`-89*8Vbe<1WP8}EmsJY?`@`}`7`@~{x=SJ-u))4AYwhW9>aWX1z5^j>2>+BFkU^LQ z(Lb6A;3$4nSRD+bmz(6_{t83Y+PxsciJ&lgAZX2N>`&z9lsAc|aB1N!eP2h2-K2fc}vm0cMD&8svNfGJqI}w0%M)8OYFieGxq6g zctqqPeUOAP7qTOJDd+yY5$*_n^s&pF)Yk=$4D;gjhSl>nKQ(FZ|IRWypG!g=+&o;+ zL%0Yd%Y21s?mGu<^}pNBK`>q&(tU*4dq4)yV<~{F!h4y_o_=-uIe^l{7<;K8w{i;< zp0nBjrl`Kme6))rpc5hFHV5#xoZVo{uW08THc&3JOJ98r(qA2_;nWw0M9N6r%LwQy z6}W;jnl+a?PJShk*b+zsf1c36M0kL%a5%_M6>6!#Ql#vA_izE2ZWqOOEp9-^J_83a zb%cFhQGQKGCYHwD=NC3fy#+@);6W63$F06#5|sGs!4V0mAIhFIZSgtz78pgSrZV3mzOm6hTTRIs&J67;f)FnFLFp8qa|}NvAwRff&(VgV`LtxPKTU zA!aX!@d+2fSkH6xSDe5k2e~$1-eCXZuTu7f&pyro@hWfy2|h>7tu&6F1d%iTa043G zSG;zMz2+^e>}C#wFbh0i0lvym9sQ7!I9piQ5?nwT?J_9m5SUw292oCiX21KkylpzG zXje~PXj4o{SW}l>rJ7Q9obyD(4;|sL3Fd2x^?!B;M}@ykB&pK^{GKz@@${gbt60(AF9=~D& z)J698MTy}A%4{WyLc5HC&i69~em9kT5F~KO7mW-d#RHHahLj{)ASKBq#QujR00S16 z2McpHH#)^Kg7f7 z-iu+OtlDx<&d=+^kH^E*n!gd*j4nuNdFK>bwf2ZKkBDyNC)Pi<&jS>Qj_p-fN5P>A zab!S(h(xsH()emQS!5fw#An}pyvd}xJ|{EpQ82J}d@}VMyaEYid7+8xNY;OOlfB_T z+4U+qjd$MIkSP!B)MhjiOb|CCQ*l z+!HDLQh@zu=5VSo2~HWc{>_8-q2E7l`wzC;U5ziMjCr_U9dts7P4f@jeH1_H%(BIJ zFsHKcaURJ5LAg>vPrqX3onECEZx;5001$jsslPY?QGI5h9(KTlX5a z*qoFCuv$C=z~u$>Jl&oL2*tE;MAs(-dAM9bM@-=g96%lGh6&@d(`QuDd5oDWQ4ZE! zFs=+HTm}bz!USUyvFTgp8g7~0iXz*7^OK+@0Y9;Qussic@bJmS?trSP{cD+$|7goE za03E<*_o~cW>X_}Fm<8b#s^Sa0Q?kRwbAlHk!z*vDvP=0Wy*Aor`Msz-+>&rH<>^O zsG4x4b08;7acb?N{JNH_^}E8H6L^AnUIuYueTd@y5Z%#K9$Nn_?{2Vxt_If22)g9y zd4l8xyov&16mrmo9vbd>MW7bo%GcY0#brIQkxEaxkcwp^%Z(i0R~$IM$NJ9cvi6m{ z^Pn=tMk@xP#Lm;ZL6(m)g{g?hRSFjs4V_fKP@?#)RlZd0=n#`ZSS(A*z-_9>ioPbm)PI_ z!3q1=jx~0;jZ>s7JqjQ&sYACsZu7&lydK1E8Qf}`ZPe1}wUnhPv_6+M*v_% zVYdZ^^1*A&D>F#fsA> zdQqn|jUVinCWf=;8hFhhpG6uUbzIVUilo7ELlcC&)%PHPfC#i?Ag)g~5Y!wKR1;9i zm9M~{njMx1+yHO@@&ND-^x^+_+2KvKl`-)5KC@iQDhA%6$&c|PMN~UX4Ke>Z{ zQtjZzA^#YbG_&d_nDek0FPcdjg*hU45;NvqHDmfy&1xOgFR@JBx0 zS9<^oUBO<`*~mM3Ew*x?#RmEj=yEifi-`@h_RtuFO`D=jDlI8dqvDC_NS}@C9i)pswHm>9AKcCIn zSH1|~YyA&GXUhkSh(NHAm_F%vyRy9B>Xr{!ZpHKIMD1o#4ucmFn9myqz>lm$kem}> zS>RjE)V(x0%tlzFz3B~RFS&wy2SevsfqMaI;$~Mh+sJoDZ0smI5pXGi=q#h|U$xRi zI7br-qG?Z~I_(HR7dCXW8rX#c00|}%e{t#p{_gV{Y|SOD3@Gb&I!{ttosqAwju%^3 z;&hl;Jl&=fLQrSRUV<{0cn^>e#sGhx`E60PJlE>D zU!dg)k_a0;h}?nvQhHIC`H^DhqCEaD*d?G8xWsmUY`K%AK$vBg7M zM$<=1)^};6tva{W*TFjGndU@Riv2Tv$+^V6@gn!eHQ?chFhDMBtMxv2texeTAVu>< zh`5%ArjvpM-NB#0Fv%1-3=);nWRr>&)eMtEozKfJE>L80ifV`SEyJpys!Y5YsD zl&Z^;t-a_a@&tAPK(?9UazOLKcWwN{ARiOq^j;TB2fao2$xkt_bp04XA;KvDAI)|$ zhg7g@DWH176;yWc%-2e*U;bj|<|M^XU*?9lL3SYl+Nka65=Wth4E*Ao;^;CQbvpmj zCj0CEJY^r)xyGj2JFIR2iI%&#FxeB8sI?w`|!0AfX%-(d;B zKnn1+=AS;w7hGT1Y^%1lux1A13a|kD6s&QXPAkkHH{jcT#W^}t>wE@RT7teJpZyYx zrNdO}ac37D3x~lMkZZ4AlhC)B7&J`^kvdpR4G4CyU6?E2d}n)@gbXH!WR)16}6>Fxtd?n zt~9A@{2V~>Q@EN#ZL0Q|F2?b^lDIUn22e?*_9dDgBM;@2{MCl3Y}cW@kdOSlD}SKu zkVB|nEi%#CUvq%}lhO(qv?D8M>);dLbc$cSrI&SoKyNVkJrMlWe=V^2{bzT&ZsvZy zhMOJQYP;liB**{-*#e(a;FewAb5>f*N?w45Gbpn5bZYHm0~a9q3sg6Yo`wrp`JA-9 z`~7ux_pMNQeWQZcqd4QuTmyK81d5_cAOx-F{R#00Ew^GLNZ=)evrFW2G&Iz?Pzjd- z{4y-BzI!3LfDpcBQgITFg7V+|x&=G;T)tm8d9lwgL`Qb~US7>6og*o3g_hZgO6fZh z<2Mm1l}y6mc*?&j^Ry~WM!L>;d%^epXZMwD^($Iz)mDUkuw!E1{p1uUKB zZ7-~^5q3c!ar9b{*nXx;0Dkffr@l1x!US`;r+*aWp59l4%S~Pmz_I@ru-d*9PzY!h zRSDcFJIX)uNtm!@m7NsQQWio4(vA!~3kUYV9gslfC1uXjwuNjD9|t*ZSKj|6`|R@n zXkGJ7w6(zff2a|qYb#LkRhG0WABzFNO!d;C4H4RBkMruJ*VgT}UfGg;(P%4wdNX=T1i}TpxkqWn_RDjFA@s z0Qu`KMIBFsDXzE$y%i|s$WeJJL%bYm%fv0@qFtl9wkGS|w!&KH`fPIlu#G;nk8z@3 z=m_5x0KhUV2lUaFl(veO7wtozNZZ-lXZY%GC#P3+2OI<-fpHq(mmEPt30*cQ9mH(3 zhSeAHx;uirp>H76<+2;XDb*qAH0lQzi&FyztpKn=KIB*&pSPu}8||-tYs#+rl_hpT z*IMh&?zRcuy)4f0RC$XMNG2uO1UDELZsU%@&vQa>l`;<*^7~Yk&#|YP$q!2}L6;DK zf8J>~hcK>cvb72D3u-tUN3XDVKhFs~zO7c!x}U8+^|RiPlM+iL;1|6T<@br@gDtA> zy&WdE;#WH#i{eDeuXwnt8n;tICX446)5)!Ln2rwQj}nXT0wN8fbfox+*@J0=a542yhCH zSsTaWCVq-9cU60uMR%ms(e!wVQyZ_E7v&`W7}YXE+`t*g-^)+x>Fy*=@DJ&#>E%h^ zH1Q-?a|hRWIZNP&sG!)5xFz7LYX&h=hz^mdtlB(%+{nW@0L(aUZW2*jgwm2LwXYqt z_6^JFX92RtL^2z=4Z_3)%(6wib}(Zf|6I;)|1N8Pai)Bk$>jkc6H)UDY0Fv`Xg$t% z0<82f8SS*j4KJ`v+cu~@I|o9`R8;dvht+gaRa|XRuNGlytI#V-eg=no`SUaO_Sfa@ zpC8-62}QWXLlZVTiZnoz3{J?;hj4Bsm7TEi1ovs4W_8*TK#H}Nx@(fR(fc@jan^Z= zJvldDq4Nb9nxZ7j{y&^9f?iS1n<4ZeH)}+D9?GErb)CAc>Q`|1f@6}Oqw93%82PN!U zV8_DG1eEwT;*w6g@GI}MEAP49hL{WUVlB0Wq&9?Pi-3z;up;eY{KzCr_fr!UR=bRd zVbN54*Zg?jJc(J2m*g+E5KXlV_xI88GQD2PD~a#r;W(+jgeg3f8vr?mE56?WNvONC z_Y|gc_YT1LE1jn&k=x~##=QvqVNNW%2}|PX^r&kbs`Nb3}rlh(dvrG2ys2W{3+L? zCGmnI0b*sN0ig(A`vc?}9PI+Q8-KZ-wUnKR!UH}|iK)C7B-|lDmr|hnR)WpE_|v~@ zFTd#@nGECpw79Myhq6f^%Hvy5GSwbTFrXhqk~=~Gro!d#k7LpnU%$IaKT@~=*l{P- zl1b{5bZwa1iLW?Xmc;mOCjQ=6vST?lFT8^v7JAj20zSyVg%IHHRL z@B<=<>wVu1AfXV2fS+lnTs)oDwf+e(232y8v>rwU2^5#~+U8IFk-g^Xx7((Bzrlr) zIh&-qP)mLiYy=XiGZN+{DtFgI@r&21?6-6x2V>=h}q?7Mu&n z*r&h98wJOYb0|j-zi?$&0Iy1FJ386g^DE&J%6%F=~t>J8oH~`{^sEEo4Uh>>k(3nnskFcjtokk%b zokhdyV6o1B6&wI3{fcaTWsvd;n8gzLtvwD1<)^g<*1kGv)Svj3^vN(T)BtI?MSBF$ zP)Ej1Dga}Gzm!br7=2NHtUggf#83~nyEVEo#Wi?jWvE0RE7-|U>wZlx1u1`5wPs>h zST$UcVm{RbAT%bND1mbZiUP}!;%l@OuwH)opmjcUgFSc04K{u8FW8B5Ut;5{w%S}P zf+z-Gt@JWHzhE!1MvaA*IZaq*B1_K{G3hSe!|;=a?6+~Lgl{6St(2l~%Kp3!Z9A#L zNye&|Cap~W4L?4Qu?qO3UE#G9Ty6osD~uSf{?m|!bfj0js1=6xFxiu_mHX855dnxp zd_Oxt+z9Z>P-z9z@~h3y^YL&prBAda7o_pb6GfC{j{XzyYcD>}8#%p$3wHH2jrOar zKW^t=wT7p>mRoA}Q8H%TuL9`$N}6@Ko5~iX%QNAYdf1vaY_!6OJyx9IgQM(fIpHFS zDkwx;%CNNu7woT6Q#`X9?vGcA2h;Y^-zeFy{NaGTot+_CLw+8C_-tU}0SvS+0&Yc`$jEze2(frY5%#0G?rPC-k=_lJ7VuLZV!{FZR&;Q2tolQ2nuD zS1C#-<-f^~hu3fgo@hRdFW%kKvPKOhI? z2|2O#=8vi&^*v1pIjz@3wYGhT=Ht#bb(FY@m2B) zeWc2HpGknloYtW+Ayd6SFK*ILh;hu|70<^H;o@$NyPwZuz~>lslpIaRk#+wiWxH4g z9N@O>*3dzU^c2+Txely$P_g1;-?q8y-pp08m2|K$CY_eBLE6)btiLcZA*6xwBLoy> z(ffKj`6uX9b^>rW`PFN_zCH>bbPoRvj(2j>A2Enby?dftF4-f1x<5a3b4|SH!Yj#7 zK5o?yZ3_mb29S2i!*?wdfM4KH0&>w>GtWh)(L?iEhPv!PCkVqSLfqK1tn<>m7FllU z0ARb2DtB^Pt%XB0e9kP}#w5_03Es0y>=_=m%rIGGW??Do_!vgr^pLf2&2-h|oz`Ay zx5JIyl*_j2fn9dud$-upyKZMksn?qN210*P)zBAheE5R`|;9WA*00l=4EHBE>s4pA3v zbn`QR;y3{6*qA^S!u)~F7l)K*jla-Qup944*{{BQ(%Spi`VLi!cLO98bQugaci0nv zYWOwo8u;RI%XSRF+VdRR@Ikl>Fu3NfcSbVnKm_5NlX9cg7jVFBot&QJA={l?O1Sd5 zl*5uGrAJJ39)U9?R?&S2gy?19sco&#x#TBw;*bA(8mmdofQeypm^zhSw(-F!x%ogPzCYyjRgoDjB0~7&6 z`FmWMqz`E^aeI*G#gCgIuHvZ3kSrlqBjed+-66CLvtq7YKyQA{wsCR%BMr=z%x!Z&oll?ay7oJDsX>}B4SEAzcUKA>!+I?lh> zcUz&M$L4dr#9v~Yj(px;vF`>ej}6;i-ZL1U;hC$uZndvpcAg!7{1I5lu)XG8L_O5@ zMJPI-d?O6DZXSnUkBP)`$Di+0@+DDJlAvj+Tg;4Uvn=7iqFv^qGo zG~c?^12sDFNFBY->Hv_yRhLz4br*Tj!zuqdG5++lPRLgB$DtOSHJG_K)Wv6=!vF0` z^y_IJKBf!=de$KeNbnH7#vAQwN>L6fz-)p ztyy)0Dy0#Q%2|K>HTp6T7D@)=gDyAmTqpLBQa)0c>RXS1sR@z93m7^CDW=E4U>f+Z zgL{&V{M?@(_u@z3t2iNkjDYE3)$H)7Q7YV3H020+NT8@sUCqD|&2rmu0k*xsWYdYZ zBHK_!s6vrz%t7;R0Vl>vOw_Wjo|fl$cfQ;D#%{A$9{4=x%m07Y-aJ^-B)iMY@9wql zU0qe()%!ZrXfzsWW+WjtNn<2~5dvctu^EFUB8&nD27w8JP!K`*51Bw18G`|_2?3HN zB!eZPZH8rLq*>I{Grd%Ibys&)S5?=(+`6~!@?AgAFEii!RrOXqGkNd(y}6t`nR)V@ zlY73$%ZXP`@R5_b@}EfI@*9j-srgLUNqZkMIy_`Y(&qsl9<8SZ15?W)zlKc{x5|Zn z7D-wfS9czMQe6|_5mqWkxw#c~GhT23Q#bbDZB zA&A3O0UId`!#47bn`gSQnuP!WAOJ~3K~$JLyjr$D`4BKLro(vqJ+=dn=7_o1 z$>p9(3L*Ebvia%${d~{j8^Du%nUMJ-KKa@3qou9_t-ns1^a#ER=Buj!%qM2;I#wD(~M%8Vui@SJp(=ct@@zQD6`ok>5n97M}`ehJtFs#m<{``!ERHp_4pxa*Ri zB;k)`wGFz~p^p`4`iacD(@ok7qT5Fx|Lbehf;*nV-fkyC^cqR}_mzadDjL!esfraP z0K?ulbEf?6m1oMYoH$c1ojj4;ZP~XowDwzll6H6!lh~r*Nqxj_IiR%yrauF$el^@Ob{xW~L=@ZzKVhju%i7`EySD1W*T)8i532!3e@dRS zAT}CARM>s1Shw7Jv}}L)K{K2dT)xW09KxSo0Ngo!w3L7NAGVfb$6iHgAb_*?1M9&c z#MOA|1;D?~3BbR}To?@{uynF)Il>pD4&9w|E#{L$1}y2n%xA&48FWEO};f zG>qefi}aCTjO$(RmuRzGq+vHL1hDX3%B)O#1Q2;JqIayVF&vKBV8>v(&djRn*Mcg5 zzj8K=Tm3iV4t{X7Nv8FW1;}*m)yJZgeQLb;B!5Ada6@{yuu4cku=-BSim3WmRMlS5 zZ2k&|=}9CSKTZ;DV@iLSo{l^cnBk|U(a=r=V#RY~1Fb>V@oTozja{58ukeAE`yYIq zA;Ye6Q;l-%+;SdoLSqw!w1@n~0z= zy7af>u_wyh!Gq=M7rw~p-)jgK!vJ~*9!guKC4X?sYB_dkt~~wpx$^#RIL8FveN4c8 zI%PNS7GQ&J`V^bhHkilBmGhkk+z>Q#o?gIR<>u?m9jK}KNW}OGlX%qSmIod!*FX6w zPBiX9@ep51%B$e?JBqWd;I2f~O-m4&y4qm=BIjooUt-4iVKVWRnXjG#kRar7<=I~? zE6@B3dP|St!MHUoI2G3feVrS8{HVvY!cRrCa#C=a9|ZiTM}Pvr3SsM$NwrLwN-ALN z9U$N%t_Ihg%1Df$(g%}}Aw0-In#vQo5P~G3&9^Pxn@r&NA&-5Qzk=b{Bj6#vF2qT= z;mQUe0|akLbvQw)%4xv74@)Mji zJ@ie#t*p-NFBjQvnl9^Y5jRtqK!<0gdiCotJ^z&^djgqmmp*gj<=GP717# z_~MoyaH#j?i|SYHRrrBd2|y3SJO9`vx7Am1+&Fc%Tzd8x?GW3~$iUKti{-}Y(_AJ0 zzB0dmAIQmzT_?s5mT7kP-m>%k?<<#o{nzO+*t#;)?n(jAvRBLPAC-@PYQFsL?>bes zA9$kN9I-T$F(+YWQ2y4+oXp4>UT%Vpfmb({E|>Xz`}l^%zHZnbsy!S*_bAIQP-ow0XfFf%7X(Yxd$m>=Pa!IfcIqc})jD)8q+nG~rKvT3-A( z>B{vR<-*g?mh+$e0-J4EQDKr(!JKCQ!wd|Pm)+;xbr3jO4^a{jebAVYD?9wtNF`A0r83?PpDIDF|Ua{*?o z5sYibwm<6ZJ;M^`vslf!`Nj#R3iuAh0}nFp=M0SVSc%8mg1TEaOqvRyp2$~(fDK8j ztX{B7cEbxxVp7}9{@!0-9R<+RT|M@n%KGtNF4NnY_~V{+Ys^hNj{mJiFY9zCl%K`w zLY7LU0<92R3A;z>EtoS_10Z8em{o^_mymYX(j%yT9v+IZX1ZzcLDJ)<=7J`bSZflu zc-v$2D){6RzsVVKJ@l&>`frn;8c;oj$z#{lrAs$Kwcd)+G1lqrrVC*A7i0#8a2U{6 zt$NsG)erXI0e>4W=REs0=RZ*wOqS!vs^_%T;o|pVJxFK zgb_A*K_huhxcGYBBCtJ=;EjR+#>+S_{>GQe^;b_KV2suI^Fy58yPvMNo2Kx){=%_x z@z;K>TzQ(WJ1sJnm*=2^t?bNR4*oc+h?e&1Fed}Y)EVDu#mtp2J;yL=&D(nR11E2b zl9W^cY2d))q#zU7wF`qkc)cKWcKb@%h7uS%D$^Zr`l}^FTqeI%2v)u)#L~YMt=iVEKN{88hTmdDsF4Gk z(RORQOL`zT+mj|oeZiR>V&XQUyrVH4^W)1mmLA=FYVry|bx;0!Mfi-@U@>$tKB;UX zXn+-sh;PlC-_SGtITV5SDo&<7q=9E9NYj5L(;KuFCr+20fAw#c`ENw{f9bQOeDDvW zobN*5u4aek4Bb`7n77hqz*x(#ljMa8J#@y6#d`C_6N@jy8bG&O6^T!{W$X&XUWAi; zJ_Am|t!u}*D$P2asESh<(@|JzufTZn0Ls8#C2__CMyM4gfodl5;9+|{TuK#9r(pMGXkzGIQ@H+wVq<`a|G@?i=V9wZ0h z6?=N&kKTtNsj3CQIO;- zbcM;KnLM-M7V;3_Bn=_+7PD+Xk}j2bu)H_Z+55f4nuJcRFcdoVLRmld_t~KEFof{q z2xQu>I$B+Ub?omU3OBtdw7EfrcbJF**usxd6zYeO<0vZMxokLqFbM9l41K!sO-hP( zw!jhoS_i;_S7vAok$MNcwDIYd!9D5MaDWac~e*UNilA5i$2CP6YY|eISy2<(H(UapoX>g@FGLB_)hq3EYVUi^4~av@c+OM zmK`7aPSU(q=9w@p-|_p(;-%|6*Eny#l4Ho;NTeXjZ&j%3yW4GbZ=cx@Z^j?g)@6HY zkAiXsSBpoo=}}C=#gA6OTz*sWNPoT$ z=_C}xfM>omUoM|}BiFc(Mx6Syw~$O*UM%)pY@B=y^U>dO(KBE-FRKnHWjhaa-`BV$ z7-8WXf_vcicJr0_aL7CCgR!8NMI@vHx};?fq?{&A4-I`~CVJ}2M?sD3>(p z>fW^K3@9ymU85)C5YmG%-iw!+`AQd(r2-*R2+sb0i8G>=REuV9Dj999i1aecM6?*;B~dwcXO~!Dy*G_GQ4)Md&SfXB ztegM(-wcZ7vhaQ1Q?`ENw*a$NmQKFLuE1|AM{aH@mrtH8b9;ByG#OLOQh(lUAU(~h z!rD!@#)qHbO~9rd=;jdK5S@)@!>|d)qlc?BbSNLTY5k30$;;Wy%$hHw%&^CH0_v8fa2 z!xUZF$=u;j{OWA^Ur$~tA9w)e%8pEK0I3Ss%qLx5C;_X*o1tyMGJ`K}^Fr@p+fi;G zI>vVpFCg$L0Cx0EZ`)Vq4xB10ry07?8yk5&nLXZ0q~H!EOontqE4vZJCBfbz7)YEi z!+d25pryNZ_NB7+dDi`R+(QBY(Wk5CD#U5C4uyAK^36?c6i=K(Fhy5wRiK5|6m83f=rGYFj0nx zHLZ;0jnF_0HcrxMiOH~Yoc#_=t1M@nscGm0^Kw=7h;`zP#Y<)V1h>FAXLt0;GJWu# z2T|X1DT@3~ryDav!_-;lJ5%*KDSkmfUhRqrE=W za}ZR*BXHmeJi$>W!h=})>91eh`rr11xy?kwr3}PR59>g;eBe{3{z1Yw2~WISmQM5K zCddCoN{^!_Lb^#Ef0gjU(W3}3<9p|&dOfIsQ6yGjGUX7&IVKc<$FmR6BV|FcoPE_x zLZLsyfQ`l1TbV4EJVIPo1gPRM`&@`dCG`~WrvaSVGR3vxbKLyPEkx93#xm1;3p=*U z${7#D(MYgTkc=oa=G}LQP~V|9mxzw0u0^H*`ijg~rT|*ft6%)3LW6|@V5by2(Xyo% zJ&^9W6EJSpk-ZT1%}R$TcAI1fH8B8V4ka>`bBhT=Av8qRtpg3x zP&KzM0{E{W!s)2qiHfx$8sY|(pc7#os7Ezu6A!-8{=@)(?**g>z(trfeR@M|-(80Z z+$%Bnz++{aU0zdc|DC(1xSCE zqNy$Qhft376?AQia(+WpT+E7?RJ#AdT2`4t6AD+Wzryj~ezY_b&+e#iy}EaA!F3P9 z@OCr}P{TE8Z}^6mpK?%3$z$z7(E2b0m}PR)n`72bUoJbo=J9gi8$ZH_WRG(#)jehF z!;hDp-~3z4!hQG9%F{}*UmRBDZac<_bpJ;Tt!DN*G~lBcAN;N||Hr?+Y<=pfGIzwD z7qkA%QZK*sa+x~)N}0R=X!-eHx>0`T-?>%}^PNSr3Tu)dXf2JQUH{x!HeB6SUg2Z3 z@Prw)4guAk;CKQNxCW2C3v3tu;G^z@s{(JFuzU6EVWy_Nxg-3ygc%Nxk!L6Ua?Zr^ zz;yCd#{U-8heR`pOro~(bQ2=jIH2QlS$y^x4(+hV9%ET-^;Hlm>^jVt=C&s4@lYwB z{Ni-^qwFu(zH2Aj_F+aRP*Z3NUh`~%8}zE|31nlC-x&yI^2%JmECRljkC-fe_41&@KJX zW$Lb{=y7sTg)6(q?$BcR4;i;TDA%ol2AOFnmH>tC%lZMf0Dj|n~;G)cq zN(X>s;zrjRC2>0fnQFq|$WTEq0}{2y=eN0QKnvc4!=vjN^QT=Hjd3^a23CPLB#J<% zJ(e)1a{$wfzjv4APn|CZe*ZU?`~ItsmF3rum-#0@Qg%N6NSWEU7hd3#)mN{VDLx(M zIrX`NchjP9aA)UsjtuV&b4;<1eTEZ*Q(OWP4a&^v>V?x~?b!2WfiKN0a-#5G|N9H& zkN%sRkt^G$5+9wMnR~- zd1H@&8yLZ@;W{JKTAFgq{(KN694{ zuSVq;pJ5{Q(qh@M$GI5lCyd<~q7fsD3JCg$kBDygkZ!n$zFecZXhtycWXSSR(uigG#~84?W|c>qe`nWss4xfk_4eSSgy@ zV0-DoR)d0|!4X%+nly1Xn3~Qe%ATD8zT?8f*0X0}2*1T5lbLtkbQ_xkh{}ATnq{0n zKX;{SY?!q%+dIUkik02=zU`L3jx$tD$!;h33Ctk^h9#7e=UT}g8o?#rHteCFK zf!DR?UMSPYUrs%3@MYc+Hvn}&ioXFFP?Z`9g}hRkzt#&FQ>Xip)6=g{m-A8b#{Tt%)BfAVNL)){fzoR+m%8OJcd@L$-?O~*Sqyv3*I%I+=50Y|>6lbLPEj>>}} zL^5lJ9Udz?Dgt`}Ry*@)h2!=1_^L6}U!M8$6ae|KTVQm;*?#lh@LApn5CPgVJb<`i6lX>SZ7`-^Ym1l6kbvrE z)P%>P1Eam7h*J-{pSSvLg7v88C-xTqRx}-my;mQ>X|cT^wP6s z>e`j^;^L0-&p$s?{>I0J*(gsQ9C6>hMTOZ=E;D@GewOR7=DZS%$v*|p<5(eRBbH2G z1)-6szrZ7TMQ4ej+&~lk^0c49-ijdO`i;eD(sz69nrrRsPguU-j=YL+>ph3c+ozSu0p_nNg=R-NPIJl0w)g#}AXD&HQLKwEJclx6Sp<5eOhF0=?sei= z66v3lrWR_VOc65DxAnK))>NPhCG)pdjfqoC$@=XihR|@&E zP|Ul)%UkYZnbb4>Qw#y7S@mJ{XS8vJxdAo~aT{_yTtpP>UBTxuol0yIVY!#dz^~MN zc?zJVx_bOGe8-%fNnTFCWYvbPKQo;h&SWx9&6iO;GaYSES;wA>d;McV9Bc%|2cb!; zufqqz%Rtr6t3?}n4hGoO3qUZ|p9U94lJ%#eiDlwPoXVZ= z1-gn{sJeA0VXTw0opt=u3yk$olrzf<wfVJ^pIhg;JVEDca(>%Hl4*&E-7c5QMb;rlC+E47%fI zD~Ub+gwO0^X8nPO%JpY{BO7)|X4BZcfWGF{E9va_TVFYAks2pJgI|<7Lnp`bGtg6M zW)&5|=IcSwI73*+4Wg6~t=x4cBMRt8{p`O-U|=@lNywGy(@!LMwM>TT1`5t5~UZ$FuIG5f6$o54~~Sjp8!s< ztuW%M2HfzD3(6+9J}|nm)Q>_)M1{Z_t_I3%h>% zueP!ykQjNT)K@oO=Ue&~i(@44)*UxD@^-q^4sd z=eI=0C;%IRe$p@bU``?*LD@o`3oLH#fb$DRBksratHOo-Fbe(9djTwlw?m;Uw^z;6 z0<5+7Zr-~BXlaZuzFx*Bf0TRcxSNb|my>^fSdo(_++WVtMwUD}6V(}Ka_&hidtVmD zE`0<xUla+ONAzjjk$d`IlbjqKJd# z<`=)f5Ma5?GP8gEnO`Wg_uf-xA9%Rj;K=IK@h>rMTq>Wvw5$Asr?-`V#P(Eof<6J7 zMKXO2;rFvz-o2PF;Iff@e*4z4z^wHg3Sb6B;QjY@gAubZnB{FH(pu>>(6Cu#?iN^m zCVsJ|o{Wp7+ELu}{FctJU)_3y=C-220`u1S0FsZ;5(d$3USWdnJey<0L594gca{m! zS!j~maI?f$)2PC)z4Zj52$F&1Aq@^at6YGZe48&b>c4rf_FLXfnb<-r$1q-$QDhAY zMcAR*g$pCL0(gRtp#d2k3G5U6Egf5Vg`d>`ueO5~pm|j=6&5#frads{tX`PLNm(ZW zQFzxG1~9iFeI{|6hFMG3LrZ7a_*qFjZkl@!=Dk6SxFx!Ff^*Rn)Gq4y4Z1C)U3Mb; zWZITLTQms=qW*z8K|NZ6Q0kk|nfc7W4Uk4e)5 zVM@F=LpS5fjDs2MlYT~2(D7@nLujI36q>jU+l0%cpc_jFpWT91aGw=US z_Drz;d+J#>1F+rq^;c1zR~Z&E8ak0F%wx|5~a|g>`rPVj! zvE78hT~|oVgGRHo?9+_1XWZz+n0tmvKU@6;&cx5tiBf|O# zE|`R${F+U*i;Sx zt0WYD9=nn5bex*Ii`9~6Py+YCKhOYzjaYl$pxGF4i?0m0fv{Tc+1HMhWtijVPaiIS z>62T^i*HPohj$Uc(%vt16V9x@#2NAZM53Eb|u2XWpRf2n$KpI_+b5a06EbhqrO8 zZ~mhcz~$<4ygotz03ZNKL_t)*+BLqr$IxeH_r3_C019Mq$s_Ga;$}oQmvpRMW0J9J zIr*>xB)r3B7-G6G>l!$>b7lR@oK{qMKLkH>IklCY$AvdP1a$T)LmLjYZD%Imw7s^k zmaD##elJ6Y0l;-Bo7^`*vdl)378bV+Laz+~N8H`u=g7P~Hyh(ro>4~9D2S!9$zU@6 zNIfpTda7Lg<)1_Wd~5YL_zq0Z+8uxbVyX~i{rrm@Hu+h`{}0ghU#_kFerAzp;|EoR)L&l6cntxKU{kiV`nWTRWH(n_3cZR-MUhBY75?-Bgh3h1a3|dv zj!y6RS`-3%%TejB_fOlSBG0e`ONJZexr@8Yk9=l(`Fmer?H;hl*lc;t0VqNh!MC+X z=xyz1w<7omd{+W9^dM##2B;kDsmW;K&PEffvL6t7>Jx? zN1u@Llf02b1n`oR!`JH`fzW{NM|#xYkMU)itQ^Q=AT8Iv@N`-H;{R3FF8xLJh&))+ zX}p&>Z}aos6hK3=e)eT1Do%2i`Gag#MZ+`kx9%B#&U?!_w*Ee5%?z4fTOH5&$I}99 zYTgsB|bd4gO`qm@=)#5MwrB5ozxXFiaOiRyK zZPl$L^4SEuw)joRvY~^Lag?LvP`)z2<2ZZSU?g&;&o2lONoU70i=Cb|#z)K#@D~Y4!l*srj@lIj^BKn=#9P(sQ+EjWZlm z>>A9i!LFLQ8em$c_Vua&67udp??C~WK{C$3X8q)^ zXY)_Jp%VZ7bn#fu=_ma{j1Z&=4EfktLjhP2B`z9KYG^DJFR3G4aE4Js!i2UTU<_~F z_y9`4P*q$CVguC~Q!Rtyz!{$=l=W4Gzs9XN8qk0uf^16!klivBRaXS@BM;Rr2q^@V zAN`xaTO8@)myrhL;K@He|GcrnXDD{w7yR4!j{50qv*m|AxwHJ8r{@c+hGjQn{Yx-M zmh@P{%Z8pN_%qv309&_48O*qug!TO?(#XdydXIxFk$k0SW6oN*xBnG>GZI$wAMhqb zdf=0nHpAo9pm5Z2I)O|&x{SGne7c%;)2+AoWwQ=&U3hHK>zn{A;aWWcJb&cgjOUkL zKE@8dyR+tRyc(ybMR%&U`Y`{PIh8dg6zw5JXv}rZSaM$rVZKo$;-Lqy#)RRH5l#K| zE39T;DBtwqgXO>ct#2(K{j)z?uCg&}8~o~${Z6WMd5Inkw^_T#MOl`gdj2Dzar8fSt)j1TmjHu9;25$&57F873kw?fC|MY@PH;RshaSNOK@cS#plb7 zXW5O*nX(%vKVP;z{!zkFCIJ@k?aiGl022n+#u5i7UjJ9DTHIgCc~acUxSz?0Y+g~g z$!OoYt8jFaaJ80~9VkeapTN`&h&yQfjHE@ArkS^>`lENoMa@qo(BYexN<{Gb)6n3d zub?%(D*S>4zT;2C8n+977upEFg56dz`uIPU*91OFj>>eVI75SU??8&eaw2PnZ~s+A z0v?Y3Zmgdn0|(01x$Wh-H|ENp`GuY3)0`N4Y#&`aD)K73&SqeWSp}Vz-etW!*r(my z$744?Exzmfr0wjxGyTz*6gZ`hLket~&|=fs$k>Rt$?6>@QIr>rV@q>0wCu(kTCxx4q)BvG{-sat2frX_7P&pVjqS15ZYfJ-JNk+IJ zw&((7CY`s$An!Sn%uJ*ofEh2jqmfkmB&zuqC!p$%sipufec|(E^*FZ;-}j+%kvBSg~Ru{UO&ZHe|cvrYYRe@-HB|JY+ zn7mFtNejOT;ZHd32)YVT!DoW5PyFQ#LuTx2VPW14`i3rZRoqlC(dNb{%9qamrt)<^ zLz91lE9>Hg}TYLjCNGdcm&0A<7(cakv zVgSQ3X&0A_N(-$JCrqW2*>;=?7VwlZ@5;0C1B$>cthCJ2D6)Db7kCDt2cij7y7{(> z@YV8(6XYM7Qdal;=bA5thq5Xx%dfn|t-Gh7H#CM$3P_%wetTCx${psJgdtxjf^}!} zILdyJAxg~hiSq5=a$ot8fAr1ed;i4$TORrP?R=j>7%wcLd|e5pxa6IQyJ>cHy36t= z7n7z3LfP!~dJVqk z0KmA5^b%iu+Bn283Hsc4>1kF!SQkd!mRWM{fWE zSK&2v{HQ#M<#}kA{sKlphI;DKtDjLUB$m{ZZjAvUT%$lEYxRpq(C5FePG03}H2cbvcQYx)_|BVvW)PM+1b>cQd{qG;{HzezO|;cdSDG~3uP&W( zyq9dn5ifq=D9fb@jjMID+}+*Z9jL#FWqmlj8Pi=}Wz10x zl@y61Lrb^J+^Zbm2PgKj<5B+zJ^u1dR|aXFjm(2$5sOQDt6cLv%`QIxLCN*s7thi| zc&#c2GlC#jlZ1(0-^Ta9{qTw-pczl&&YC+w7q~^ZPPnm|Xyt|Shrj!=^2uL2R(|yF zK3$&tnl0rNFl(M;u?LX+R$QJe-1_7PXc$?VJ${_k927a>3aU!LM?IOPJL^hPMAA`; zeJ_B$7s}-aM5eavEURze=GgCW20(a|lV<8tV6O3zmn%Q~56kSge|@eSTYmL9hCm#6 z+IA%6d$*s6)w=;D+)UH&7@vCqrpC&#Up`Go0m+fHunv6`cD&3hG6Cc9ACYz5~~0;Q$qk{*T2=Jn|f@a&YWe%g5HgDDC;*)l^xs9mLK^34-v*t z>@u@|8gSSu*ZB%*s6wKrrUKkfe(WK+f?+wNZH58B6Q>F@DJw8COqf|dz%N2Wy{=q= zM`+Q@F6IwtU6rd4)wC@eT@b|xg?I7UFL?z|WWnnT`6v-IdKI5LGk4YlFmV~}%BeEG z_$d??vr^1#Zm?#}J&^=59%qfxGwCSor&QuiQPG4{{}x#52Y=FB^YdhE zunAp+lZnCNpNET9ImWzr@+2o5k0yVsmoAmnbLYz%3SfpK%(MIVQ+C$&=|T8aA}`jg z!e50cOx_iN!sB0424=@wr52xmhCBTp2pt^zM*$dzKQt18XNwA*`#gXJFf6Y?wLJ4` z^({ReohaldPha6nUn|T%qO_@%@s;PwV~;#u{^`H?aQU7;^zYFTd-6r5^kB$-(9%1Z z-g^Myr*2^WX|{2%aWYmukw*5;y!zWsda`VYjM9iBLk|-d8RbxUa24EC?g?NRu>3kQ z!Wj^QRT7c>C5rfD6!06L_ylqY+n{)-rWVR7s}w62-vI8;%$+HK6jKGj*yh@=l9TtB z(F4phzW#ASC?sjAytH(IP9Z6*8ZVc9(rZv?QXd8yMxnyQ*sEz4{DUl>4S(lwLt3S# z6;46{vt}!l<$1xYWY82zAqDfG(9;f=-A(N zeY^Z&YVu?GYnPRLm_L%0{8~aS%Tf!9MW(MXf>aRz;4MwC)R4hS4AKk9VNNIV@{!Ay zkJN?X{z0>wXWyVq+`hvErDycB{{W0D=Pr~LxB60c=K_+0^a89;7+)Ms*iEda>7=Pl z)dbu+pw(Mq)>|VzW6T`A(<#T`E*UyM;o-C@)h57G`N(|Ys1JUfPOvFvx|}`7_Z2;) zV_nLiYZvI#zf^wLcN{Fg@4vmb{F{Hp*#^p~{WAblz*`Oju zQx7M@+3{zgQeiSFq{W@Cq}_inI{LyZ*r8S6ll4RdWN0~griIEW}o0R4i|hnrj`)v%=F*4m)3RfTv^@9)?F093}b({?@rUY_B|3% zEwq(iESvdG*?IdHd&;k?no73j@q#8&_?K`QK9x;a@c5=&_JSIm@07-FICU|9 z=qRn`jk0u=JNK*u=_5$6YLR)`3un!DO}cP%((7mWYA+vGRoR0O0mgmxwX*9#Dc}F+ z9zp@IWGiD^w+)qfo8c}-_Hom*TP*W;@8mc#lZnFkXV;%qfUNkreK%Txw+hVZ{5+Oj zMQ8m&D?YI|z3ncBT^>9lK7~lt0XqZjFR|e9bN}+k_zLuIl=1faGW3daX4PPQ@ntg4 zY8_vRrt}ts=dH~hC;&4If^`m8oMHVR>&*LpCz}p_5kK1nJWy|P?F z<`otzBVmGuT?5*GQotIO-~SXj48O9M7Z`PJUSZoVi2(sTA+B6(Ofdn1>i~#1Ax8;psSNkCRA`zCq8V+80DsjZG zAylvKR~^+2?blhuUtIhQJjeWs6M`W^A{disU1E)*d-I7RK!#7Bh0j;KXhVSp-rYQ7 z1e-0uAO7IJ@?HPqL9SJ&;iHTZO6!F49n(7yWNILK*F5FZ=2LL=S^CY`PxF zAaK&6wi3cC^tfey%c(Hs54-p*RLfiUk8{&=GgN{RH}QJ73c;ra)i=LUGTqy^OrW{l zuE&I+3)fqF@lN&tY~gLehBf_kg@K8{H&_L~FaIg9h5=VxnWA#MAHg-@G0QgVgxR{g zM}C?OJ!@$BF*7*Zw%jZq*gIAJ^>}MJfbfs$EhtR#gkSO@C9(-!&1=f!FM;{5^r_wn z9g5z7>q~&aRJg%8)JXFo;ZAM|7uh?he2>p^-VbB|HJuSO28bs3JE`abM%;|jDr0Qph{5aI81P!VW%C4fU=+fihEi!l5nyb4j?L@QjnI#*6I z3%?G%@=+A-+>CN&9$=jhk7S#%(k;D=`!?p?6+nwPzV-$;{#+`v-}+tb1K^{dm;NJ4 z@&hoon-w6YEs+G4C>EB4DIWQtK(>;N&;b!AFnXmYFpSfyuY@nCIgeW~MWx`|h2` zNZyQNq$b36bt7bW#y>5Dq9(rx*COz?SCO8Du!hA1S#S(aEqdF8=H1+uM||Ybw|^CX z^XH`rf5oCBk%Gn{>ox@P8vXQZC;+}~PccmZe0+jyYMP-7-R_S*wYQu-y_fq9PSZkj z-vIL+Gh3PC@nbf8?u$xi&fpxM{d#}7zKf5Ka42b-`yC@A3O`TA#`Ykc1E@_rZ_3kY zV$13E<5RTavwKh~z8TLq1z_WO_To%=iPpsqroA0=>fMLyYuq_utJA+3AaA^b30u8G z_z*Nc`z$nhqD&uQ_VMiT!QYK75oUZ+*(9G$5~SOglIqDn!UH257NYfvuFMH@_evBl zPeeNQ2qbmaEDRYBfxk@&x9h6SBlOy#$=H)#M#)ftJpdlo*}Wa6X>0#<`#rKMlTB}N7)470lWnn^S4%@# zDZecxPi-i$L$tvU|18m&o=l&|@cM*dWSY=g92HmK8s3g8Z{tt+Z^o~c4oZMrm~R-(8-GU| zD1ikx0@ZmFi=vSiPFL-7h8AtGN^p|0CI<2%Ky@DxjVZW@s|R-8(}<)aZxrE5(7T(J?!SQ|!yL9?Wq zg37ST8b9d=)Hi+%F34u33(ldqy|t@;J){BndJC`a-Q{Ki8q$+SD$aT#P29Fj)!&Nu zpTBTA_AoOTVEC$_8l&JJ{QUH|HLu3TZ2r{b1=e)`_O8ASM+0ey2l$3Dk!!RD$V-wb z;_`_~eAfEMeU&4~nMG%|J&M5ctfK&|Gg|bS1B~(S-o>4aSCU+=@-}nQCV53hu0B_` z9({_fxg0a1=RCC?9*7b&E5NbsJA6n(;m%OwZVbXiJ{(GH(DQ(I)-Munw!v*Z+qS%Z zUIADrH^!_Wtuqhcge7QUDJI+zPUkIR-lmdU=({KYsRRNh05{lPIP>r~^JbFd!oNZQ zAH+`PEi?3~T+hoHPl*7xW~~(2(U^bz%#Pv4^MFK%k2U^4RYsV|wCQ)F1o+rBQ&1CY z^Od}|^dkJm158Mx*@BC%ckR=?Z;BxJz&V83wP%BlYxMRM9A=DZk>?O%`T7c1py{U| z=$@td@ZSH0t?c0AR^NHf-#b2A=M!mel-W*;fI8>Y_R$ zXwi(=j8;)mHkbWe(|1pU+fXC;3Cm9uK;;GNwF|$|TezqYipoG8KVjWOm~;r=JoD~+ zf_I0}KYZ5!<*^p!mdM?+!FG~Lv6=AHRJooWfJ&M=i%^2g*4|lfZoe8af3xtw-m>x< zGyPQlbiVnh5CbDK&^nHn_%O@dYi0XW_mxY(?3la`1JXdMb{H1Qj}d-pqw+AW`4&ao zE&+@v?%ZBS?R+wlwP_@ie&;wxJA_TC2?_l0p0hkdG zj4z+0SFyWH?Y+OOpLvdN&{65L_o1bj)m8x{0lJtJAYD0_wN^X@Ls+v!2;(L%{5W4= zA?0CB&tvLj(j%c2f8-kY5P}G|w(grqY8nk=hZ7G7a<7~Dh@cbbTQ`iHvAjaxS^?|( z1`|I^HzY3O!<}^9fjxbaWgfchr(V2Tj(?mrVNe5_4$1tHnX>(!?Pc%b?PcHLo#o(> zZDsEPu8`uxs2@LmcX^0ie)sIZmP0-3^E>i^&hyvCIc2tQ&tiG~!oKqFE>4#Rb}zHp zgsO28u@_~apM`=BxHZ1g`eUy;qJ_8G7izPsYlQq`d27?Eqy~0J=&o0_qz*u|K~H9d z-F}w8GQZt=?LzR^7&@K=1fB1R$Ce=e;utK=5oFcB2Jx$3^Y6hzSHTmir4vtobl2E< zCH`&xAu@ATHZ0WSA}0!w^v$?-@hnT2on>1T#QZ^)XKB?}&T%aZSKvorQRoiklmV6f z+T{~vVefrq>*I&Z((`9nEU>#yZcywaTJ|(b5p>|2f~1T;$vJe8+x?+m6<} z0AeebZXVfE7SG(|BIGp$ouj-5paJE~vNW_`zCJEXpSoPmum-z@IogebbLH|k{oeB7 zujOKo>kH*OerbRC8&6#;zy0A$<1!Ok5aerJsQhSyLY z7q85hUw@Vi-_IqmV^)hmu|7>=^u%WOGf}&T-i1AvJ23C805V7c3ww{J4n7rhD`_doOma+s7dx-<^;fy3_OOM?$Tgidg6Wm;i7Gh=T8FaM{3Behll z03ZNKL_t)gGh*UZBpr`%iboLp5-(2|c3b_-+5=!7SJ|kujL zm+U|t+VfQy>-X$)i)ej%2`u?6o~3fQhtF*JnKnr^;>MW5Nxk`Uqnw+2r2Oc%-%*}@ zdQT~zUoXGsiRE$^v$TKZ=lBxjFYhjY@X6)!`@jBb`SuT9EdSj{FO)z36AzVNy}Y;F zyMTgWXf?OM@W79)40LJb4dEzHE27~6!9CCvdpEHP(>z-A3fw(AaDO*Md9|PBm3Z34 z=n}9>KSLzDOjfkUxBtBJ=Ue`Wr&Mhw;1xDLfyZY2>JdEETK#I!W_WCRR?BA8q-D$s zThrDqECo*-?LNLNQO(;5TeK0Wx^#`AQwh`-S;auPmv8bd$K^7Acxzdt0ZHq|_Tdd5 z2jMCK6@aiVnU44j-21nd>z}{M8a;TO^Pv}+4~r@<<&Jhe{k-jPbIgI>@kN**h z;NoS)7JpVAmR1;68kKk(d`5lC`)Bz26tZdWTwKO|2lLJfz=%vxOzk)b)5FL*udp>z zL!$WvxOVaq%}4j9vs$fu12@ert&w@d=x08|Q1RQ$aBRH{IvS5fFNN!aqLmSV{MUEv zGCl%d$MyDuy`FiA2Iba2Cy{8Ls0;kHJ7-cCgQA{JQ}l;@8hT7sq#;LWMA2{e_VFKL~f_e4nn(&Ngq0C(U4vk)^r_C@s79e zMi(K|vq=E1;Lw3-@cO;UbU&jA7q>q+WHKZ8rY>gou~Ur`dh1s%!>EjLO*@QQ;lcy9 zT++;#i7Wz)esNdNfYcBJH(^^q1+B0>u;T6DhPChx7B_i`o1Y;~1-<1_o8c`TY#jHs z_2hx}x4@-rZn%NwTof|5htrySve84PLSPYY4*_+2Nf%+XHm^}G~AvQyi zOW@wwyt@Km96Gi8DCtpc%xDmXc-EF*bzMqP(9{?r6Di=elJquOCRspQEHiSZi zyRqtQz_r!xD1_@;LT&-hzxI z?=?d;alIPObC$CT_OS!%@)8B1+m7J|X_{nWg}!_a&!{)gjDZ*gx6z1Y5}G*pRf! z{*ttmc)o*qcLfk;t4y-7#7!>OULo^LJaAnRI}fvXn%1ApCZjDe37^S7Y0&({qP>Oz zuD>1@5QqNNlNZ*|PGwV*A6hy!U-wfmVti@$zrD4~Fu@hO^lrjWYrn{t{rWXdm@(OB zw_l~OxlL8UVSZpDPig5@a2A!yFd4IF#pp55UhwmC_m-d7amc+Pi{Of9uevf;HGU@KP`lr;!T4 z7CL}<37;PtJcemg41pF7`AIKY|9}CI*4%XKBWCS!x*L>P{ptP8((7T}=H2Ygt(PV} zKt2T@GQkVeteUZ)R6ctgB@)h?E-M^ER^NClm$}~i6C{Z)e#=e6} z-sikR>+WTl(`=C82u1RQvk@%CBk|D8xA_64(x3rLgaEd9;uG+WO~*roZXN1yGcQ@j z0%VHox)%7nxkq$YyqnLluakq_MB+BeoXP^ate)rMPHxu>&rIO$iKVPVTzq>TdS>*{ zFaAPzfM!dC3e!M>ZIhn*8ov3iJpdYJ8@9F)NXbrp$%{To7kNMtjOhi;?y3r28Sr?s z_=8edOiiz*5r6nE>-5sYzPov7Lx3p!;IG~_Js_+$@X3QWZcLY--i35CtVRilp5QTis}X*P zsPJ=MdyyqLyZx(l`=h}_>4sXoCc~o=$^CxGP|Lf1l!c9c=tkC%=@zczerDlFy2fL+ zf6gqlFY%-`G!2=FO6Tp?-?Z+yb9o2&TqbfxJtzOjaJv373S-WgR%Xd!f%3*``2*2^ zcx&x+5nPkt!7{iKcI!`L;z`em^rWR!sPAfbNN9R<2M=>=&z^Ggc~1&Jt)A5d5?$k~3F)H1{I#oUc_?jT(%PbLGMNSPuWEp*DZK)_D}m6+ z=qd;wg|U|XR?Zcr;SF_d^>Ax?+U>2EECpJ+Nwo4@%8*GvCj4CEwbKn0?W`@U{@tgl- zZFHgpj7ehM(R~JY6#%w0)50$teW=`Ij$rLPb4Ji>X5W53^K}@WN%KkqGWmo_IVp)r zOa?Un3cQ(q1@ZS5;O4A&bkyh_X5uZc4g#our=m25Kr(tjB@UpvHQe>Lu^I-j zYngIZSpb)?niMD&P_nUWyO+A)c9@Yca5;!Ke&dB2R~)sTQqAC-LLWyu+UIv`GJ ztw9YTYx0Q=T_-Y>(%}|C4Q}Di!s8`Xz5b&^s37bTR6)PV zc3Z#d;kZ*Im8q~gF)QD`vgsU$K7zN^xTa#%g0S@{VObX^SYar5?b*L71$Z) z?Kj?)=Mmu;%2<^E3Bp8PiB-FQ2T8LvT` zo}0En@Dn86am(9scj3P!;H?}j{oCZGXclaoR&t?b8I)y@%sP=+9C7Fw4AwzBP zz|hNLI@$-M08Ki3Kwt(SBQ+G8?+Q8rlQg>9w_GKBeJX-xC!dXZlK)z7M2TR-3@-IC zOxWOt;FJgWTA%V1xJ4gW@nJU|+*$rJP@%8Bp^0BA&SYW+^ew({3Yl;q@e-0_uU7?7 zzx6Q13X`8Zj}9mgeG5y>T-%@fO!yXLjmYoYS9gXD74V&Yk6~6 z;GLh0Y>O@;DzVQr!wuD*R;V&flo!e(*NBO*o613P#R{rUuvRsA=&6~cW%YT}Zv*Wy zCc}e&GQG*bx3YKGR!0?t`fsh|XpTuTJZmeeP~pJC!!Uy~oWvo5?vA}i>Awl<;lX7+ zZUSzWKAr|l;8Ww^?|*x`0t${6C3G2j2gI=~x)EU4*GJp#7c0Zz*XRMzhR#tgnG9i# z@GJPj4hfl_$Z05C|5v$$J{2y?0Ke=K1TL`23;ZG;{A@$6-x!q_PpJSH3}jfy(32y~ z%g>i`^t%t2yB=k7k>yF314c9K28^lcHpiP@ci00k9xWChsI>dCZtHo4%@CY$%krOG zXx$=IIV2RW3>k@sA6Con(|v1Bs!RU?PI#ff5rIfV7z#gSXtVo2fvH=KBPxE)f|#W9 zItpuryxHZy$#i^X`@viBC#k@@mOpJP%sXiXlf-ujKt;$0;B{^*`#-ST+Iu3;uk`NT zw^nxYZMpNL%$~l)&Tlf+%A=i(c{484s?{Dy?1WhYdje)4%AyHUGAJ_5KuG9fA%kBF zrlP?TWbt~_Pa*~MO+oMK(c(_RwUlKM%;2h4XUOA6ehl)(_R>>o_N)#?P<` zoZa5wgIAFF3#ZYe+BW0rVdb@;IQdafCxKhTG{t%TECB|w%2_6A_0Ivg5tp}&c0ItM zxEJAhWWd|5q5y#9ovpx~7D>Xm^nwunDdjg81CVl4Dk^~Vh@u#X5Px3e$9S$xEwBP` znhij|@Hv=|jcGU28j>zflX~ip@D*u}lCPh?M(+X-8l5{acK~Gxs5LUZvBaHj#8_pw z+?eIF5t~+W;RoSfd6Y{)Bx)2udt2clM$Jxbbnz4?M(jfcwnFu=fB+y&wrTV3U3{zo zi#z_+oj4u6amkM}|0@xGC;Xg%Q=RZ<-gpF8z&#TX!B+UfEmRsn(}XFLSt8_Z>z`gd z5%phZ(r62Nuy^mcUhd)o_%||P12a&t%0pyC1roZneDZ1qsN_m1&57Q;jq98I$C>;X z13$qeO8qfH_0tPGF?sU{cZ+$G$1S06b|jHaJk41>a18FjQvJG9fvOeG+gw=|kIOQA zcr|_F6VIsd;Pf_of(~uL-7`l0=62-t0OT3+ zth^90wbc}lI{?pK+FDNCm??)3yJH;2V{_5z&u)|l|4=Cpegj?p8?^q*d}(U!QJ9n= zSIj%tIauz{s0Bf8&(uB5ewZUC|9H!xA(TBEh08Q6*AC?j;Q@7Jy_a3uBzqJNY>iiL z&2Z>901`&}T?ur^>aH%ymh{0b@tyozVQ8|#c;89DEb$PKaXNr$Y{6-zyJDvTaEz}) zz*^nISRc1AJQ*qoYZ#Tcg>z};)E&Uio4&a%DOoj>AnP1!!_)Vr_431jvmam@wKoG}*Cedmif?HmD9s=Iu zw7l8dG96Q!wg=$&J}tF*A#b$oc~I_d`JHlTv-N)F05}q?EVLd#r$_40UNLDq`6n}Z zqmbpVf|=B*49udG{WGv;avm&NW3FTvy}@fL(oC{B@puq!b{s3*9In2Zb6n zZ%NY%i6QTkjlBX=P0Q_DWLgkYNckIdGA3+$s^Wp3&C59QmtB5`0FL|Zp7rg!lW3f~ zoUyBK+?Kw#xlZGlPLlv$W?`cMD4vQ#FoR|}h%w8_uq`uJ%13seFaP-JePy0>R%FJ; z%%Kgi4lkN+ujLU7`K%2kA-%=4^~7|AmiV}9-b}fg92LeoIiHcx0i@zFjjxJ%6P}(k zGf`8hNlyT3wcNfTiOZaG_dGT9a$b6Ht{?RXzwY3Lp)@&O;oH|8$-Ea&@OE$u7h_Ehq10 zcGCJYUaw!#GI5NGDar+zi2`ZLA;IRsV0e)H-DC&gC!VY0|Lg11Wj_~~UV3_}{E@#i zRSrEtPlVfp*%ibVWsWh=JV07?5Ly#@``>q006ngRTxTD^cpH~5LIAoSYPK;g>-1Ke z#F}BX;S^&cE7bDI-!i@S5GMF!k;W#%P;MnJ%pC~~5JHg-Z*@cyp*$N`g;0AC7K+NHUgk6B za-cl5`xv)1ysw;I+g^65;aiK8?1Q8Vs)<@Gf2w^5Z*E_Po8MSZI%u)z{ejK^)d*mN*X4Fn}c_Lfmpd+!}^{=0C19dwC8Syv-TD=?^Mf{ zm zaabU3FE$OF!vi!!@4`Tq5SoOA1Z(C{JwH{E60lIf=tuB5Jj4e zCcKtO3W!$|`nBKI9Uv?aDSw6HHxfU%^r(K5UO{RB44Vu{p$3lzQQfz|g;WFFrez}j zgf-zo#!vIltJ&i@*ef=>*DI%9Dr*J4m;dT7(K5&le<^wNt2e{Sg zHM-nP2EuFEO$w~K#M~HXYTip=l?~#W@BRc%-0d-|y?n_t@sS-jnLU4sEnOcFdjR_AmApa5MLq9j#m;P^J#?`Lq_l2}E_j#c%lXE&Si)mF|%@ zk0ATwMF?ZlXgN7i=i4q(3^D`%y%F=0jhY@FcCC- z>=vtesPyASn(kqF=9HP@a+xLD?5Xmf|F;**gNI%z>sJ|Cpp3@M%Q*+&`JAb(heUEm z<~{WQM(i-yU>R-0(^B>@ApE-D2(+*Yp!xQPOm~5_zE=32`YcP7Q^H~D#S2)JticeI zU|ZD~UlpYon=c++(FoK)wQ8aRCgM1LiUK!_NgIJhfHTt%yy>|$xhe!uBh3|MGLptt zyiUTn6lm`+y@eRGrYN}vV=n{nRc zHQ^!C50IO-O}zLa2%{MeO5J_5tl9lfMf6C7r;xt8AMaN1cun|+-vsP_z6X3Ng=V^c zV2y=G;N&}YFY>I|OQa6>?BLC~F%xtu0UiZ00u2*ntG1^Fkq5sByuu!EzkW3+&?L$a z3dNq{>`o{DjE|rDdrjI`dH}V-j3OXB`QkSnJ@|})QF-I?botavwEFD&d+qF~{Ng`* zwS4sbXE^=~0LRZ&RO{D}MQ*QB2~X{Mu$TH>-*>J6KxO9Em}J=CNNZRRt{JnuW};~d zlN?N%aZ+O`=^(9I;Zl!Es!xnqtKHvCTLmF{C759yfOmy65HsMaP7o$eRRDDDBs2*_ zuJly80_c;EDg|3|1zp5hsfZ9(JX#fe5%`WmFwG#Oi{@pYAgE7(VbS+1I<)v%mKOC_5}9sCcy7TlTCyIr6G8DO+0juwqLET15gl&oRB7y-cR ztxyYTcHU%?$C}*j5JMSEzrkq%loD035cH9YVBx^o2} z1y;AR>2GJvAS3v_q{n8dVrJVeMC zKLGx`g)v?p+r(y?MVab&YL;u|`q}I%x&;Kk8kIyF~Zh3HxL+qG-j3` z^WCLWL9QO=fdFCf3ut%im6-U}fW(j0_%S_BbNV7EX-#;&qZRn@^jiWED3LYoRUQ7e z)>lRz3_uWkojdo|-rz&CymR!{3z6h~s&I+_Xz!1CdNl<`lb5nIg?D=>ph=QtTSzMs;*Qj zRGRdULa|37PJ0K*oG1Qe`CH6 z;1=MieIG#q^liYm*JM!N@^j}3KwNe=#`lzM-|*qG__q zcMI&W%|EYNA*mzBm-D!VW}2p)=i!c9T=*E*01avH1#J$f8wrL>%VzVq*bl{l7}IFoVeu)eEsK9 zOqS6At2kz)FAdqF_oL`N&yrRdVWa!60H^1Qw@fsm{$PFx;6^4C05=2C);Ac^mAByC z**(4WCpZQK{*w(AfO(J)RRF1l3GHfjRyl3Bz}|uH|0By>HBa{5_P}xn001BWNkl&-XPPg{RXu0fQNoflo#jr(QV%hg9t;;KX zuka;5MDIyO#=VCb4sD;J`w1#8$EwMwDt*MM!9&1 zPKnoF6FYFAo1+EVSYG828-dVp-MIqtQ6FlJ?tj@p0j=4iA}>4lR~$js`Js8e#p{k0 zK-OxPU*XeW-&5uv|5{Y%8#TieIG-b;JCj*-Gp|VUat5?+TtNXq6uZ+Q1WXrY0g$a- zvf1B8??yBRLb1wXIy#{Ko6Z`ohDqSy)rrtX0ko*K6|Zp>u6oc%Jmi&p*|pE-n8~Z< z$+!T1O&1yGpa7C5qNxCq5pZaXGhzG|Ad5u^(u3t2w*6%Jr?V%@-@p9(%HLal2$GJ< zL)`p(O$?Le#vVF}M}JZF@Q%Jk=shVx2OwZ7n0SfEKP&BJD-3iQUVF`(OXx;E!fmyG zX8K%tZ2q-!_w32Cf9_n_HGhpg4Ycj7I@w#<;6o;>9DcdFzO9^F+FD*ae^>eJ>3hoG zUFMkY0>_`XOqWMc1js=YK~0#{O&3~>m#%X$2s74h`-K)`KHgdL*_n3jN)_)FY`n40AJ%-Uvh__$^d#Z^Ph7vCJ#@Ak5j1=bzL5GqX|iVjZ@gH&mZ72mU}FuiPrbK{NAww z5S_!GnS*S|jH(&qn z%U`?tk@CXL-Q|A9lrywCOery`Xurwqh!C6q!QB!tFc7{mHL%*NM}CEd1-UGSITr-~ zJYCh-Y-#x1)c4K3R({*|=gVVTey!}Ddyy|1fo9>JGDe`s^9Z&3+!21q=rZ;;Za&%1 zK8Hu0?A*9me%IoO^1Ua=+)aO^{M0Ltm7ktFQVLsL9~-SP(Fs2|yfGKKI-Yr=REGS+ zHnp_=y(|z@qFRIbZ~n&BR8H5D|M(5w`pFqJIAH# zG2gX|3Ny=o`+$+pr8lMuKQvYm=n>-7JZ&K0=~=*Q&Bqu*;g5~*de4SDgqLx7R7Q?K zY}{1u>51^|&XGzvCW$or+rREu0hp+CoY}pbwa;B;bl|D7@!}`AhLr7xT=%rba-e}1uRv7iC+du7&7gv$#}sH z{^Tbuw{PGh*jN}zk!1vwijhb2?RN4#MK9Mp1y20H$T-qEa|HS&4t`X$OGpt|{mnpQ zcuNz5+sdC}Bh}LQ0OQSZ`SzXvcX?vr^W~?nen;MB$P7q`4zKCDL2m1$MnXcxx4Qw_aB`q4}S1!`PNrIQU35Jx0S#B z^w*aENb7Ty-Ld~ab8iCmc~aK**1NC0?|V;o&k6%G!_2^dAOsXd6hS3wT;kQBWV`6i zHHl{7#^uC&PBw3H^u`!-&ecOs&T)-`CmIz50W-)Z%fRf@(>=ZS+x_nA{d~SvzyJI8 zhypV`NWJgx|EpisQ&mqr^*m4QRfEuD9>Qm!bbK>wK&UKGLTfDkS)oNxr`K3KV|QSY zrgU!BFcX+AzbVL2pz=oN*WA~=n^48S!q-Tuz*IY)rq6>V^jBzZU}SyUOD~`RM#^Pc z1PAcjxy_o2cpL+ud7g9pB_zhadLIM1eeC!w@O#}W09UX_-U~nG2*ZqEy2CjqGokpg zYjWl%{rl${|_5ZjT z+#Qx`IZ+_l+EO4DmxcRSlbf|j}+D^ubCNl!8tq|*~#W?YUD5-29)(V-lHL!2! zbL9ti{&@N7xvww3dG)2`XXXw8$7PS;wUZWsu|KpnGN<6Ipkn$a_mr(KI#j;l_UUr(r#@JI^*48yA3k{(OHntKV^m2~ zD3bx`inYF+q(dyPc92v#|qL=AT+7#1WKyeVDepRdXI0d5f5xT+p&d0i6 z`&RfRoC<)3dbuhea+v2J7r7kYbg{hnu5IN*e_F~9yl$x++|20zEO~ce&dp=33n0zq zL+AAS`t1A5^dumoQdSu_B>BP3G6v52VLD!^AJr{P3(P8GXDXQ#V#75Qz>YVVG#S-PjC>6^?3=1I(+XPLVii+i&p?*F|>>8pbukVU~3!OIk9C;JH%b$oV@{> ziXxRvLwF9=ceW4P_xCX?{U?y>=R?~w5F^zl^acT#cBZ%q` zzO`>x1s~}8Zw(t}Twny6`xe)>m*kykOu`dGqL#<;4@9DksL?jY45vLf?+E*nc8TNV^7o zUh9N1c7J}1_>%9cQ1g+zRJZos(o`u#A<(a9pt>wiY%6wEmpRX^TltyWZ;7KrzmKNY(4M25Y|H+VbIhYh33LE8%?`F{fp|8N2!0Kv z=I)oYZ=rniL?I*mPC%*Arlp_h@NGAMxQ4bk?FXDftuc(eW{}Qkm&p9DvWiv|>nCs>44y&V zct}%z4o_25YYwK<011N%kI+0ion$cBri&UG)!01UY#XV zd7WDi1WV_pC1Jr(w}!tn51zz4!a58)%=excD%(a8Vp>ag-OShoGq@A*KJS)v_ zKT!l7AFBWcy#6i9q|!th*jloMSoO%kcrFZBB*C;&3Q{RaBSHOSDB6G7Pg zh_4GDtl>vCQ>!!yl3>xkAY>jKH}PbiLC*^?T$f`lP|3JLJpH5%S~YR$E^K2U0mDjC zHi7WMKXm82I+G?ubEMr9d{%iJymQ>f+MRVeA!puTbP0j4sK*MD&Z53z#6YV%;Y#P2fDC?*lEa}gP$s| z-t^(})%2&QR<@QOTfUi5`2BPnwxBFn@dfY@eUeT6Gi7q%A~pQuJfC53i%2j_Yun(% z8{i9t)QLzqB!nXUWRf2VW<+ukcnO({Fk~KZT!TOvgpJlCFH!6SQxSLy4(?tFZhUoo zggkOo{4B?0-}Y@UE5A7OzVfzzy;}a@hGXS0edbvPSQ4K}V(N=u3xuclEk41k0d_v& zk*9?X2tOTYi&@Y(>P1|^xeeG2I$8!zjxg9aI?VXP)&BDQ!$=h?8%{U?$XGx&xDn1l zwsb#@O`Kq`C;-Yg11uyQt-Kdl0x-h!T8Xh++^s`yr@wgsza}i42O>5oHIaZf{+ux2m*-Wdz zG=TRc+-0s~a?@8o%|x4!eH1WlP6&t4W35e506@;^BGXd|XqP^&`xa)AfkIAPi~`z3 z4Z3aQlVJ0q(8>IDMp|gr)^^fmJ%n-)JMkuMgx);hoB!_Bb;pJ4Obz1~F@`wc>-_}I z0&ui>|Kud+-}C0A*&JJL#EUFHlK|X<=*5|R;NIss>2vdChW^$~-~5X5f1mr^a?dYs zDOZkeFQfQ7J7Br=jD^Smpl404%@H4G0z~-J$`A@ZX^8rk?&}7-pJ9OJ8mHz?0BPAh z*4mDDEV_3e`s~}Sbk8y#IZ(zqP3OnI|7scMLRJ^Gto!Yv@Wjkc<)NOE6zp0d(<^)1ia65wApzn@#CB;Gqe{I;5)8`mdh&)&HcS0#Nu@ z5yCa6aEMpDQZ^7XatK3YFi(YGP0!$uJRZeBv!PqMY@x(Wcmvv$F!zM>&V(f{0&$#S zkikYrh0{W3poe?Dh!;T*JVHu5PVE@l=7jh-0`GuQl&JzhdrulH;kLMH-_8Xd;BA;@ zsxSc?ftQI`yc0j@5IXtMEP3@Dah3rC92nDz$r~mEM>Al{#RF5=@`xf}24mm8GIZo1 z8+o?aoTCOsaEEq~A5<1Z?HdPIZ(L@q?~ZSMN%^<$`EYsr%&W?A7K%;L3dqb*O^9C= zB{N8@6A+i245X#2!9<~A#jnEBzB*j}?y{j5?t$PZHot9QsaR?L4?)w@Q`GX5*Dd?$ zZqViMbloBH_x-P)E~DgiaSjT?!`Z(=e>;MRQZ9=CI2%|7A zv2w}v03zCW&78#Em231N+?}SIiHT(c4vGAUsh0dUq8L}6_}jEc=&6}plP&6bU{qVQ zHszIL#4eBW>G(uu4Zu&qw!f8re_9d^-Y~ioAPNMyK^Sb2J=t^A{3^L6`os}X6^heI zTn@RW*5}`4o8m+y6f%8NMwD|dJVFzS^k`GUXTC0F$xGNs@}u|X(1wT#&J4YM`Qxh=Q6UOZJ6KK9-+`+L7r79M

-or*}h?Ji*#k` zJO^4#Nfu6)+RQi#SIsH3_*KENK=o|}8xK7Lz>9a3mC)5a-7Va!@I!lO>;WVmtg(82 zrQChra@n_ojY!<@r=U>^We5HD^tlUP z4%)H!q2Ln%jG5h1I2o?dxB(}L{3Or4II4Hz)0gxWG6%jquw#%bz5CNI$IHPxWKcyA zAqI=e`_$fy9(HJLJFm|jNf=U@2y#lm$Fq%3L~ zrGQX&$@tJX^WeKtR^;(L?<#X2{bZSc=z%i*zCVFB9m6e4oxjhJo;8EWSbuX;pBY0Ja zJWa?)H&6A6;2U>fC;(dkxH|)&#JuW-i}e4mW_7BFIPN3YW_r!$Jwm$dSb#OTaVWsp z2RYayIFXksjQT^Tq+@v+8UONcbE`^-I8+ScO}RUe7bA%S*S#x@(YVciX~xL@{8OFS zdARTxn}1Hw{6Enm{L){j`e$Io0PQ|{{N@y-=Z{qZAE4l2+}#iZo_D+@vjU{Dfjxpmugo5Pkfk6;?+Jksd-6gbCTNPBWdisVI+Pq3OQISwDaB5>0&O$|pDi z+66QY;tX+KfcL}qp$Hsfe80({=@JI!wQFNoY47x1-`I|_@bN$9V9)K`67>nrq1#eMjvXpfKmQA5 z^o~22mfBI~fB8R^bEEf`%e(I?J5^}%gaz0c;v3kq7op!yJX^v;tFv?|#5W0(eqe)m zbqfX^{uMukO%nl&r3$EVL~%qpz;l@aSS??5`vT4V`7)2N+vu^Z^RAK9{JLVw5m&P%+VY3tS~fE-AW-Aq6%GND9I&N*(U*@S9S9TFX!AzzruIcmRklLM;E}?J`?_7V zFh1n6+vRfcEUJXA@G>_ip*ARc@=Mpi7DzUZP%El5WQqtkHHrgEF*tVx85vCC`01|c z-u3Ix|KczGvI!@!H4SU3D*V?5!FPj0wM*X!y=0PJJXUla-M!}Afy<$xtt|a!d-#@} zW$9zTLksAorEl++a`k;5D4TD;p)5m#-+$!!5MrQA4zv6=8i0r}Nr|66x)Gf$tWKSw zMQ{*oVl~==(7SC!K-cFYcC7x+PU{ZF*zri$eSNuBK^Ntm`O#P+y7f%E7gQfGY z>ETB7y+J}gGvY6}ybxkJSUR1VtkL85=tEF5(P^aW^u_!>BL&bQJaO#CGI%c+KAwBB zl*!Fx(Bp|11M=GN36KOK1#6fMBMug>!06VZ^IR;lNI%F{fQ*II0c$2G0*Pze949lJ zmW6)UEok!}ID;gN#Kgi!Xp{IlzxFnATL2lYu08$;986#o>CZ#E2s;P?Nne!0MqA4i zSw%>CHs@3(Y1I(Uz_lP#W-K;h1>fe?^2yH<2Odjw1(sPOKStki#Q0#O0n!{80R?Y*A$1Up zva}hjVsw&5j}gtEh9t?R zf#zj?q_47~uv_D+0CI>6@2UXIo4EvkcK!{Oi{KzwVU z&^lIay6aW_;vnE^>MmHTan*Q? zYlx%0QvMzeLfM5U2-oqWe&Q%;GxlJdi5Lgo=%9>$`DMaM+w?VlX!m6@D3~lp(l7al zS1KxDSJxOQWpHrp`QHwYvREX>l)rTI%oIR!51+CzWa7?y%M}#>^SR<`-+yU}!!f6q z%P41|X9pln-yx=fmZDLzBc#QOv?6G6JROQLLCR6w-m zEJj*)RvaoeTClZ`o&Xp?_b*@?uZFJDHZ^_(zu93xPsoJ?;p-Jfn_ZwZI(WWJFKsJ- zc;T;=|9at2`O~Yc3U%(j&1kr&CLHWk3(D>QUA}4TDvpeOsN6fGMU^Mzh4xvUy+V5C z-SXkBNnUD*joGUCt@)3=mu2067dQ{`5V!j;<`G;z%6-qHZBI+oQT~*m3PRI(dXa&* zOj9R%>}PJe`(@>n-&B|3 z)rQCH#f37w2@c26{`b)2V434Wk!7^63v(7Zj6uP$c?><0$woiQjKZ<`pfpNg83c(& zT*H)l#o!e|he&G947gCMRv{KggQpnqYwi(hn2brG;Hx&5$V~}gtKkidTUriXdPa;p z^$Jj6W38<*BD*pCui$@RXJ2_}e}9?1P-|psQx#$EC!C`T#AcHb)(MQzr*vFEWe`O` z3!pc(Xw)jDBvI2L`Y&t*-3TaJy$4!ID}@`kD*OsNcqX6Up{wp`NJ7H_bBp%+vvh6;3|I##qy~wmjSv21Ly;GisC1kDoRqW;U`kDB8CXQ z$Ani05%gbwek&O7IBsxT{|=}=T}E{vqnZClEptx#001BWNkl9&M%jV-CT-c?Et|>85N&mE&3u$X0tSxjLtG( zIEH&NFQuXh>N|sfQ2=H~H=q_@be`-ajzSdc z`iVGeS3tNLr(Elo-yyKThLD>{-#@?8WcOVWXsv)%HkNRd^AqHC6y|0Q-6=r#kEAs~ z|85xfVRlarF*Y!aA{b&EAXAl$4LI+g0Y}Q!Q^m+^rwC5sXae6rZ|O3 z$g_g9Qg(2_$w}z{_BSt-Z4-2liG!v^`0pS`<2BIV|rA-Pz>QMtFo_y9YM&m$WCtSfoDYgEKy06XWgF85Y)_ zLul0p1HZ4S=n6n za0T2l3g8ltOTsf9=!kuXoM?z!5UC##WRQqc&%MI*ggl=#u_Kg~`4d9;UO+6-4!nAW z(&FJ|Mr-uKnQt@d;vdFh?Bnph_xW|TqT^2iHq%-psm*rm3VfHgHU0q0x`)}~s{)sf zX$2(xUeJUOY8HsmNO!%7H~o2%mn<<|p|w2JECDV5A|lQfxuP}^NeTl+|EMfBQ_-F+ zqqn}Lj2^i&(LLLrXRH94Br<?9tUSa$ybGJz;jW-5PS zDn4r*F~7EOp-jH`d+Q3#q-!M4+&psyup!MYFT68N9yfIab2^i@4Ck+K*#b8SPi`ND zv8h!U37@}87r{mW;jQJTSragUd(8%c*uY!c>&4qO@|EF; zTYM9@>KZK$BW>rLx#!Oc~ol%YYiiRzN?BZAHO`CUw*uJHoh((5nDkACYUv z$VcA5)-eLn=1+VzCh3dsCDQQr2UD#;Retldvj(A{SMo14O5 zgE`{}Mr3A0w&5J){Lu-dL+_qnVyxf+0LD1-)E0odCM}QG-#1^jF#a@mnG{g~>9Xl1 zAvBG@EPpWy-|!yW4R7+9J~?Hizp%mEunn(#2M+%h-pykXUdv0Kib?F)Y8liBnh*Fa zArC1xoHElTKO5iRE|yzAT82-&wv69&Zw+uAey@uHm}EuZ*c)D4X5agv(tnuwV3x8f z3j;K3uby2ft(hayo4Y`vetZ4pP?qOIrY+1t-#{&JKS%|WQ z0jFig4^nUlUx*}t^x+A4rM=&lkxC%aYoRrv2@w96?B|!)R9%L_B)F{rnAw^<#%Qoa z381rj*pKB1j z(Z-g$1Awk6A0NC>uC8q^|NX*i%D*{xhvIJ)HNNM#^=HZg?UbQu`}G*o>XEdw zki2PhpVd<7W01}SLb~}UzNAs(LuI4_VE~Qb`ey zdcsCc_%-Nt0$<@8bi%}Lcq#@D)=Atd3?fgSjogDjm}TGevhU~aKL*{TMJs2+KU4GU z6hK2@knN(|-uPYR>TjU{hM3&j zV@BZ0qYGtZJHjJlsKg8cQ!ddgh;p;0CvIm=vLQ)(YJbw>owEtVLwtB@AKyr-o6W{_ z9f(^X<95zE$6FD?RhX{BPyxt}ODLlu)@u(9UM-)SyS4nn+1tt=Pj4$*nZje@yqu%S zKhT=|Yt;N;6J;6%h#}=ACL+^JrTYd4-1Egx#hY-QH}5P|g7$qmYm4%*`3@vdHAZ0) zP>W8LZV~hfVI<8aj1L5%|G$TAzE3jW|IfZ_p&Z=705sz+Ypwee8gA@ek$bDLm3MO4Z~D6MitfQCQ(rtfUPC1OnVhK*1&rej}f07+~)eo&?5o)!LSYLb_*7gOS1zsnvnkWUA4( z!rtOF<_I(3p#@%fJ1s^Nf0;POM^?+-_l%YIvN%X4a_~=N>#j+o65qxQW{KLzmS2<( zcqD&(uft;}jI_;xCkV8H-!bPB%qs(@^$WgP$Ii6fkb4n`%q_5eG)2Y+u9O+h`v0F7 zUS9s?xx)aCmc5MATxN8CCBo0DrGeoz&octuVc7{Bc?i+LO^cuPXZ;Ts=+ZNK>c^2tf=5g_>Z;A!pASnVupbJWuQY+w`A@j>5j?MKhcPM0axr zzOohvHiLe_J0XdI_-!Fs+ru{l3|f!xqB0^5zq5fy#bI#5rMy~rTu4R_!t-{;pJ>S< zH4oJ<0RF&aVbfj)!3Wr7rp8U*tW|$VVPb3SlejunHvhGM$Sp)Ws%Ika#rTXZ&sqVb z?@98Tj~y=)-}$C;^_PCF48CAb>6^QhuDJ8uvuC*+a~HMvw$U=Nb+}yNJ0vuhXg>D_ z%+mDP#64;$YZ%*t>POHV09#~h?Pb;w?AZ@vA{D7|(>H<^D4>i&DKmnyW-^#>-jD!K`jYUe`DqVnVV@|(TB>+|p-ekip#$ztPF9J;Z?mZBcCc7quLuqEf2fQ=tpU4H^8-}TABwIBM?h1V9 zPnwP%=fVvuP`*_jo@3zpbx&Xt4{_^f&-T#TGzX51mJeUOqx{OnqvZoLTUpl26;zDu zpKY~1Balh#H*KXmGu4gUDxOrY`IOtUe~HP5QR zOzG&}{Omi~XHfv`hImzu=F(#bpVcklQ;kzryfjmcizxQ?X<*uW%>_DY#6lN5% zJP};PllW5^K+i1mO;dlhY&y>FR|fxFA0Y}R(cvHX;660Hu2OZFoW56h%!5zo_|<`jnN*1F`eg3thstZybY*X^N9?f0Rg>%8|Q7 zs$=!*p$;y+rgP13aMtd&1p1+O&Oo3AGGt4HW`6(j72;iC3GbHj@cdon z_onuh-=(?lsG|dYQ}pq#ApHH*{%g2-(@nH9M5>HziTwrU8V^3mw3Z6Qs6ha4uSItEDH<3l}q|Ju%zhlJcpA^j4YK4v@E{k71PZw?Lzg21frZ z%(GVjB;Mh>^X0E9kMq4cH%s}^c!8>BRDw=Z>tEirP`1(v7-v*}ni_qW=`Ur)CeO@8 zmTT^0Mt~)kD;7RPk)Y`lvlMgw!U{@a5hXAJF({1`I?N5IWiA#HGNnSeCf`A>C%ae_ z^ja>!2qg0M3vlNv#;GmO46I`YI9bvlTDt=z40w&dhPN+nSOqXoYFiwT91Ae%;HMHe zc95F&o3@mX|0YUcpUTmyLSb*Xi2>o9E|fNIVHam+4oO2~>$i*&fhS&Tcb6?Yc2K7c z>1GhHk2{AJ*;_xmyt$lOJYGIMx4XP|dVBfA9OE>E*-Do{VLwkZ-$h(B6`(s0wXer~ z#e`U9xPJb*-#_PdtwW{#hQJ%FMw-v=M@^%o>1v^>gj@_FPFoJucPI2Ba^)2MY_CiC zSVi+t5W6Nu%HyZF`RA+V%iYJI0U$2MaVu_We+1j|sz109-lTK-j+@k&z8xHg{x0C5 zvOu5UN%XCsZ*qoB-YPTk!N08syAZnZUmbnrqo&vVl5^wH3%48~Bl=3DZn7B(xp8dq zDqVop8_UuoA1rexA1j+w0N2S}7X=Vvg3#oVV`cN-`u1|^=iga|pSP1$fm}5SANfeo z3y;mE1+aA&wasY?7M{~6Ob)*iS^=AxNpOrItpMOE zY5CO-Tnbep(^gM`C2|tcOBjSzOKMz*oNz|c+-u=dkZ_9jC=3eTjXSkwS5X+CrVR*2 zKfeuSUz|q;M%q1Q2q5dcnaMbDgr%i#+EPCHYf~%|Vyh~HZflmjgaXc&?`o=$*q~9J zh|`e$c?MXi+<`?&(nRd%PCqa5FunO@T3Jh5%7w*)<)OLlL^cY)RmhvV_d$o&9tEM5M-*IeYP zv)MAum1ensgEH#Wyk*r#H%BG2=4B;>bFWIjwf_MJaKV>!@-{jNpYWh-VKgHzNG@xl zv>0farJ@Kwtiwr!8mze)2AGf%<+3!5yKc=$5=5YI=T13)_7F;q8x3a9mW9V3DVv`6 zrJw)b#ryR4bx{BkN5&iA0LeXXd`r2A0$3a5cqi^Hju1hdLFSz2&n=M|=3|)=aC*gg zX$3_hdt%O2{O5KIGh0A`!rjYIOqsS7ums%9d1e&2B6&082&r``pfuT~mIQC{g_0H? ziL11wtL&#hRvP1|a1wu9`0R|HC9>Yq|YPA>(f0*I0ojJtauGoYT2$Dxw!D~&=+wVBQYb0W`)EUcV z2JRL(EqHom5}_Y2rwo^WOt5Jmb#Rz_w#F|7o#k z4=hBw@?;hMQFg=(vmq(t0hAN1gY8^S_TQj#3+BAoGJKkCmOQ!tCF~eFfmMeD%tD9M{2ieH1{=N6^`E z$6aOYtDaXD-v7xmaLW$p!fkQn)Dit*j#Rq%$Xpqp94=e-jF$5c&r-G&9K_SO^6%n# zFK6KBDX5XvX$%IsR^CBEAj{=*i*yqzQ_Ft_wf0Q`(2D4Xk+c4s!GZMaEC~e{kify` z31gBz{OB7kuDwb$?kS!s;NTKo*9irXu7M6bu^UcFOjjXvMe z14Cu{b))4izkOGE(b@iTbn6TkcrJ2u6$^6E1_M3_mxG*6DAt+n!5j^Kb#a{ z`cJncOoP)e#A-nLX>=o<4DMBz`Wv#~r@w-{^Cqf3=87|pg6A+ou042wA7@UK1x^jx zObcO@`Ec=9N@=GLtju!or|tE{@`JB@qD&6Wlo^zveSZ~Zl&Lr@U*!;!!)0(Mr!QZm z6+zMppn7p~KeT2nAZ3THG3sy+OaoY@1-6uPaOX!p;AOaMWJ_6_Cj(R}YHKVNtA2VL zZiziH_IPZ_XjbU}c|eB0evNYmvS39sO1?LEMlz!h2nTeovZ zo~r}t(|T}69VsqMTO7LD-oV|MfOcuE0^4??=E?Yt$8iD10`_r1%E`x8%0GV7g>vVi2g@8? zA8UUP_y{VZORZ{|4IMrf$F)TUM_sLf@J_Ie+vuHvlH^&&3t#q{{J6#BUGr84W`TjP zGG;*WB{6wI18lR!lAs&naeOlhphAb02H`QA{y+DL+sd0+Jl4RhljDwQ}Jc z>juU-DvHjqM>dVnJ+KQXP2IJ2>B3?e8|P5O^+)rhtH{$2?Wg+k}_-_A<^ng-qd# zU_-DhNMd9??)d4Rr^aFYd8A3`5)|u?8Qo|E)$Qr-foYBwk|qOl;2|ywt?AF6FXimV z(cmX>OXdJHoVXCq+I-8gQnvD_psW%*yo{rlFmYNoQ4+XY#>|n8BCV(9Pz0N2%lEwO zA%un{PJHGnErrtRlQLLaxLk&h-AM~zlBWN8(4+Q62>acX<<@j14HG5MDdL9aMjE9| zL8Fol02IZFCkk6b$1^#rXiK|hYV7qxFb^Mfa8gp4MLNsunOiRJ{Old&(%iOkY~sl> zzrr+blpjSpsgk^Y#$>OX>GHYd*o|f95C845^qEs!H_g1Q0)?lWTvP@w0lso!AzIhf zg84&WGwRLizbj{!IBuRj1B9^^Fica{U2@(m)X)1WGYWIAn1X`g4W$9%b^M~@@guc1 zZ(&kU9ZZ_$4Zhh0=wNDGe)CA3@L#ioExDGFP8|Gr;og-8!4Z6hna$2ai^sRP(kCxZ{f|;E65jZuyeaTB z?~z0&!ma5Y>GvJM$3O0iWjEcXRrunUzVlQ$vi%eTfAsx11VjN#Ob(af z1N-pfTmW$*3X`*BY=tVoJ{|{`@|Qn+;wLQeg;$!p`EULiH|X+P!NOA;`RW>)0%PqT z`dbVvYV+XIk3F@!{Md(&mNy-kMj3G7jB%={)Zbg_5?x1gT@`=~u14(}87=$2@y$U~ zMcoJHnbW4JK8Qdo2Of~Hz`+L@a0Al0bW0)hBco@Zn$PB$9O=!dw+mIAju*zk;7hC~ zv>H^gr+}cNCd8&dY|>SS<}aL{Fn$Cu_6lO6wU8|I7OcI4kWPN%8Ry_x;|W4d(3AhB z2&(onPdrWFJDD@O>K1eWUE`#kk#c17)$((%`)v7+yQa(IX9fxz(O9hqH(tO#v zHdl76Dy)24_%edsiPrQ#I51xxr|JK;*IX)J_q;zV^GtK*`~`NB)|Gvf6^EDhF~%@* z;s(gUH^RS0T-N@{zf!1hn=IL}C7PwyuD4JrD1g#QMS!32r?&T71%O)y8qE!0l_znR zXY`L7?k)Rf*(36ol>tb)%CyuN{r<-<_m}Ve;GN~3g9GK3@r%^{Ds1_g8J;cM%gBNK zd|y9veH8$BbppNfMfa2~-|@z>Y%5>@CWTK_0v-+SCKnAfz)%=k^oQBCdn)e?ef^8H z5`^?nkqKr7^m7@jt$@o<(F%ZgHj6D637mE@{x+Ml^Nqr(&Cu#^Kh46hkW~aJV8arz zaqHFdkGlm^{Rn}lPx}_uPXxes1R+X{Z*j6z+qdryZoM^-zy=hRfX*;|w`**nyyF$0 zEkFE<%P0W`KNtH8>xVGJhjQul;WL;=ht+o;1s%XV7OM{t2RW=kmLD_PJ=L-EY;Tbv zY+xD@XqKj?ojJ`Y?868+BlW?DG!?{CA4FsGSgs0sH>)uHB=Hc3f_mYT2(O)SU`#jo zv?OB(PCo^G;Yt;Bg!Dk)T)BLHu3UJ86^tuvuZsd`tpMWP#+t^HEU_-T=t6zC%Bf2<|$fR{_z)5A$3N0n1 zU3dev@Ok^062xB^ObSdG{JIj>t=e@XegQ?yCoj@Rkg}*K%0Mp&ut6Dg;5C5dOtXJ^ zkP+au^7eZ_TYllq2oU|Avu8>aR@7AWeHUH&@=+{4t z;O`~^!gsa0-HkIJrYnGAI8CeI(t{`lDuUnu=rx9L65HmSqxiGu$|Ozy!~OH+NoI}i zK6JJGy{|hJaB`+E3wvCJ|Vg{v$Wu z#0_S3P;gC!WY@vb{#cD8%{c;*6(Whd>a?&iz-iw-)|njt^L!Q(7(BDgz3Wd z{NTssw)1aLJ|WCIA9!K;Z;u@)_v|a>meDgb{jK!yp!>J@zzXxU|`VhyWesFgLfJ1f+d z(8|inBK@#4PtBFXM>tD>dj=-CfBn)qPI)1Yv;xj7v$BxGMK`lZ0zx@D-zgD!Nuv^Q z7hDQe23O89@#5=Q&Y;{&iTzZ5W_$(UdwYq(B)_i18u8X&OEAW>IYns}_{hjB=w?yEP*-<*XmL4qUF0g>->RkB;U*BJT z=yh}D(U7lyqZJJr5|Mmk9m-`Msz<{cFc;q)xQMOq?HmC64 zP=*h2mYyvEXs|}N!nC{vc$JaD0WLvRZ&l&POEQU)B;(QAkxiZ;>S{WF!aCLjF&dhuoRN~dj1SYZqYr+f+A|VJ_I9$ zWntKK5|}=m@#d;!c&wHn?zjo8nC8p?KI^%IScu=+!*CmwfbfQj5#G|!CH9^(-^-m#4OEiV(E)|bi zqow4jyb~zJO+16p(wTu-xOj#dB&#PP_`s%C_bno()esXK?ZWMQQ7I?iPmTXRXaIXy ztvSZvxI$`ofq}DCmjNF8s82Utyu35Dhrh!8=gbB;iA<&sBEu)A7!WLfT7LEKZ7pAO z$2M96=gXfwh4Nv52SS=HE0$Suwi823|;&oc%vRJNi3PERs8NdIn_THUVi6%@kM_T{o|2dw}L9-`T0 zNL2jD>*)$)ZGh!%S|rj+uHtE^s=Zxh*HZ$9)tyMPPJr*M6HqCb054@GN+4I^0hZSR$jdSWO@7D+sb28Tgs;|jFks2 zk8tniaQVc{aGAL@RAy$(7)44es<5+ilquJ7Xz5ksixGa}H}fclibPG%^ke)S+gZw? zm!kks0$By4;F}{9LC*jvY!u7W;^@IN%Qb?ZKzR7x@R)g|_Q=-N^4O)-^0H&4{QK|O zRc=2zUZxr6nV&jYt}NV2nAP&Rla;!!ylJld^RIib+;#9#w*5{}_UxFWM-WA>@XyXM zV79Z2oghClhRh|8Eszh(m;zm$nNQZTM?iEe7zHjt2;~I~lL=#z3GqGo7o-+j?6%~x(?K{fRxBXE0C<hx^6;mD@qK7!K^&AW-M5}X0Uv+OHy6Om`@ z^=fJixEX|^Nvg9rtRm-tB=}+9WJx9 z2BsEh8L{N`!rT~h$K&Pn^hCM;{ABq(YR!4Vl?gfrqvU8~f=2Gs< z^bYXZdUBj#nwzX-0C+GhFwub~p?^mnqiwCZP)nKxuBK-=ck(&)9DPXi!nLAqum)&` zLResOWE4%q$@%4{KK4Qs_O`NVa%;JP7ViuCKLg6lVt5TXN_*)epDVZg+n*_8D2UZ1 z)&r;muA_PG6aYwu5WEk3^{dNcZ~nS6^{ekL!#6RCxq2mi8|U}kfFaxpg_K)z8}$cR z#NtT4LTp#y{3-STY??1SSv+)hm}|zY$q{77n&!BOS1z;8f!&VwQmlzXe=c1eJ+Q4z9An2EJQeh95z@j~T?CM_5q4#c7Q-}> zXv+v*3Z@}N;|1)_*yxm>ShNSS>Q0pfBtn5Mx5qJkxC3le+Qs8FHN`z=5F>HEs> zpW9Pz-7`@>J-W4g-{3p68@M-Oq|CnOtO5xHk) zo>K)-wJBo(TqS<&t$(N7j{Fp5%ln?#MpKzC1Ffkso)JzW+B30OzG~me^3?KPuJGDK z>kGx2{)`#6D?p?%MvlcU!YI|RBm2RyL#{&o<-Z+l_ZC_^PclLG4E(pibr)HmFU=26 zD*UB<$L&ky$KQ-HW3YF2fik5%zcR&L6Xeek_Bp0Q`&|*o_}xWj38fxO!-BKCQs?{W z@*Ld8Nxs~in*l#yJiyc*fP-|r86=_18G*kt7lqId56XL?!}_bzqAS!!qo&s@Xe$dV zl_dl^tv`7N(<7-LW?g6Al6!@72?pWA-+1B$|D`f~ zBPYMCOmXZSTQ_M1EYO6qRkoz$QZreg5-j`MadXN~MeX%kr+#Zo;X^5+I?&13GK6pP+qYZ2)L>{MLdr!20sHDuUSJn6wDz5#;yn zn?b3KmjCY)Bjx>%(0q3+z=-;&#kX-=5f@_Eq+fBvkb`>?IpYGpMMPL>MW)9O(rq{c z<2^|sF!(0P>W>yo9ICbV+qv=X!E2!)aG=3ec5=ebG=hH-A>KLRpe4eOFu&!NmGUp& zGF!Hy&}SFvo&mpdncCSxg#HWGux1|IEE3U87fiG#jz%y%Z zv4jt@`dB6-ZubK$pP$A`Ial#S?%h9c@8=l1Ii zCc>+62ZHw^$Jwa>5`PC@V`;xNeqt!YEI)qi{HF58kKB!t-NqjO$@0j=&hm9!z4p~t z{|in0eP!nUb7jxB>@F|+zy3xU*|oQJhtsiOnAvJ6|pOE)UheIU0wCaCzmo z+OC1%Bi{|qkNRB$bk1Eo*TfaT7V$=Va|)Njc*{&FEwKNeLx1U0vlss0`SLBd%$3{R zIf;7z*hy+%Dpl_%T;Yb_ojhAPK!j5kq3tv`&O8FuTg$*Dw^nb9tnFXjI1ng@cY?2= z`@QaFzkUp%-^wXA+t|zC%7kgkc7|t;g8g22_-EhPR}PFVmB0V4)p8d?{|nzYUk>jE zhI_lbZdKk>PHbWDa(ru<867KsbLNlBuHi?^m5&XSqu;foyzHNS zBR6jCV*vC#V=<4G{+(|^3G8hV_b9;kvo?#gMAz7xSy;dM+?og-1ikX$XUltUyqS?f znx+izy1H+cF2KxH)IYSPvS)w?E3*VH0nR`Xf)u36y^ac45L=^zq!{pwBlRGyn>51 zoUq3TuYYxJ@b#5IiL?hAkAQaYdNqg7>ux6Efu#}v2b#D3!f=BK;xHRa`cb%-=Z4D3 zD_hGa&uuQh_xO1Et;ZQfn`ZP>f-Cex7ukjUUd~>;8K%6E9uwm(Ukw@O%Cp?E%h)_@94! zwjAHfR40e0xZ7>Dor-H0%krJSiXSzsJrzwyOHr|`CbpySwt^cih1^g?8RqUs_#mYh zJw`-!1C7w#k=UmnK3|p@Na&;T39g~zdi*KZ=0^3-{(^0Pd!3hu1BbR=pmkq zv^qQd#4)Ceulq*P46^p%ou9a~{OF(EQcmpSi~!Izc6?FZ1iMB?VD@fVf;qi+X)yLH#yOn=!Fz(&+R{h$A1`PBFQ0C$`n;TY&s zDTt{lHfHdr5_kNDN`Qes27M@0m50Y`&$BEzOaN_qwKWlk<@nLhfkRhi?c}hH!wj&< znRT&I74)hE5N+bL)uF)Z<~s*!YBzq~!lZAgUmSHOLG0><2q5-O=;M~3n%l%}I6>>H zhUvaL#}-!yat-{3kDh z#qsh^E-@{a9tDynLfOT0kjMT5GXc3jjn_5C1UqxBeJfp$H{P^bZbh(f*~2BNytgm~ zIl%PW74C@m$=~Oa7!KV0kykF1{o6R(!IP8F9NyTQ=DP|7fp@XqRnCcY3NEcLvXb&3 z*!IJT&$?jdm>W?n6%SXSZ4L#)d%1?X`iP?(G`VsU)JAZMBbmXCgXc5&{_si%Oi?kNYho3lHzUg=G zE{9p{vo^+z45u6KWgO(2KKahF^TGq=o}WHmZhzBlxN`&00*YydvRL|T={x!#O5e77 zh^|-2UDVg(J*^7-@|g%!UpfBfZz-pL``61AW(5Y0u|#-zirs$92+&-!5_UhnN`HyM zVq;+l?6lwzeMy%P_sHE@cw3;h5Ij|A5XLyq4Md}y@3wajja&-fX+T&2CNjI!FeIdW zWCWORij~%bT8HKu%p{=EI}W9(%Ym`@Z8$vvBNpN?G+uo7gG0wyU0U%ZK#$3QO>tI$ z8ewze6}X_;`3Ps4iKqgaUiYar5q57p^{+DqUOZx}%6l8xPr(4#kJt z7-XbDw*&hY77cD5TPu?&0*aA!2rS(_heaW$JpTS0SIXfX%S;1PyE7uLrq3c8fiVh` zm!~THb*h)FK~w)cKy{2WA%|J>p>lN)I7-%Vw0MjmTXJ!a(8EMERw;*#a#}b?cZW3l zt^F-y357{{0_AtMb}z8jWc&6qw0{rNg%=r1V7d_+1fH~)nZ3&3ANEc$)rf?tk;~f9ftTziIIY|{Hd;+X@cGAq ze|_oOa(kkEu719}3IM`Ltl_QO%PnvJk@CkV08b5CVY7)#SUon(ftkD@tirU25*X${ zJNxNFoNvEOL8NbQff8S%b?9R&&sBv>aO(ifcIr_M4neVOfoWFM=#-#EV@;z>sRWeQ zj=_j9_^rT<*BteY7LdIn*#|94_Td*3q{Ti@yZ+4@tIMbg-2v#^OW1jH>6~qX*?;D>h`>BoAXre1B z9xdkLqg6)OY>C+-t2D284HL#zwdFL(NWOG2DdRIdQ}Zn1As~1-BjW}^Plo1d!LpYn z;0qjPIP1WknkfXU2rJCC-li3PT6})n&vpUV2*=2cY~rF$#(q*>5J~^!Rf5rypx`5< zu7s?l6su;yabeEDTLuA%e>#@T{?{208#DEvI92C*$S+kxdH zX~I(8lv5Xh$+YA;g^&YW0RGJf?_{~}WVz`uwBQK#KU*Cu&wKC5@;AQw*UL-3Yk!$M z29exYMJ>}eeVOzX%g4~D-$>@svPoz|URsu}$Lq`A1?VyZVLtp*KVBaGC+{euw;X1` z<0Sge)qk}c;0i&z1C9sSlpA4w*iv1jaO?`Gu`T2}*I!8?iDXn;0y#~XC9lIw7al*( zQRGxx`dNtS>r>d71%s2bubZ%`O^g?2k?C^Wwvoyv!CN5FX^Ka`r+tShb@V?^wHu4y zx@)SvepI;XUOhX2>K51y-Yt3}5idOyz*s6&hpS)OH401e;aj7yR&N>F@8A*F4o%$f zfkFbr)G++k|N7Q3d9&{>-FVYV@C*`ne%6^9(;`jEwf6H&4|^Am_acM4R~f|3)o{e4 zh8ac>hY|i9CkK3`8#qzB=ROF)(uJ@oE*dr+6>!Qmf^KWh?g8roX3oxVQ~}eaE(`CB z;SFhE({%QMF3ZI8Y>sb6VVtF=XIt(Wl)&5^-Bre=sQnii(Cd`DQ5n4cXi=|mx-gfM zeCWwT-)+JU%?;+2kGXrQpaML5-rQDVJIIi zE8Bju4BYl3nceYUV&I!2E@N>i&e zqh*lMd*fADD+s?tLUEyiv5G}~*DyLU)yHbiSuTgcC&E5RSr4Q1bAwXSBua(eG~3&_ zqD*+lopif5$W+1SZQtKRSg$<6z@Gr(htV2ioRqP%2K{t1CvH1V^M3~?@UpU!=D+>? zr6*a1h^DlKu!xe%qM|Omk!-L#_A*LK=feC@`Og1&PkEHJ81tv-8v*o-Klo&M(>MM} z*>ZRBOuZ9r$uMR!uE`sU}Xp32) zXh1z!BkG(R*fj_=w_chA)P7C)?t6oyHF(0b@Rq47b*$wD%K)BfYw+sT`08$Hhw~y` zg&FRHSYmq8qvO4`c+kOLXfAwrW`ywe;U%|aXF8qYieC~mA&l{-FrsQ;9*-E{1R(LE zLbb(Hc@S8_X?JUIKh5)rTaR+{4pV-d%DFOYl}wtnI@jo4*s53t-<%tmvNth}iLaY* z3Qq5O;+FE6(+rM~`5*oIr^TNem(c8vUcOI zRN=2gTaWlTusx^ki@yxtj%0^k`Ra1|9Y0nce#cLS_}m@>J?UpbVE4Ft^pXQ{jt{sw zXr9s>rFQUqfY}*JRyY}gLTn8I$%aB8EG3<3Kz3c7d4lp|oxpwvxor{xA4U?6CWqYv zX91#6q68>5kjy2LW(0()5&&L=!uj$f1qoy3(@Y`grXR%+CgEF8g5b!*TcewHpP=8E zHHqRBH@p*>0kHU=@L{nEqnD<^87>~a0=xdbA-NhaUNMH*XcCurxAgTRFV%S+IPrHd zBHF@fi8bkC%iBnx6?PSa0zc1`-~xSVmGa0YZsPS0Lkkgqr*j<%4qZ*#uAl;JSz|i) z#0UM2yQ|rgxImUEGaz%^Lbb>=vujAw-4TZnSk!27vVUNZou-qw?&r-SHOhBomW@J; zH#v*23ZEIyMMo=4{l$=6#Uu&ENh}=opJZ9@$4(z9|Li^c%eUV>UEcO>r^-v%$1ud) z|H>lgI-qQ9#jKJ4wX2R~Qqc^vWqJNnWp(F2DE&v@kodkFKVSYafDO4y6C5F*ed<(s z&$qmx%)b94W$1>T5cy(+Kh1v_!SMiEVXZqr|DNT;qYMnrFcz@r_D*YOsP9aHZwo>r zPdb>Sa4YZ*6dk>3wCra7SOud~j7%4yhKEoB!AlQe@JpP$voslhi{4oUb(wwPsP83sb4jWe!6RXN80O0YFDjtrHFN=2ZI;N$(@cB zr~&YaSk#XePKYi(?J;S=Xj_lFtI-o|W13w&iJQ0xn~>1VruYJL`yA*av6Hw^_zO>5poOqN?GHbJe^=f$rkZv|lu8JGo28QfPv>4-Uh$fx z^17EiOc&Ix>ci>Uij%F!HE6KrMmPsixzVVsKFl7BJ4^qIf1~tG9)ir!A{ptW@?2Q{ zYQ_LI=0r`bV4VKI`^q1^^yOvvC^rjpqtFV=CRO%U1PlBuq6Ab3hdLF1{8CYOqF@_}9aB@dd0C^n3_d>7=4D zI^(sK<(>?u_E-ypT_g~C6lXUW8@zP(f!3PX6N&t>!Eb}T=N`BYrouY}pbSlMkxVw3 zwRmeyHv zsK!{iS>q0-i65sFSjw7+e9Ms3H|54#$IEuMrP+N@80)Aq&A|)?5)TXtcmzKJE(0~@ z%fKU}!7{5#KvSEpt=w=&4d7P8=pRMW!q;zqD_qxf?Ugx}o?RH@=}hy;D~w_sVycm8 zs$E+(^*aJ@`f=>w`RKXnu_3IAP(PiTpjX)Su&JSiNu;>z1y0h`ZLh4N<}(tjtnY9ITip!sF|`N~iLT`OQ^ zX1cuZhyPxA>OcOMGRD;4%EgoEQ`riz8!%6E4n5%bPknH6ut>pQ#!mxi3T~)1E8}SS z8;8>gl%NAk6b(vXtSSKmVPq5wCVhOqBeZ!NXZ>DhIs}|FR1_IEfbk8RCqONXY4hzX zEd<{i{3}D@6pNl1(@FsC_%wU>?qFJO0dExcb1WzqbWPRjC`5RWw}H&u#_vzHuun( zvNXjQfcep#e7ZKl{CU6S*ufz##U0@wCDte~X=aTp4`+TU!DK4o1A6bMuv<0L*5m1g<{zNcn@Wy|*lU_Iw#W!EUH4=THJ{ z;D9cR)Z%j#pxt$OEQ-Jy9Aal6P}&(6k1YY4>KXCpTauc_a+Cme;;=t_;?~g|GO|oO zwhr7?Xnehzon~8@jrcldjA9@{nJ--q6v1jniE!&N9PlQ}w{NXl;`O)4R?Q!d9*MnPE0=+OBVYHLMxho6oIdA~afV!DK zZ~%p|gPY3a@h#l2r~J^0T;yQV+0Vd#*50Czr$RomhuH#Vl*ack zBgGYV)Fzb{#)aL%Moqc}o=!~Kp+|?0%4~qma0>s4e_Dp_{xRsnDk%vaA|&{idp_@?x4%8SAP5L_6SCxQaEIbRQv!}U_Q^(9QS_ZOAhC&Q{ z4T9YWTDj&;JR8DRzY0@5Ds1o*u6cESJ$Q3yCgZQA+I17pm@rhcHbHMbdFfOmA>R;D zMwQtW?tDYfFuw0~(4^^SlIhZF4&7(xmu>>WG{Ev#X|%%8-fJ`!f+IkoslcDd9yf(r zZ~apa>q_97IE2Gto~^_S)5NbJ8W3Zi201u(^4QigwvYWGbl-@jMT+nv_}0>zM#)U| zUH!z_bO{Exun>(i7RPpR&f*RiCQ-345Z$ARWo-K7Ph%^?!$~uMr91o)R7^78?ChKW zbQw7Q56jSt|0xP2C)-rd#PDVN`N~oN8?*hH|N6`2{%`-zGI7fd%#%J@nG!NO7&yZ; zipoI2xAJioNM4s|6=MGLNOYNCkl6vJ5p}n$6jHkbjs=9lsnL$mf7`Q@OCx~Ex&XAe zO}I=I8V?K=MM9X$h&65nJd8%cx|TpDtg{=IXY<1?xK#eYqlGnKvsVD&z_PiMY>hkb z7FQhoX&E){D#b(Q#k2EmtRtvh- z+moOAxB%2O5sOo^Wsw24n&*gM!Vsk9a|10xf_PNF?)&LVz__|*{yd9m7MU4xJV$p2 z^b9w)cf3p-ndD+32Ko{ah$^hu6?_l%&?H;tlSI6TV~wlIN7!vRJju8c+l{j*kNCt~ z*p#or&7<)Q)ztblSA(a1HJPN9*^mK*fA%wF@c7>^!!P@(ze?d3<*z^mAhS_0eH>2t z;eYq9%BTLpKPr>Yzp<>HeTZg1Bll2#9s<&0?V6i~|m_f9@ zO2G2hjZ_#nuoI!7KpD(Ac*Afu56Q(223phSgyC?!g<8YcLM0*-FuvxVm`KBK;}5Up zr^5BV{cK@HhFI6Xn_v7BVNIv^y&-I5+IV8ZlEl<9-nmt0U1KWvI!wk0nqMTk7aw>v z=FMB81y|mpWa7HzqcXg3eg-Z=!5}LKS+39*U*e4aC2K{bv&*}2B)P=bqWS{%Yr=|; zw5H(arZC)9WpH~ZYF6M^C@BjZ1|Z&_)q*$8F|^iKnXDbD6%13 zlK67}d<7~1NRXX-5PoHTuKdye`NQS$fB$ot8CW~_NSzsg=qiA@D1kZ_5JoU8eiqj< zOksE5GJr?&cB`;glUegyI9*G?lDBX@dv4Fc!E$gPyS9MKh7{mZvu_YA!-f&Gw1SRX zem3~wZNi;jCm=dkM=ce<2or$u!!7aijxsck*z3Cks`20fZe2Jn%4WLd$rs+Znb#Nr zv5HfSFx82-YD?2#ad9+T0#+WCk?|H!r}_-Y6F2F=laR!jtFoB#T4j-qNAjS6yYo`G7v`c1QVK*18dW4E9XE`5-?A-rmyLB;|go^KOOXRaZr_E<0c~0F^n0= zn^-x@x38Z=N@qV;25(9;mZiaewZd<7wFq|dFo03eY-IH&mo&!0$ol*H695zB+S#I|`{R=Pg z2;wl(&H>p^J@UBvS`2>IugCCvenA0x4Ldg{ScVYcwz}P80Ic*h2RO?B+=li721Z8W zwaCXg9<5b~AEzH^Q*xSHscuK(( zQt?*hAPQ=ZqM-Qod5uk_N?l-7IkK#VkSNYCm4Lz;6=n@O6K-D@MbFvG1X^8uJ(20{mMLZQPuhOrj z{1m>>vrh?^U$?Gg;I-agdp7-p-~0P9^uXU#)wKViCxYsc|27+e-E9DD2si{}V0528 zLH}4h{QmcH?n4ZpIj%K;-qn`2u4)-D&rCqtll?_!rh-Wjh0`Y})`~0vX{viu5s?S> z1vr{KUmjxLKpTVkv>@^%A>jRi!zTvv4#9wy50L2Oa%~GkN)dE~0G>uzQsM3ID!t+< zeL6n{rj93EMa{fz3{ptoX)Xn)lec8n&Ae>@7}umWSc|3|P|(b?B#~t;D7o4-cugWR zwO!_!`I#435~sa3^o@cI4(Dh&+PzB^k~k2gxf0}0Q%2$WE`{2XTZg=%$A;gaZs~CX z@URYgVM&KWffM5=67U;lqJ~>{(@!#C^`Md$~_MSQKMUF z>FgEF1h`#DpVAcqIaTL_rF@AMS>^?!P;^HB(2H(b@>%XxINyh+)FS9Zu@shRhrw68V1<5A? zg)-IesrVIp-N)TxQ4V;3S#eMd3YFC@Jt@5&A&6nUr_U32yg3LPX{C8<;!w_fUPJA| zGxy2VReUvMj{J%U)X2}KAou$5Z!9dwCSM>*!=R`l6Td)E3Rmdeu=F={8jU!e8ErCO z(6nCfHx#FK4oF{kxW3cAp**wOM;FeV0xRdR4KzVj{NYFm2yu9UXViB_KTVdr6@4y zr~7PxaJZ3i6q7KFP`N}w@riQ-m&#u=l1FAlM9Rt1Oa@sO@9z)jz|ldD0+ZqoYQ~lC z@i#eE+A{!Zv$pf- zkit!e>aqc-l^+AZwW@csw+8h^+^3$1Xa3ngiRH(ih`~EgL`Qo9bS#HhE@(}#ECm;u zh5!W{qT|)MDLBxDFk8r%gOCp{(J=^|I>ZtpmjlcM2qRFAH{CdK_{h;A9XP6yN$Hj+ z%n%Sbit?4UqJ)w|R<9U<4LkcrKp()qfRB zfBMNZ0{sgYQhAu*^WH!{Hmp`R=}h>67LAG+L#!z>~s~(%BWDBAlWryo??aDDpv|03@t<#SkuS`a_>i@9Wpu{_8JufO5><_itk9?jO>u zWhw^s5keGyNFzT=Utbu4+5mvtW!m=KI=FibKDuJTr$uOxn?hIkpYY{bIlE+Jg;%&@j6F> zl%cp(?xtQ)=s#%Wokh$|v0}hD1&7^wAYX#wpwF`8A%aF`B4+Z6SrSo-q>{wMOYaHo z(iIL1PSzj|Lh?gbzLf!hkJEga0j%kxqZ|6@MxHq+Kdvaa;-HW4W_yBw8>%d9=;(mY z&ep5k>5HYqKOUFv{kd2>^!6B%VNe!&Zbi2wC6hzV=nw800LH)uAp4hcW+y7y24;b7 z-Oueg6m+Nh6(Mq`BMS)C_GRM$OuG7JeMy};ITc6$;YZ`O!$)HN-~We*17op1pzp=$ zyLS7ekQ@*)e|0UN8YK06a7aoph)_zy5S~GGG_UsZk`Nn&jGhc2DA0=b0=QksD3z}X zE0HXv!aEXZ6ztU(S7S~m+a5eL7*jgG-scq1v0O!fr5uWrlBHkjfXfXm=#8*(?{ZTb z%L_D&WC(LE7vR+eYl+#U1fK*jm7vMb!pvv8B$s5Sc(fb&anY^?r;Y_LOS`A2jbD&drDK~j3A7w&0O2TfJCL33d;EdG(=vC#D zt>$$&(ZHLFY5s<0gKM+8&9}Ou^2r!DZwi=c=tnX^yJZ-4A_a|V2P}7k>&=-vS1Df(P>aQ^E*Qkkbpg`SYrNo%!q;PUnfw(-4wybx` zUwUpO=Jd&{8Eq1dkE?klNMtDWC?ks!q}D~%6cNA5LYcr*aZ!-;D_==t9|lkN*S%R- z(kuM%Ne|_k2%vJ=w2%;F3YZs$B!k6W+JSPUwr3jrz#w={-=G8~2$*F|n5xmFUBXLz z;kZnuD0X=ft(alM6JlU<3u{R=-u;{pJor4l!I6SmDmnTr;$=~%C|IUUreh!|7K zg26)3^9?;Wwjwh-Dn>vFVzihoX`^po^@0>!A51&(OL6}6569a0i5OA>{i}LwP+$9@ zOl)LYE)8qBRY}vO{Lmk}z}@CULEURKUa_2ptoyl`_Ivujs&&6{)4NLq@$n&1z5ukO z&B29#_itnKsb{1Aqz-#rU(|>sC6Y)iX>)La4~?qv^O7*I*~jRf>(HiO5DtzZE3Xab zKwOl^{U(Sq;Vq*)u=FU)0?AqIKR6IGGlMb8eQN|ywDMpJ(gH6fO39%CQt4AcNw>Zf zuVke7V#sMEqpL1tT&5u*X=NFROY%*;EFXSZ3a1OhHjW~f@GO(#mqIFl9Tl9)N*V=g zXc>?SP}0C(5=f=!dJ8SNsVmB#2EeJ6*699HI1+NKyr!E7hRNt)6@@#V?=7Yzn|o69kG;3wkT=^u&t{b#g< z9Ml&R^<0Y9G`z1;uk)Gm`(haYUWeEF0A2=U*(v@tbv5;y3U}8MfCj(-*wuJVgYFA@ z;>6WH!Iq4~(A(~f@n8AZvGjZYBQ}5Mf5s-K01xX0k^Yr@wx7p;nGLMwd)v%7l!!)r zUIXQe#7tkcU!#2lJzJn$)9?Qa7?viemwkkG@MW)DP=is&V=JT7Kzf{~_%U zU0Rftlrp6H<*7iKT}ML%L}RN;;XRS)1hnYkEep9Lba>Yie7hyvHwZ(O(kd zYFw8tKUvD3`xHP}Xvc)x{xl#EvkZ+9fv3bska0~*4~Z+N04Y1O80scST6V^1zy{9& z8Qfu+PuEjsM~#Jo>K@QQG0yfX5`uXYnVZJtV(3CKsk(55P2 zU%%q&E6JPsLi$4g--xFl`uXV7Cf_ih3sIOfYRIv}-B0<1IL`=_U4^zZ(BES^3So4@vJn#N1vPtIsbun;3Uf1YXnqGkeD zH6x(k5em}T;3+^E2$lleEf|uL4(j4g!Ad?RjA2NbZ+_hA5*($Y|8k+gdWZ#mzW9m^ zfxdS)rPE}l_0kFtwqRt^C6EH=FeDEOB1Op^ebUpFYi6Z`y%6Z;k;Xy`RGZ5=-B(JkQ$1>%rfkx+{ig3Gxa$nS z^%|`XGj2$uc5x}emYx-$_Xj`ty>a#6k=Xj!e~Q5`KN}k-4rn82Q3~Fln{~s23p!d{ zx-E95*Gfl%yUsCDHUv_lQCWOm4#Eg<%yma{n1YnKpy-SmBq8A-olH)@x?jAd83E5G zTsXTHvyCCxKdrCC>Xp?zI1)+C_v=yEoO(z=ivsZ|EXqWJwsAQ^Ho{HRR0+v0_2-%S zRMt$hlrcwej6s&K>_uQC&;LTA2-iyM!AN{}GadpsnH zGfcihDs;kh!Ecvn<(IWmt5U?`YNSb?K3UbMzpht=)6t)ry$$ZyD6ZqA^UFRmy0B;2 zR5`s>AY-n>KlB0+Z!9mb?$h%D(>h<^fYyJL3f1gTUkSQ&>dvwc)6}6WXCi9<&D`p%QH%?^AO(K^ug6P-S(1mxg#g zp)3n5+qslb9oP-Gz%vRX;e0obO(ZrJFK9+ECqpo~e>FcEu}{yqlLywPj7;!nK@?Z- z9x$S9SmXczAOJ~3K~y6kqB6)qm<&^ym1g27$hN+v$f0~V3w{QW-`i<8r_k7<_H`)yYngKOk3+p)JCx6`HK=kUfhT=9XdIw_Y1~#QthxFePy#Dr|dEU7!c0Z%lp_E08J%wc|b<` zCq1U~;aF)1?eaOC$SQ*sGL3KYHKZ)F@Jzhn%Y?S^+DojQnUFpTo62Sm z5-vsxteYvpRXw_NSV-q}t|%1dfQPfzmbF2wKA>-S=B$c_=H&N*@vgddv1z~A`pf6m}=cII?<;d7-Ozf8- zm>h`FoE4PAEifPyKHn(AI1rbqf&?>-0g0e+a=E`qIq-4`v0*^htnh@DVnJ-VYxTAy zlgcVShbdatBcqzwq(hRvs-UicXxJ!Y(&YC?R!Kk0Nqpi8<}8Z#R~=LFHQJ;2JnaZe z|2|FiwZAfQa5O(9zNVf3xi9MLQVUY#eT?>cI!{x5RtL||j>Ts$zdwF=>AslN!~1`~ z^W}Kg;1jxQpp9al@KdAo>viV!mGklZyZ?5qjgG}A%do}(bY+X;?I4?`i{*7Z&~}r% ztpLb%4ruLCazWh@3Y6BrvC%!h|Kk(SXv zU*v&bI?Am{KmN)sz#`W&DoQh@8v@G%K^=h@%i52)a&A5LP3p@vG6ehd7TmDTwaX=f z;<&y-vOKx_N2(-1hJx9q%tEL)*>J(r7=|&=-r6_Ht>o3XvN#k^%-$D|UO5y0aqV=(zWwph&a3f5eSZ{F{pVt} z?}(lO(JehS(AK(CV&jo`;k!Q?myg{U`*Z+FpKj;Xa@fY(vRM05_Od2aZ+kFnNVgr_ zRs%roX%rg)H&zYnMyqiexxRStq7HZ3HLbkzskNOp2v^1?;_UbRP|P1a5l8>zzsAVf zg;+hI*?=A|?&vY%Q3=$L1Z;`di}fgR&IB|IWQ0u-l)#qhr$(8a5y%+m3$qC7s+J68 zXlnXbMgv2@{b`IzzK>4b`BR$6I&F~cAc<#rFn?K}w$j&a2DL01)j9OzQ#zMkvjUa~ z|^oFBJJp0ZWGs9Waw4UV^7wi1|)VP$sGp+uckkXH7X{00mnZ@u0 zpA~%%V0Bgo`m&Z(YE#|di7&l&JRZGtPyEU3(Rg@JuZ>U5#E(ua#fMk^D(+tS6V1*} z#`3^n?G-BCirP~TbB!PP%XsC!Ux-)ld3TQdebu`E8d*}D+HYB;TF~vUafj6q{C2wA zZUE}aTM68-gc)~(8oFT}ZeAcf_B-5=Fm~EInhDVH7w>(0%JpcTnnLv zSYXB_LWx7DovND3OI+&8hAN+T%S-F~{L+$cwV;%pDH%?Ek*A{W6&VeD+g+@V4tk zYx8_F{JX{g)D2KKG;}v|4QXsf{h9_2o%n|B@UCBc{klsqtlMTw`)A^b5B^{rJ9aWo z{l)La@a3ggJFrg*%Q|ya)9+49=&{}vJvz*Yl+$4K;ifgghCn0HhMqNtpZC}YbaS3_ z26J|Tk}z7K3>xASs=VbXM6?0HD8i9OhTcYLb)gJQ%^6si7PjK5z9~P@S<|MKMnav7 zH#(-zrOQxdo-#rhn39-)Jj5k!lFQ*a(^YCs`e}GoDOE#a53d-7`+}{=ED1CY6dt*X znrS9K0a+m+|3!J=;w#8}*Od`f!)ozdSSxr}jvAiiQ+?ZX zuEIT!(5Lt5u?RMZQ1 z-yavIektzx;$v~>GoOhq$)TV~x zPR7Q>RGjEri3evNi@VPKZVYRGWij;p{_s{zo?43OJNsh)sZkmB#aLZ97oYC@Qaru? z-7%q=lO|_sccot`cN@2SnvNfNtS^Td!c$*vuiFWCl>wk3Qt+A+JjkjUl z*x+><4s(3&>u=D>ddO!$O1n>^{nGS-c=WyB6L%av8D~EK7cqYBQmju6=ko!5l44Yc zHwPIlF#_c<3Pxu%A~hxzH$T>2%~JX~eO3dWq`AXwtuzLtEx+zybVN^_r3cFq z3{V;dRU@;eE-EWK;Pi*`#bNFWEVYG9-!L0utE zY_gn`HS4Bz2S#IyTYI>YK^jG>pSNPgFn4Y<{_HFF$A5n9p7`R>!8koW8s9Olhjzwg zwY91GzDv)<{h$4#nBIIPhV)smiF@@W=#z`F|Cm1Pc|h;#kLX*4i_gY|^T*?n$zP6h z2hPNP+9unxjQq8{SdI)WL&#qnuj7F`jv?&@Zdc=`-72{241gP>hBP9L=7vU*Qs{a> z&lczy$Eo9i^Kypycv%C!Oiyq`8-&FD>K$j|m8k>qj;}l!$De#e?|VzI_l=5=`|xb? zNq8kJxw$8`;0row43tI=qT=T$vMudK=UD<0XoNh^Cq%%-hX_~>z;i83Wa^cQiJ>D> zQE=&43Qk9wfHBBhfK3}@dJ0FmNV7bE#OSMZ^~EEWE;wcvv@Oa+c`|>}2T!QF0Gn_D z1@I%MGINm^b^wsKN3%ZQ&7KE_BhyoPNJkfK#g%k$rOEkyYwAp9)GxgJYrHG)*Km)=XGjyzaHxP;rX-iuK7QU6VsoK$sbqn zp_!PN=B~<`W*GFfUfI2>C;whL8_%tOAU=KY`(k~|P4 zRO9&Dy!f-NY47HuYL;#A+wFFR0iZ!rsMH#6977tBFrXXQ1^_x&+fSo9y&C59v58|N zKsY$Cd+E)>Ngd|6G%*=}`M`I^@gpbW?aw?OGcSHMwlrN`9~jjjBk7fJq9EKVl=!k5 zkfch1@F+0TlOQ7~O1_j+BO-q(r%Ze|M^pJK{UPCWu&rr5$Y(^fjrbqQibaMUl+v?4_@(qk0uww{rVBIy6Q`czsphkeFAJ3oq+o zum1SL=+DNJ$KDwunh8v(jr;WmSFO}m?iv#A3%dE+&|#KYAoAS4sGH>+{C2oqVF0K& z4S^umuH9fXEIfv(VDk5ZC<4w3(S?#|a4tHIxZSXZPCV$NG6VzayjKn#jdK&<8}}Z) zGwy!ouVP%M%53VE+`1kf>FC{GcJIk8)1o}`mwW!ED^Nn7qq$l)~}A%dtwR>QV9CQ_nx5 z<$@jv(h0?=alalfl_;emEeVOZ`-^#4`_mlmXe{C{yZ;@XVL|D6*p9 z&)b25shFfsSi=L7hJ>u3s{rXITm{dii0D}d!JIK<97V_lHwmicns_;L5GnIgICQ4} zOts1kgTm@i*qBsWw0dS*3W@I&#{iBo!%dsq(u zm4T$6cl-6IwMX{){rwtuI5J|q4bvdd_AR4i+XEJ(^P%0 zU{j+BXW1i@l(dYBV2pYiJyZ{gC~8siq+XJ0IEoQyrtwWZX$G!T9syvNCNER|a$u>l zWCT}P+1z7OkG+O0yOs&va|cM5Wko{aK>jJOV4XJEWnlML;e|a7198f{U0hTOCny%G zpFb#ZF$$%8Sq~eCgsPBuvdw`kaYV|y6C@%f1<%{9dP}Qc)rZLcz-+LDDD5<=}Dt;&pdjnD6d~1+o*j!W9%Vr+NfIKO`F5Qiw z4CJ0|t(if&tHAuF(8#NHc$1Wfe$rEjpo&%42@-0905xkV#m#m=$q6Sw7h#!HR;t9q zXkZ{SNq9;I$wzx+LIRma=1Qj8ywk`#I3Odvbx~(HM!dN6Ks>p5e>^dAI#x%m}ni8~0|?-&F>H z0#i9x+7LQ84a;;L$VJ1OA0AxYI1a06h3i^A$74-xoH+GGei(zK37^!xF1-#A&mTG# zFX$1|yHDH`_rLU196JAOu1Pm!2y#Y%HXyJPKI%aEbL(5_mocz(icq5#yYG}QwO5djbdX=s z(2@_o&Z|u?9M={oeN8z86h##BAZe9@^5qgq#xJu&`NfhK^}tU=ZPHPJ>_-K%-09Qe zA7jRYR0I9`te0-#&M%F|3(F716Px$M(?dt}p^kky;*Z0V)BI~ke3aUX-Nvoxb+~Cj zU$ydsTQ-4~AJrgTmfxP6fNlA&)2qX7BB>o&cAWvJOG<@PC`F_}!Ci408|OwfGz~xJ z2HIc4Hg11O<66as=1z471JfADAWZ98)0*;`BX`8}nibr0>E5{am8WCowP%|d!LX*W zQm`$R1!a&>BhzdIX5Dh6S3Pr-#;}pUm{=F{$NECXAn&6~OV|Uzi1cwc0Yyd2^aDi6 zQ^yLa7z7lGG*Kqeae4bNH{7_(K)4i<{KY3w_*rnL_EB2pm8B-JOhP{e&rp7xzF-Em zAcZMqg_rU)X^D^MqEu-^Xv)lNMGDL_`8>j1jF#TW)RA3%n+y8(L&U3#_s3UOPRCPy zC*thTbdKy3n(7a+6k>$dI=@z4E4!7u4y%vzuEVYH(CB~rfwf#%R@(BY8g*SA)+P2p z;5&c*d_4BpV=+HJpK^HLefPyX-}z28&-OssBkE0)^dQ)lZjQwGO~<%JjHw(=Uf}iv zQ2<{)JQRQTfKVx=4-~}+fD`6}L^)iv4$m+>4Y;mjqbhKl>ILM|C8A)>#G55k8>|CrT{7PDf8W_UTA2 z?e4FvjmCwmC*%3$JL1b5$Ku(}er?9?i!nXmG{$I;p{PdbTEW}+PRjr*e;c+HA3sWu z5#XZT@Mrr8H&hFy!+#@(jKlZ%}e!Y=<#@3pNS|_rGs(cQkh8;i&m!b+jLb*JSdW)@U&n*w_ul44&8x~ z&0JWUj!Vm@;)RtX@zu?P@p9i(ENYoGDg_*8v{%}k(u?A^M`$Z;FJ*={$PA&!oq#rf zJ6-%%exMcKu&w;6x#~{??Cj`Ec+Q?Z8^85iza78$i@zApKmS}j_0*T*jyvv%_r33- z_=7+ALw%BNGCuU74`tuqD9xR7i`{i9@O28BK~&TY1c8ROBMb$^f!CKi1jRLuQiJ!p z;B#ja4qhw2aT@{irk@c(3OJ0h(L?Ufjhu|H&K!vor`{fC&c7HZUi(t)Tez5tyfLT^ zL#15|0XGvjWBc^hAxekB@#rpwpzQhswJzmNIVoT&DN6*E z0fWE-oAq|ygHU8OkLq0%v@AJjGhH;NkPJdjp)vhPL?9KJ^b4MSq2O$5*b>)IDti+x zy`{M| zI2`-5_ScDBTHiNHC&hOk7+UFb!>=(4R%pTohZ@DF-SEp07&;BpoEEZRn&qOFpIYX? z+pZU_&0{|!{X-AES6`yuAHVsVe;FVC@Q=nLk35ow;KzRK!|}0?eJtMp{`cq1pwvtI|9Eu%tiozjnnDApnKGZ51e$Z_%*Z8^l2#}9n8^Q20^beWfO46AxC+XLYL1m%m-!QkP*NDFn#O?XPV!{ zNhpO9k^fY1VTpV6PsLSO3bD#zn@~o7@hYuUe6?4O_VTBp;t4_W(k(ki^?r`z!k=}} z-klO!+?0T?TA(i){VpTiu#_FFdK1-CrW9{AfbN0Vn;fymW(q4fTRkJ;OjzIgR* z-}cUA+P{BF%Kz6{_G8D6>gmN1;rckPK5oj=;OlX_-T>5T1#p!6dPcwo06xB5$dr5tqo8Y52TXom*OR(^cx?W`xZ~1GaqPmg zF+TsYZZ8&NFs=_#T#>SV>g2ms*7wGp3+Lnb+}W61ej$cdmeU}hnCnuC4eb(Y98Dw1 ztwzov*wP^;D@YMKi6TmI5~4i#8LAb|;NIcONK(=Py@@2;-3St$e3o>)J&yD*UAhz}PMpw(W@b|MkpE$AK7YOLTfzX) zh*a1Pe@$}-KtuT)p7f@J%ww1%v^pKX1*Wa=(5>j;_7j&5^2`7~7reFdL&I-c&Ish^ zgxNJM4_?*BN?w{d8sn$lA!BeQj$eK`4qp6HjOz=>Z+l5EA5`Ke)Xjo=394K8DJ2&)wrn_={e{EZ~iY|d*2qNPV;Q_JX1c%$T!7Va9T(UiW7PKPDTkd``{m1vf;u4_%S)&7xK zPK6%PM>U3GQP+a_7WC@hvYy{v(W8Bok(mOAvJA`Mj4Dk%(l5oPZ<$4G8}2*{vFRuG zLoaA$1-9{>6yLmtPS^46H$+}6Lx#v(X`=$u^ELi>U^{*KbbRJBkH-TKJdmUPPyXaj z#KR9i9Iw85F6QQD(?A_QeE93mch}wp*s1+$LjVtc(|CC%g}k9z@eHk~R!kHarM2=J zx4#`;`<<2zM8?tGfPC|>F$lHt6JGoCR$PvldSzJS=d!et14zc#mgC^Ul{h?mK8{>D z8&embj71HH&z$^FJT-kHjRuN6rsK{Ji1)zqe9SCfi33ZsF>&>L3@^W`Cl;khG)^k3 z($&b$$1k>cXkK|?0K8Ygd|+T}F`l1#ARaz=e~c;Z0Z!bIlj$f6jK*T{>hz|Rb5n3b za9v8wr`Vvc;n&5v3WS&UA!J;o99$?m(|7IHHQNB1hlsx{KU7+U*GiAVp;)!zwQ(yc zifFus;5%JTi|}5fz0)CW^IG8zDW7rL%Z30P*Y+3c&HW-PAOHBrRfsjQX3cq9uwP0(xxA?J>Stqm_7#1~ zY%VU3ACK22X5z}wSdOHqD&u@d#&1;o`!Ncu%d!9JY>ew%`|;&VF|v9khSqc+nb#Af z%#z!@(m82Kuw&C+wg#+c!o8Oa@KS!sFfXm8?R|rc+=|m;7+@S;B{T_bK%;G z-u5Tc8~8ykNCP?i#3w$X>Hp<8eE3i-EG%eQa8R>suam`1t?;31~?~ zK~&QK(3Uh(+to^M9%xoLLo2TRR#@n59DhyoEP%M?cX&-R4v%p|mx(argmGaE*sx(kOTowVoWjV8zH+<15?2Q_)#ltR)i3L<3g@Vtuo#ez?f{HvG#}Mda^w1h z^_b4OACrL?TfHh{aW#hZnY5ve1%2{*P6wjQ>ND3mR!_5y7iQk44a<{pWn@bG3_20F z%o&QHquJ>ily&pf`+g& z4(xSV$!ge3L9NhMa9|t1o}cuchVz2I;H0%Z3vf7)GS@Kg=VK7$cu)v~zyo|@)JQIR z6Q^76PfA%OeBUn_~}(AqdOUxcA-K+}L$Kr6Jv>^H2HxW?PzJB8Kh*7=(5vIAX5 z}2r8B;*phY>Yz|h;uP8=^2 z9PaqFzfB_^Q|&x6urUbmP%gv5vps96%M6YJ=ROB%;cM#UdKxBg@=Gu?*0y1gRAB~k zonBG|CuIx~KSm*7)0a z+h3<)+<7@YL+Ipd=sLRmhOV!}YyUSIFa2IpCI4@r`__68Xs3$TjY4DDPbb zoF344JAeCuT&_!vC$Xuc@oy${-rtNoz9nu0eytUECt5K`2O9o53}I+1AHriLMB$C2 ztX6(#c|vd#ZbOjtisraLczXFMlj+9c#hGrL@Lm_;ri0_!{zBdUB^-A>A#+=8$Lc-Z zC!Dr4zoBVB(*SoqH8kCjF!1YL z)D=EEaWkLKII18>29buHakm@vF5bkc+sa{97Kb?=bkht`G#p{R2s3U7%?fJhF#CZu zPPqNO@OD1%x?J!(+_WsHe(VRnncbVt0JyX2jzh@Zp~ibbXr?0^;8r}KX$X<&wX#F2 z6~31r+Ra?f8(tjHG+<4$A6Q?>RQ;F_l8r+ZoNaVHKVfc1!(KFp0ckTXoRtrM9cF*6 z$c_gz-Oypz^S9G?9__N#{w$<^py3SLcm}>ne%`bOpza@cBnn`>9bPLAJoY0vD4&I{ zt%wLAv|bm+fOL9=wP`hE+>A%?RLT){$_%22?O8`qhqZg#@n6ka4QJV zya=A@RzjfhI?Qy3d1e5Q!+PPS^-7C+)ZzF^3uk^{Ltysbt#2V->+kY5f$g?%9AG;v z{U~vxIQZKa?PZ$r>%ltAxD^_IeUYwtOsAaYcfK_=f3N!NM1%fjc5f*IKu01FIE25A z*EGVcAm;0(Y_&4Oj~{5fm)~(HhjGVoyc!yZm$Ep`QV%Z;wnu*Wb;nMXEcHx3%yKne zD6ju@eI0_|7x9e~Zl!XZIt;uHZ!4$6dcj^ar`-;#^KlquGryr}Km}$KC7#~bPx~GA zW`=J$1K`d?DD1#{DTe6?t_2@xULXPoL@9ArPSb$C>accr9oEL3F3@T9f({4b%u{?f zr~Kvxw%e$tISg3iv)wV8 zoxI3nSBHbQ{k1|nyoR}qXyTOvO175{HD52BGLXKVar2s9!|R3Bd~XGO&j7S~8R4j% zmBw^K(}Bi`XN7}iqhKEM)&4e48m2kDcD$O$yfqKub`H0{hK^&J>t??p^g67K*Wp$` z;zGx7{x+<`9M5qaAAfzd>9yZDuZm$LmF}!yIlJuEFCwwQrd4QyW^53i>A>FofK2Em|uj^3LZx*jdZQ{7h z;H2#~*a@1iuHR1aoQC5V)^upKtHWx%=GnuyTVT%sY`4WtVHPT&70l2H)I87}4m94T zJ1!9AFdxu))im?>q7i1g`Py)&aF@N!U;EoU_)k7?=5x4VJFM+D-yXbi3+x$y8@JI7Icfm}w<6pqVjU0OUhzybgs+|< z;P2(k4}2qK>XjBWm(}n_e08|v7`jaM*Ss~pQ}|BwI_@5Rb1krE0B)|G-Vj$UpjJdD zP=}djo?c<*X+!fm?oQ!t`Zv?>GSzvQW=L3#_wv{Ajkn{Nz6Za)7T7ZYUtjy(Fm^4t zZ$w$m>-dIshVb;F*F3ipznQY!3=d_#S-x9Yzc*uEdj{YZ_G&Mou9etIPmy}@wu=f+ z9lsr3`|Gr8`i=0LDaVb{*eTp;yKMIF#J@-X#<#$p0rBAn=;}HKpd8n-r~J30Bfh3Q_Y~}FYPP*d+b!UMo=->WQ*C Date: Fri, 4 Jan 2019 15:33:42 +0800 Subject: [PATCH 029/267] fix ubo binding and update bugs --- cocos/gfx/binding-layout.ts | 58 +++-- cocos/gfx/define.ts | 37 --- cocos/gfx/webgl/webgl-commands.ts | 358 ++++++++++++++------------- cocos/gfx/webgl/webgl-device.ts | 8 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 6 +- cocos/pipeline/forward/test-stage.ts | 57 ++++- cocos/pipeline/render-flow.ts | 4 - cocos/pipeline/render-pipeline.ts | 7 +- cocos/pipeline/render-stage.ts | 8 +- 9 files changed, 277 insertions(+), 266 deletions(-) diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index f49d35927a..e3c5e19d26 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -5,42 +5,44 @@ import { GFXSampler } from './sampler'; import { GFXBindingType } from './define'; export interface GFXBinding { - binding : number; - type : GFXBindingType; - name : string; + binding: number; + type: GFXBindingType; + name: string; }; export interface GFXBindingLayoutInfo { - bindings : GFXBinding[]; + bindings: GFXBinding[]; }; export class GFXBindingUnit { - binding : number = 0; - type : GFXBindingType = GFXBindingType.UNKNOWN; - name : string = ""; - buffer : GFXBuffer | null = null; - texView : GFXTextureView | null = null; - sampler : GFXSampler | null = null; + binding: number = 0; + type: GFXBindingType = GFXBindingType.UNKNOWN; + name: string = ""; + buffer: GFXBuffer | null = null; + texView: GFXTextureView | null = null; + sampler: GFXSampler | null = null; }; export abstract class GFXBindingLayout { - constructor(device : GFXDevice) { + constructor(device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXBindingLayoutInfo) : boolean; + public abstract initialize(info: GFXBindingLayoutInfo): boolean; public abstract destroy(); public abstract update(); public bindBuffer(binding: number, buffer: GFXBuffer) { for (let i = 0; i < this._bindingUnits.length; ++i) { let bindingUnit = this._bindingUnits[i]; - if (bindingUnit.type === GFXBindingType.UNIFORM_BUFFER) { - bindingUnit.buffer = buffer; + if (bindingUnit.binding === binding) { + if (bindingUnit.type === GFXBindingType.UNIFORM_BUFFER) { + bindingUnit.buffer = buffer; + } else { + console.error("Setting binding is not GFXBindingType.UNIFORM_BUFFER."); + } return; - } else { - console.error("Setting binding is not GFXBindingType.UNIFORM_BUFFER."); } } } @@ -48,11 +50,13 @@ export abstract class GFXBindingLayout { public bindSampler(binding: number, sampler: GFXSampler) { for (let i = 0; i < this._bindingUnits.length; ++i) { let bindingUnit = this._bindingUnits[i]; - if (bindingUnit.type === GFXBindingType.SAMPLER) { - bindingUnit.sampler = sampler; + if (bindingUnit.binding === binding) { + if (bindingUnit.type === GFXBindingType.SAMPLER) { + bindingUnit.sampler = sampler; + } else { + console.error("Setting binding is not GFXBindingType.SAMPLER."); + } return; - } else { - console.error("Setting binding is not GFXBindingType.SAMPLER."); } } } @@ -60,15 +64,17 @@ export abstract class GFXBindingLayout { public bindTextureView(binding: number, texView: GFXTextureView) { for (let i = 0; i < this._bindingUnits.length; ++i) { let bindingUnit = this._bindingUnits[i]; - if (bindingUnit.type === GFXBindingType.SAMPLER) { - bindingUnit.texView = texView; + if (bindingUnit.binding === binding) { + if (bindingUnit.type === GFXBindingType.SAMPLER) { + bindingUnit.texView = texView; + } else { + console.error("Setting binding is not GFXBindingType.SAMPLER."); + } return; - } else { - console.error("Setting binding is not GFXBindingType.SAMPLER."); } } } - protected _device : GFXDevice; - protected _bindingUnits : GFXBindingUnit[] = []; + protected _device: GFXDevice; + protected _bindingUnits: GFXBindingUnit[] = []; }; diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index d50c70930c..7d21a511d3 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -22,17 +22,6 @@ export const GFX_MAX_VERTEX_ATTRIBUTES: number = 16; export const GFX_MAX_TEXTURE_UNITS: number = 16; export const GFX_MAX_ATTACHMENTS: number = 4; -export const GFX_ATTRIBUTE_POSITION = 'a_position'; // 0 -export const GFX_ATTRIBUTE_COLOR = 'a_color'; // 1 -export const GFX_ATTRIBUTE_COLOR1 = 'a_color1'; // 2 -export const GFX_ATTRIBUTE_NORMAL = 'a_normal'; // 3 -export const GFX_ATTRIBUTE_TANGENT = 'a_tangent'; // 4 -export const GFX_ATTRIBUTE_BINORMAL = 'a_binormal'; // 5 -export const GFX_ATTRIBUTE_TEXCOORD = 'a_texCoord'; // 6 -export const GFX_ATTRIBUTE_TEXCOORD1 = 'a_texCoord1'; // 7 -export const GFX_ATTRIBUTE_JOINTS = 'a_joints'; // 8 -export const GFX_ATTRIBUTE_WEIGHTS = 'a_weights'; // 9 - export enum GFXType { UNKNOWN, BOOL, @@ -707,29 +696,3 @@ export function GFXGetTypeSize(type: GFXType): number { } } } - -export function GFXGetAttributeBinding(name: string): number { - if (name === GFX_ATTRIBUTE_POSITION) { - return 6; - } else if (name === GFX_ATTRIBUTE_COLOR) { - return 7; - } else if (name === GFX_ATTRIBUTE_COLOR1) { - return 8; - } else if (name === GFX_ATTRIBUTE_NORMAL) { - return 9; - } else if (name === GFX_ATTRIBUTE_TANGENT) { - return 10; - } else if (name === GFX_ATTRIBUTE_BINORMAL) { - return 11; - } else if (name === GFX_ATTRIBUTE_TEXCOORD) { - return 12; - } else if (name === GFX_ATTRIBUTE_TEXCOORD1) { - return 13; - } else if (name === GFX_ATTRIBUTE_JOINTS) { - return 14; - } else if (name === GFX_ATTRIBUTE_WEIGHTS) { - return 15; - } else { - return -1; - } -} diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 86f3589b30..d1417f5fec 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,6 +1,6 @@ import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit, GFXGetAttributeBinding, GFXTextureSubres } from "../define"; +import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit } from "../define"; import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; @@ -523,7 +523,7 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - let glUsage: GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + let glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); @@ -541,7 +541,7 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - let glUsage: GLenum = gpuBuffer.usage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + let glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); @@ -550,6 +550,11 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { //console.error("WebGL 1.0 doesn't support uniform buffer."); gpuBuffer.glTarget = WebGLRenderingContext.NONE; + + if (gpuBuffer.buffer) { + gpuBuffer.viewF32 = new Float32Array(gpuBuffer.buffer); + } + } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_DST) { gpuBuffer.glTarget = WebGLRenderingContext.NONE; } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) { @@ -569,27 +574,33 @@ export function WebGLCmdFuncDestroyBuffer(device: WebGLGFXDevice, gpuBuffer: Web export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { - let gl = device.gl; + if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { + if (gpuBuffer.viewF32 && buffer) { + gpuBuffer.viewF32.set(new Float32Array(buffer), offset); + } + } else { + let gl = device.gl; - switch (gpuBuffer.glTarget) { - case WebGLRenderingContext.ARRAY_BUFFER: { - if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); - device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + switch (gpuBuffer.glTarget) { + case WebGLRenderingContext.ARRAY_BUFFER: { + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; + } + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + break; } - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); - break; - } - case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { - if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; + } + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + break; + } + default: { + console.error("Unsupported GFXBufferType, update buffer failed."); } - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); - break; - } - default: { - console.error("Unsupported GFXBufferType, update buffer failed."); } } } @@ -843,26 +854,6 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } } - // bind attributes - /* - if(gpuShader.attributes !== undefined) { - for(let a = 0; a < gpuShader.attributes.length; ++a) { - let attrib = gpuShader.attributes[a]; - let glLoc = -1; - - if(attrib.binding !== undefined && attrib.binding >= 0) { - glLoc = attrib.binding; - } else { - glLoc = GFXGetAttributeBinding(attrib.name); - } - - if(glLoc >= 0) { - gl.bindAttribLocation(gpuShader.glProgram, glLoc, attrib.name); - } - } - } - */ - // parse inputs let activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); @@ -901,11 +892,17 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG gpuShader.glBlocks = new Array(gpuShader.blocks.length); for (let i = 0; i < gpuShader.blocks.length; ++i) { let block = gpuShader.blocks[i]; - let glBlock = gpuShader.glBlocks[i]; - glBlock.isUniformPackage = true; - glBlock.binding = block.binding; - glBlock.name = block.name; - glBlock.glUniforms = new Array(block.uniforms.length); + + let glBlock: WebGLGPUUniformBlock = { + binding: block.binding, + name: block.name, + size: 0, + glUniforms: new Array(block.uniforms.length), + isUniformPackage: true, + buffer: null, + }; + + gpuShader.glBlocks[i] = glBlock; for (let u = 0; u < block.uniforms.length; ++u) { let uniform = block.uniforms[u]; @@ -924,36 +921,13 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG glType: glType, glLoc: -1, - bufferView: null, + view: null, } glBlock.size += size; } glBlock.buffer = new ArrayBuffer(glBlock.size); - glBlock.bufferView = new DataView(glBlock.buffer); - - for (let u = 0; u < glBlock.glUniforms.length; ++u) { - let glUniform = glBlock.glUniforms[u]; - if (glUniform.glLoc >= 0) { - switch (glUniform.glType) { - case WebGLRenderingContext.BOOL: - case WebGLRenderingContext.BOOL_VEC2: - case WebGLRenderingContext.BOOL_VEC3: - case WebGLRenderingContext.BOOL_VEC4: - case WebGLRenderingContext.INT: - case WebGLRenderingContext.INT_VEC3: - case WebGLRenderingContext.INT_VEC2: - case WebGLRenderingContext.INT_VEC4: { - glUniform.bufferView = new Int32Array(glBlock.buffer, glUniform.offset, glUniform.count); - break; - } - default: { - glUniform.bufferView = new Float32Array(glBlock.buffer, glUniform.offset, glUniform.count); - } - } - } - } // for } } @@ -1009,6 +983,28 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG glUniform.glLoc = glLoc; + //let count = glUniform.size / 4; + //glUniform.view = new Float32Array(glBlock.buffer, glUniform.offset, count); + + switch (glUniform.glType) { + case WebGLRenderingContext.BOOL: + case WebGLRenderingContext.BOOL_VEC2: + case WebGLRenderingContext.BOOL_VEC3: + case WebGLRenderingContext.BOOL_VEC4: + case WebGLRenderingContext.INT: + case WebGLRenderingContext.INT_VEC3: + case WebGLRenderingContext.INT_VEC2: + case WebGLRenderingContext.INT_VEC4: { + let count = glUniform.size / 4; + glUniform.view = new Int32Array(glBlock.buffer, glUniform.offset, count); + break; + } + default: { + let count = glUniform.size / 4; + glUniform.view = new Float32Array(glBlock.buffer, glUniform.offset, count); + } + } + break; } } @@ -1071,13 +1067,6 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput let glType = GFXFormatToWebGLType(attrib.format, device); let size = GFXFormatInfos[attrib.format].size; - let glLoc = -1; - if (attrib.binding) { - glLoc = attrib.binding; - } else { - glLoc = GFXGetAttributeBinding(attrib.name); - } - gpuInputAssembler.glAttribs[i] = { name: attrib.name, glBuffer: gpuBuffer.glBuffer, @@ -1594,185 +1583,198 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } } - if (glBlock && glBlock.bufferView) { + if (glBlock && gpuBinding.gpuBuffer.viewF32) { + let vf32 = gpuBinding.gpuBuffer.viewF32; + for (let u = 0; u < glBlock.glUniforms.length; ++u) { let glUniform = glBlock.glUniforms[u]; - if (glUniform.glLoc >= 0 && glUniform.bufferView) { + if (glUniform.glLoc && glUniform.view) { + + let offset = glUniform.offset / 4; switch (glUniform.glType) { case WebGLRenderingContext.BOOL: case WebGLRenderingContext.INT: { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { - if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[m]) { - gl.uniform1iv(glUniform.glLoc, glUniform.bufferView); + for (let m = 0; m < glUniform.count; ++m, ++offset) { + if (vf32[offset] !== glUniform.view[m]) { + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); + gl.uniform1iv(glUniform.glLoc, glUniform.view); + glUniform.view[m] = vf32[offset]; break; } - offset += 4; } break; } case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { - - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 2) { let idx = 2 * m; - if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset + 4) !== glUniform.bufferView[idx + 1]) { - gl.uniform2iv(glUniform.glLoc, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); + gl.uniform2iv(glUniform.glLoc, glUniform.view); break; } - offset += 8; } break; } case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 3) { let idx = 3 * m; - if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getInt32(offset + 8) !== glUniform.bufferView[idx + 2]) { - gl.uniform3iv(glUniform.glLoc, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); + gl.uniform3iv(glUniform.glLoc, glUniform.view); break; } - offset += 12; } break; } case WebGLRenderingContext.BOOL_VEC4: case WebGLRenderingContext.INT_VEC4: { - - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 4) { let idx = 4 * m; - if (glBlock.bufferView.getInt32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getInt32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getInt32(offset + 8) !== glUniform.bufferView[idx + 2] || - glBlock.bufferView.getInt32(offset + 12) !== glUniform.bufferView[idx + 3]) { - gl.uniform4iv(glUniform.glLoc, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2] || + vf32[offset + 3] !== glUniform.view[idx + 3]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); + gl.uniform4iv(glUniform.glLoc, glUniform.view); break; } - offset += 16; } break; } case WebGLRenderingContext.FLOAT: { + for (let m = 0; m < glUniform.count; ++m, ++offset) { + if (vf32[offset] !== glUniform.view[m]) { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[m]) { - gl.uniform1fv(glUniform.glLoc, glUniform.bufferView); + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); + gl.uniform1fv(glUniform.glLoc, glUniform.view); break; } - offset += 4; } break; } case WebGLRenderingContext.FLOAT_VEC2: { - - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 2) { let idx = 2 * m; - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1]) { - gl.uniform2fv(glUniform.glLoc, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); + gl.uniform2fv(glUniform.glLoc, glUniform.view); break; } - offset += 8; } break; } case WebGLRenderingContext.FLOAT_VEC3: { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 3) { let idx = 3 * m; - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2]) { - gl.uniform3fv(glUniform.glLoc, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); + gl.uniform3fv(glUniform.glLoc, glUniform.view); break; } - offset += 12; + ; } break; } case WebGLRenderingContext.FLOAT_VEC4: { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 4) { let idx = 4 * m; - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || - glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3]) { - gl.uniform4fv(glUniform.glLoc, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2] || + vf32[offset + 3] !== glUniform.view[idx + 3]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); + gl.uniform4fv(glUniform.glLoc, glUniform.view); break; } - offset += 16; } break; } case WebGLRenderingContext.FLOAT_MAT2: { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 4) { let idx = 4 * m; - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || - glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3]) { - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2] || + vf32[offset + 3] !== glUniform.view[idx + 3]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.view); break; } - offset += 16; } break; } case WebGLRenderingContext.FLOAT_MAT3: { - let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 9) { let idx = 9 * m; - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || - glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3] || - glBlock.bufferView.getFloat32(offset + 16) !== glUniform.bufferView[idx + 4] || - glBlock.bufferView.getFloat32(offset + 20) !== glUniform.bufferView[idx + 5] || - glBlock.bufferView.getFloat32(offset + 24) !== glUniform.bufferView[idx + 6] || - glBlock.bufferView.getFloat32(offset + 28) !== glUniform.bufferView[idx + 7] || - glBlock.bufferView.getFloat32(offset + 32) !== glUniform.bufferView[idx + 8]) { - gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2] || + vf32[offset + 3] !== glUniform.view[idx + 3] || + vf32[offset + 4] !== glUniform.view[idx + 4] || + vf32[offset + 5] !== glUniform.view[idx + 5] || + vf32[offset + 6] !== glUniform.view[idx + 6] || + vf32[offset + 7] !== glUniform.view[idx + 7] || + vf32[offset + 8] !== glUniform.view[idx + 8]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 9 * glUniform.count)); + gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.view); break; } - offset += 36; } break; } case WebGLRenderingContext.FLOAT_MAT4: { let offset = glUniform.offset; - for (let m = 0; m < glUniform.count; ++m) { + for (let m = 0; m < glUniform.count; ++m, offset += 16) { let idx = 16 * m; - if (glBlock.bufferView.getFloat32(offset) !== glUniform.bufferView[idx] || - glBlock.bufferView.getFloat32(offset + 4) !== glUniform.bufferView[idx + 1] || - glBlock.bufferView.getFloat32(offset + 8) !== glUniform.bufferView[idx + 2] || - glBlock.bufferView.getFloat32(offset + 12) !== glUniform.bufferView[idx + 3] || - glBlock.bufferView.getFloat32(offset + 16) !== glUniform.bufferView[idx + 4] || - glBlock.bufferView.getFloat32(offset + 20) !== glUniform.bufferView[idx + 5] || - glBlock.bufferView.getFloat32(offset + 24) !== glUniform.bufferView[idx + 6] || - glBlock.bufferView.getFloat32(offset + 28) !== glUniform.bufferView[idx + 7] || - glBlock.bufferView.getFloat32(offset + 32) !== glUniform.bufferView[idx + 8] || - glBlock.bufferView.getFloat32(offset + 36) !== glUniform.bufferView[idx + 9] || - glBlock.bufferView.getFloat32(offset + 40) !== glUniform.bufferView[idx + 10] || - glBlock.bufferView.getFloat32(offset + 44) !== glUniform.bufferView[idx + 11] || - glBlock.bufferView.getFloat32(offset + 48) !== glUniform.bufferView[idx + 12] || - glBlock.bufferView.getFloat32(offset + 52) !== glUniform.bufferView[idx + 13] || - glBlock.bufferView.getFloat32(offset + 56) !== glUniform.bufferView[idx + 14] || - glBlock.bufferView.getFloat32(offset + 60) !== glUniform.bufferView[idx + 15]) { - gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.bufferView); + if (vf32[offset] !== glUniform.view[idx] || + vf32[offset + 1] !== glUniform.view[idx + 1] || + vf32[offset + 2] !== glUniform.view[idx + 2] || + vf32[offset + 3] !== glUniform.view[idx + 3] || + vf32[offset + 4] !== glUniform.view[idx + 4] || + vf32[offset + 5] !== glUniform.view[idx + 5] || + vf32[offset + 6] !== glUniform.view[idx + 6] || + vf32[offset + 7] !== glUniform.view[idx + 7] || + vf32[offset + 8] !== glUniform.view[idx + 8] || + vf32[offset + 9] !== glUniform.view[idx + 9] || + vf32[offset + 10] !== glUniform.view[idx + 10] || + vf32[offset + 11] !== glUniform.view[idx + 11] || + vf32[offset + 12] !== glUniform.view[idx + 12] || + vf32[offset + 13] !== glUniform.view[idx + 13] || + vf32[offset + 14] !== glUniform.view[idx + 14] || + vf32[offset + 15] !== glUniform.view[idx + 15]) { + + let begin = glUniform.offset / 4; + glUniform.view.set(vf32.subarray(begin, begin + 16 * glUniform.count)); + gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.view); break; } - offset += 64; } break; } @@ -1948,8 +1950,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let cmd6 = cmdPackage.updateBufferCmds[cmdId]; if (cmd6.gpuBuffer) { - if (cmd6.buffer && cmd6.gpuBuffer.bufferView) { - cmd6.gpuBuffer.bufferView.set(new Uint8Array(cmd6.buffer), cmd6.offset); + if (cmd6.buffer && cmd6.gpuBuffer.viewUI8) { + cmd6.gpuBuffer.viewUI8.set(new Uint8Array(cmd6.buffer), cmd6.offset); } switch (cmd6.gpuBuffer.glTarget) { @@ -1983,8 +1985,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { let cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; - if (cmd7.gpuBuffer && cmd7.gpuBuffer.bufferView && cmd7.gpuTexture) { - WebGLCmdFuncCopyBufferToTexture2D(device, cmd7.gpuBuffer.bufferView, cmd7.gpuTexture, cmd7.regions); + if (cmd7.gpuBuffer && cmd7.gpuBuffer.viewUI8 && cmd7.gpuTexture) { + WebGLCmdFuncCopyBufferToTexture2D(device, cmd7.gpuBuffer.viewUI8, cmd7.gpuTexture, cmd7.regions); } break; diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 8faf2abb87..1279e9783e 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -424,14 +424,15 @@ export class WebGLGFXDevice extends GFXDevice { size: info.size, stride: info.stride ? info.stride : 1, buffer: null, - bufferView: null, + viewUI8: null, + viewF32: null, glTarget: 0, glBuffer: 0, }; if (buffer) { gpuBuffer.buffer = buffer; - gpuBuffer.bufferView = new Uint8Array(gpuBuffer.buffer); + gpuBuffer.viewUI8 = new Uint8Array(gpuBuffer.buffer); } //let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; @@ -451,9 +452,8 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { // TODO: Async - let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; let isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; - if (!isUBOSimulate && !isStagingBuffer) { + if (!isStagingBuffer) { WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, buffer); } } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index ca45a0bff6..160f9ecce5 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -36,7 +36,8 @@ export class WebGLGPUBuffer extends WebGLGPUObject { glTarget: GLenum = 0; glBuffer: WebGLBuffer = 0; buffer: ArrayBuffer | null = null; - bufferView: Uint8Array | null = null; + viewUI8: Uint8Array | null = null; + viewF32: Float32Array | null = null; constructor() { super(WebGLGPUObjectType.BUFFER); @@ -142,7 +143,7 @@ export class WebGLGPUUniform { glType: GLenum = 0; glLoc: WebGLUniformLocation = -1; - bufferView: Int32Array | Float32Array | null = null; + view: Float32Array | Int32Array | null = null; }; export class WebGLGPUUniformBlock { @@ -153,7 +154,6 @@ export class WebGLGPUUniformBlock { isUniformPackage: boolean = false; // Is a single uniform package? buffer: ArrayBuffer | null = null; // for cache - bufferView: DataView | null = null; } export class WebGLGPUUniformSampler { diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 2088bf2cde..715d87dcfa 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -3,7 +3,7 @@ import { RenderFlow } from "../render-flow"; import { GFXCommandBuffer } from "../../gfx/command-buffer"; import { RenderView } from "../render-view"; import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXTextureLayout, GFXBufferTextureCopy, GFXAddress, GFXFilter, GFXBindingType, GFXType } from "../../gfx/define"; +import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXTextureLayout, GFXBufferTextureCopy, GFXAddress, GFXFilter, GFXBindingType, GFXType, GFXCullMode } from "../../gfx/define"; import { GFXInputAssembler } from "../../gfx/input-assembler"; import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; import { GFXShader } from "../../gfx/shader"; @@ -13,6 +13,7 @@ import { GFXBindingLayout } from "../../gfx/binding-layout"; import { GFXTexture } from "../../gfx/texture"; import { GFXTextureView } from "../../gfx/texture-view"; import { GFXSampler } from "../../gfx/sampler"; +import { GFXBuffer } from "../../gfx/buffer"; /* declare module '*.png' { @@ -38,11 +39,14 @@ let _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 { @@ -82,8 +86,13 @@ export class TestStage extends RenderStage { this._shader = this._device.createShader({ name: "test", stages: [vsStage, fsStage], + blocks: [{ + binding: 5, name: "UBO", uniforms: [ + { name: "u_color", type: GFXType.FLOAT4, count: 1 }, + ] + }], samplers: [ - {binding: 10, name: "u_sampler", type: GFXType.SAMPLER2D, count: 1 } + { binding: 10, name: "u_sampler", type: GFXType.SAMPLER2D, count: 1 } ] }); if (!this._shader) { @@ -92,6 +101,7 @@ export class TestStage extends RenderStage { this._bindingLayout = this._device.createBindingLayout({ bindings: [ + { binding: 5, type: GFXBindingType.UNIFORM_BUFFER, name: "u_color" }, { binding: 10, type: GFXBindingType.SAMPLER, name: "u_sampler" }, ], }); @@ -112,6 +122,8 @@ export class TestStage extends RenderStage { let is: GFXInputState = { attributes: this._pipeline.quadIA.attributes }; + this._rs.cullMode = GFXCullMode.BACK; + this._pipelineState = this._device.createPipelineState({ primitive: GFXPrimitiveMode.TRIANGLE_LIST, shader: this._shader, @@ -123,6 +135,28 @@ export class TestStage extends RenderStage { renderPass: this._framebuffer.renderPass, }); + // create ubo + let color = [1.0, 0.3, 0.3, 1.0]; + let 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; + } + + let 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 let imgElms = this._device.canvas.getElementsByTagName("img"); if (imgElms.length) { if (!this.loadTexture(imgElms[0])) { @@ -145,6 +179,21 @@ export class TestStage extends RenderStage { 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; @@ -241,6 +290,7 @@ export class TestStage extends RenderStage { return false; } + this._bindingLayout.bindBuffer(5, this._ubo); this._bindingLayout.bindTextureView(10, this._texView); this._bindingLayout.bindSampler(10, this._sampler); this._bindingLayout.update(); @@ -256,8 +306,9 @@ export class TestStage extends RenderStage { 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; - }; diff --git a/cocos/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts index 714802c72d..67fb3c161d 100644 --- a/cocos/pipeline/render-flow.ts +++ b/cocos/pipeline/render-flow.ts @@ -25,10 +25,6 @@ export abstract class RenderFlow { } } - public resize(width, height) { - - } - public createStage(clazz: new(flow: RenderFlow) => T, info : RenderStageInfo): RenderStage | null { let stage: RenderStage = new clazz(this); if(stage.initialize(info)) { diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 1feb09f8d2..5c7fd4c6a9 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -33,9 +33,6 @@ export abstract class RenderPipeline { } } - public resize(width, height) { - } - public addRenderPass(stage: number, renderPass: GFXRenderPass) { if (renderPass) { this._renderPasses.set(stage, renderPass); @@ -104,7 +101,7 @@ export abstract class RenderPipeline { let vbSize = vbStride * 4; this._quadVB = this._device.createBuffer({ - usage: GFXBufferUsageBit.VERTEX, + usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: vbSize, stride: vbStride, @@ -128,7 +125,7 @@ export abstract class RenderPipeline { let ibSize = ibStride * 6; this._quadIB = this._device.createBuffer({ - usage: GFXBufferUsageBit.INDEX, + usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: ibSize, stride: ibStride, diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index f739f39e61..102eb54468 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -5,7 +5,7 @@ import { GFXCommandBuffer } from "../gfx/command-buffer"; import { RenderFlow } from "./render-flow"; import { GFXDevice } from "../gfx/device"; import { RenderPipeline } from "./render-pipeline"; -import { GFXColor, GFX_MAX_ATTACHMENTS, GFXRect } from "../gfx/define"; +import { GFXColor, GFXRect } from "../gfx/define"; export interface RenderStageInfo { name?: string; @@ -26,17 +26,13 @@ export abstract class RenderStage { this._device = this._flow.pipeline.root.device; this._clearColors = [{ r: 0.3, g: 0.6, b: 0.9, a: 1.0 }]; - this._renderArea = { left: 0, top: 0, width: 0, height: 0 }; + this._renderArea = { x: 0, y: 0, width: 0, height: 0 }; } public abstract initialize(info: RenderStageInfo): boolean; public abstract destroy(); public abstract render(view: RenderView); - public resize(width, height) { - - } - public setClearColor(color: GFXColor) { if (this._clearColors.length > 0) { this._clearColors[0] = color; From fd16680db1e26761cf30160e076d5f8cfab7f716 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Fri, 4 Jan 2019 18:49:43 +0800 Subject: [PATCH 030/267] add retrieve render data interface in model --- cocos/renderer/scene/model.js | 133 -------------------------- cocos/renderer/scene/model.ts | 173 ++++++++++++++++++++++++++++++++++ 2 files changed, 173 insertions(+), 133 deletions(-) delete mode 100644 cocos/renderer/scene/model.js create mode 100644 cocos/renderer/scene/model.ts diff --git a/cocos/renderer/scene/model.js b/cocos/renderer/scene/model.js deleted file mode 100644 index fff9d96afe..0000000000 --- a/cocos/renderer/scene/model.js +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { aabb } from '../../3d/geom-utils'; - -/** - * A representation of a model - */ -export default class Model { - /** - * Setup a default empty model - */ - constructor() { - this._scene = null; - this._id = 0; - this._enable = false; - - this._type = 'default'; - this._poolID = -1; - this._isEnable = true; - this._node = null; - this._inputAssembler = null; - this._effect = null; - this._defines = {}; - this._dependencies = {}; - this._viewID = -1; - this._cameraID = -1; - this._userKey = -1; - this._castShadow = false; - this._boundingShape = null; - } - - setScene(scene) { - this._scene = scene; - - if(this._scene) { - this._id = this._scene.generateModelId(); - } - } - - get scene() { - return this._scene; - } - - get id() { - return this._id; - } - - _updateTransform() { - if (!this._node._hasChanged || !this._boundingShape) return; - this._node.updateWorldTransformFull(); - this._bsModelSpace.transform(this._node._mat, this._node._pos, - this._node._rot, this._node._scale, this._boundingShape); - } - - /** - * Create the bounding shape of this model - * @param {vec3} minPos the min position of the model - * @param {vec3} maxPos the max position of the model - */ - createBoundingShape(minPos, maxPos) { - if (!minPos || !maxPos) return; - this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); - this._boundingShape = aabb.clone(this._bsModelSpace); - } - - enable(isEnable) { - this._isEnable = isEnable; - } - - isEnable() { - return this._isEnable; - } - - /** - * Get the hosting node of this camera - * @returns {Node} the hosting node - */ - getNode() { - return this._node; - } - - /** - * Set the hosting node of this model - * @param {Node} node the hosting node - */ - setNode(node) { - this._node = node; - } - - /** - * Set the input assembler - * @param {InputAssembler} ia - */ - setInputAssembler(ia) { - this._inputAssembler = ia; - } - - /** - * Set the model effect - * @param {?Effect} effect the effect to use - */ - setEffect(effect) { - if (effect) { - this._effect = effect; - this._defines = effect.extractDefines(Object.create(null)); - this._dependencies = effect.extractDependencies(Object.create(null)); - } else { - this._effect = null; - this._defines = Object.create(null); - this._dependencies = Object.create(null); - } - } - - /** - * Set the user key - * @param {number} key - */ - setUserKey(key) { - this._userKey = key; - } - - /** - * Extract a drawing item - * @param {Object} out the receiving item - */ - extractDrawItem(out) { - out.model = this; - out.node = this._node; - out.ia = this._inputAssembler; - out.effect = this._effect; - out.defines = this._effect ? this._effect.extractDefines(this._defines) : this._defines; - out.dependencies = this._effect ? this._effect.extractDependencies(this._dependencies) : this._dependencies; - } -} diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts new file mode 100644 index 0000000000..13cfd68490 --- /dev/null +++ b/cocos/renderer/scene/model.ts @@ -0,0 +1,173 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import { aabb } from '../../3d/geom-utils'; +import { GFXInputAttribute } from '../../gfx/input-assembler'; +import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { RenderScene } from './render-scene'; +import { vec3 } from '../../core/vmath'; +import { Vec3 } from '../../core/value-types'; +import { Node } from '../../scene-graph'; +import InputAssembler from '../core/input-assembler'; +import Effect from '../core/effect'; +import { Pass } from '../core/pass'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; + +/** + * A representation of a model + */ +export default class Model { + + _scene: RenderScene | null; + _id: number; + _enable: boolean; + _type: string; + _poolID: number; + _isEnable: boolean; + _node: Node; + _inputAssembler: InputAssembler; + _effect: Effect | null; + _defines: Object; + _dependencies: Object; + _viewID: number; + _cameraID: number; + _userKey: number; + _castShadow: boolean; + _boundingShape: aabb; + _bsModelSpace: aabb; + _passes: Pass[]; + _cmdBuffers: GFXCommandBuffer[]; + /** + * Setup a default empty model + */ + constructor() { + this._scene = null; + this._id = 0; + this._enable = false; + + this._type = 'default'; + this._poolID = -1; + this._isEnable = true; + this._node = null; + this._inputAssembler = null; + this._effect = null; + this._defines = {}; + this._dependencies = {}; + this._viewID = -1; + this._cameraID = -1; + this._userKey = -1; + this._castShadow = false; + this._boundingShape = null; + this._passes = new Array(); + this._cmdBuffers = new Array(); + } + + setScene(scene: RenderScene) { + this._scene = scene; + + if (this._scene) { + this._id = this._scene.generateModelId(); + } + } + + get scene(): RenderScene { + return this._scene; + } + + get id(): number { + return this._id; + } + + _updateTransform() { + if (!this._node._hasChanged || !this._boundingShape) return; + this._node.updateWorldTransformFull(); + this._bsModelSpace.transform(this._node._mat, this._node._pos, + this._node._rot, this._node._scale, this._boundingShape); + } + + /** + * Create the bounding shape of this model + * @param {vec3} minPos the min position of the model + * @param {vec3} maxPos the max position of the model + */ + createBoundingShape(minPos: Vec3, maxPos: Vec3) { + if (!minPos || !maxPos) return; + this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); + this._boundingShape = aabb.clone(this._bsModelSpace); + } + + enable(isEnable: boolean) { + this._isEnable = isEnable; + } + + isEnable(): boolean { + return this._isEnable; + } + + /** + * Get the hosting node of this camera + * @returns {Node} the hosting node + */ + getNode(): Node { + return this._node; + } + + /** + * Set the hosting node of this model + * @param {Node} node the hosting node + */ + setNode(node: Node) { + this._node = node; + } + + /** + * Set the input assembler + * @param {InputAssembler} ia + */ + setInputAssembler(ia: InputAssembler) { + this._inputAssembler = ia; + } + + /** + * Set the model effect + * @param {?Effect} effect the effect to use + */ + setEffect(effect: Effect) { + if (effect) { + this._effect = effect; + this._defines = effect.extractDefines(Object.create(null)); + this._dependencies = effect.extractDependencies(Object.create(null)); + } else { + this._effect = null; + this._defines = Object.create(null); + this._dependencies = Object.create(null); + } + } + + /** + * Set the user key + * @param {number} key + */ + setUserKey(key: number) { + this._userKey = key; + } + + getPassList(): Pass[] { + return this._passes; + } + + getCmdBufferList(): GFXCommandBuffer[] { + return this._cmdBuffers; + } + + /** + * Extract a drawing item + * @param {Object} out the receiving item + */ + extractDrawItem(out) { + out.model = this; + out.node = this._node; + out.ia = this._inputAssembler; + out.effect = this._effect; + out.defines = this._effect ? this._effect.extractDefines(this._defines) : this._defines; + out.dependencies = this._effect ? this._effect.extractDependencies(this._dependencies) : this._dependencies; + } +} From 88f9348dfee8efb5a9366da76a978ca3ef013e93 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 4 Jan 2019 18:54:36 +0800 Subject: [PATCH 031/267] fix error ubo name --- cocos/gfx/webgl/webgl-commands.ts | 2 +- cocos/pipeline/forward/test-stage.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index d1417f5fec..df5e0e6e85 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1938,7 +1938,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } for (let a = 0; a < device.maxVertexAttributes; ++a) { - if (device.stateCache.glEnabledAttribLocs[a] != device.stateCache.glCurrentAttribLocs[a]) { + if (device.stateCache.glEnabledAttribLocs[a] !== device.stateCache.glCurrentAttribLocs[a]) { gl.disableVertexAttribArray(a); device.stateCache.glEnabledAttribLocs[a] = false; } diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 715d87dcfa..8a4f67b2e3 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -101,7 +101,7 @@ export class TestStage extends RenderStage { this._bindingLayout = this._device.createBindingLayout({ bindings: [ - { binding: 5, type: GFXBindingType.UNIFORM_BUFFER, name: "u_color" }, + { binding: 5, type: GFXBindingType.UNIFORM_BUFFER, name: "UBO" }, { binding: 10, type: GFXBindingType.SAMPLER, name: "u_sampler" }, ], }); From 1c445f3098cca0d449b2ba4770ef66ba4abcae22 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 7 Jan 2019 16:23:00 +0800 Subject: [PATCH 032/267] add 'isNormalized' to GFXInputAttribute --- cocos/camera/CCCamera.js | 2 +- cocos/core/root.ts | 11 +- cocos/gfx/device.ts | 15 + cocos/gfx/input-assembler.ts | 1 + cocos/gfx/pipeline-state.ts | 28 ++ cocos/gfx/shader.ts | 6 + cocos/gfx/webgl/webgl-commands.ts | 5 +- cocos/gfx/webgl/webgl-device.ts | 7 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 1 + cocos/pipeline/forward/forward-pipeline.ts | 19 +- cocos/pipeline/render-pipeline.ts | 131 +++++- cocos/pipeline/render-view.ts | 14 +- cocos/renderer/core/pass.ts | 9 +- cocos/renderer/index.js | 2 +- cocos/renderer/scene/camera.js | 478 --------------------- cocos/renderer/scene/camera.ts | 141 ++++++ cocos/renderer/scene/model.ts | 2 +- cocos/renderer/scene/render-scene.ts | 19 +- 18 files changed, 379 insertions(+), 512 deletions(-) delete mode 100644 cocos/renderer/scene/camera.js create mode 100644 cocos/renderer/scene/camera.ts diff --git a/cocos/camera/CCCamera.js b/cocos/camera/CCCamera.js index d197071376..b08129c519 100644 --- a/cocos/camera/CCCamera.js +++ b/cocos/camera/CCCamera.js @@ -31,7 +31,7 @@ import vec2 from '../core/vmath/vec2'; import vec3 from '../core/vmath/vec3'; import Component from '../components/CCComponent'; // TODO fix import from renderer -import {default as Renderer_Camera} from '../renderer/scene/camera'; +import { Camera as Renderer_Camera} from '../renderer/scene/camera'; import {default as Renderer_View} from '../renderer/core/view'; import {ccclass, property, executeInEditMode, menu, inspector} from '../core/data/class-decorator'; diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 2882840121..26dbfe5c87 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -48,6 +48,8 @@ export class Root { public frameMove(deltaTime: number) { + this._frameTime = deltaTime; + for (let i = 0; i < this._views.length; ++i) { let view = this._views[i]; if (view.isEnable() && view.isAttached) { @@ -88,7 +90,7 @@ export class Root { } public createScene(info: RenderSceneInfo): RenderScene | null { - let scene = new RenderScene; + let scene = new RenderScene(this); if (scene.initialize(info)) { this._scenes.push(scene); return scene; @@ -155,7 +157,7 @@ export class Root { return this._pipeline; } - public get sceneManagers(): RenderScene[] { + public get scenes(): RenderScene[] { return this._scenes; } @@ -163,10 +165,15 @@ export class Root { return this._views; } + public get frameTime(): number { + return this._frameTime; + } + private _device: GFXDevice; private _windows: GFXWindow[] = []; private _mainWindow: GFXWindow | null = null; private _pipeline: RenderPipeline | null = null; private _scenes: RenderScene[] = []; private _views: RenderView[] = []; + private _frameTime: number = 0; }; diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 9bda923c72..d1e3f93686 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -55,6 +55,14 @@ export abstract class GFXDevice { return this._queue; } + public get width(): number { + return this._width; + } + + public get height(): number { + return this._height; + } + public get mainWindow(): GFXWindow | null { return this._mainWindow; } @@ -99,12 +107,18 @@ export abstract class GFXDevice { return this._stencilBits; } + public genShaderId(): number { + return this._shaderIdGen++; + } + protected _canvas: HTMLCanvasElement | null = null; protected _deviceName: string = ""; protected _renderer: string = ""; protected _vendor: string = ""; protected _version: string = ""; protected _queue: GFXQueue | null = null; + protected _width: number = 0; + protected _height: number = 0; protected _mainWindow: GFXWindow | null = null; protected _cmdAllocator: GFXCommandAllocator | null = null; protected _maxVertexAttributes: number = 0; @@ -114,4 +128,5 @@ export abstract class GFXDevice { protected _maxVertexTextureUnits: number = 0; protected _depthBits: number = 0; protected _stencilBits: number = 0; + protected _shaderIdGen: number = 0; }; diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 88be409ef4..fe18052dd4 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -6,6 +6,7 @@ export interface GFXInputAttribute { binding?: number; name: string; format: GFXFormat; + isNormalized?: boolean; stream?: number; isInstanced?: boolean; }; diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index e371b7dcb1..8d091141b0 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -128,6 +128,34 @@ export abstract class GFXPipelineState { public abstract initialize(info: GFXPipelineStateInfo): boolean; public abstract destroy(): void; + public get shader() : GFXShader { + return this._shader; + } + + public get primitive() : GFXPrimitiveMode { + return this._primitive; + } + + public get rasterizerState() : GFXRasterizerState { + return this._rs; + } + + public get depthStencilState() : GFXDepthStencilState { + return this._dss; + } + + public get blendState() : GFXBlendState { + return this._bs; + } + + public get pipelineLayout() : GFXPipelineLayout { + return this._layout; + } + + public get renderPass() : GFXRenderPass { + return this._renderPass; + } + protected _device: GFXDevice; protected _shader: GFXShader | null = null; protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index 764ebfb6dc..980413e9ba 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -45,12 +45,18 @@ export abstract class GFXShader { constructor(device: GFXDevice) { this._device = device; + this._id = device.genShaderId(); } public abstract initialize(info: GFXShaderInfo): boolean; public abstract destroy(); + public get id(): number { + return this._id; + } + protected _device: GFXDevice; + protected _id: number; protected _name: string = ""; protected _stages: GFXShaderStage[] = []; //protected _bindings: GFXBinding[] = []; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index df5e0e6e85..09748aedb5 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1075,7 +1075,8 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput count: GFXFormatInfos[attrib.format].count, stride: gpuBuffer.stride, componentCount: WebGLGetComponentCount(glType), - isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false, + isNormalized: (attrib.isNormalized !== undefined? attrib.isNormalized : false), + isInstanced: (attrib.isInstanced !== undefined ? attrib.isInstanced : false), offset: offsets[stream], }; @@ -1918,7 +1919,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } device.stateCache.glCurrentAttribLocs[glLoc] = true; - gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, false, glAttrib.stride, attribOffset); + gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset); } } } // if diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 1279e9783e..5e28863b76 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -103,7 +103,7 @@ export class WebGLGFXDevice extends GFXDevice { return false; } - console.info('WebGL device initialization successed.'); + console.info('WebGL device initialized.'); this._deviceName = "WebGL"; let gl = this._webGLRC; @@ -126,9 +126,14 @@ export class WebGLGFXDevice extends GFXDevice { this._depthBits = gl.getParameter(WebGLRenderingContext.DEPTH_BITS); this._stencilBits = gl.getParameter(WebGLRenderingContext.STENCIL_BITS); + this._width = this._canvas.width; + this._height = this._canvas.height; + console.info("RENDERER: " + this._renderer); console.info("VENDOR: " + this._vendor); console.info("VERSION: " + this._version); + console.info("SCREEN_SIZE: " + this._width + "x" + this._height); + console.info("MAX_VERTEX_ATTRIBS: " + this._maxVertexAttributes); console.info("MAX_VERTEX_UNIFORM_VECTORS: " + this._maxVertexUniformVectors); console.info("MAX_FRAGMENT_UNIFORM_VECTORS: " + this._maxFragmentUniformVectors); diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 160f9ecce5..9bfd803b83 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -235,6 +235,7 @@ export class WebGLAttrib { count: number = 0; stride: number = 0; componentCount: number = 1; + isNormalized: boolean = false; isInstanced: boolean = false; offset: number = 0; }; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index ba1f6b932e..ddc813292d 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -1,7 +1,8 @@ -import { RenderPipeline, RenderPassStage } from "../render-pipeline"; +import { RenderPipeline, RenderPassStage, UBOGlobal } from "../render-pipeline"; import { Root } from "../../core/root"; import { ForwardFlow } from "./forward-flow"; import { GFXRenderPass } from "../../gfx/render-pass"; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../../gfx/define"; export enum ForwardFlowPriority { FORWARD = 0, @@ -19,6 +20,10 @@ export class ForwardPipeline extends RenderPipeline { return false; } + if(!this.createUBOs()) { + return false; + } + let mainWindow = this._root.mainWindow; let windowPass: GFXRenderPass | null = null; @@ -33,8 +38,14 @@ export class ForwardPipeline extends RenderPipeline { this.addRenderPass(RenderPassStage.FORWARD, windowPass); - // create flows + // 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", priority: ForwardFlowPriority.FORWARD, @@ -43,9 +54,11 @@ export class ForwardPipeline extends RenderPipeline { return true; } - public destroy(): void { + public destroy() { this.destroyFlows(); this.clearRenderPasses(); + this.destroyUBOs(); this.destroyQuadInputAssembler(); } + }; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 5c7fd4c6a9..f56eb8f420 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -6,16 +6,45 @@ import { GFXDevice } from "../gfx/device"; import { GFXBuffer } from "../gfx/buffer"; import { GFXInputAssembler, GFXInputAttribute } from "../gfx/input-assembler"; import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../gfx/define"; +import { Camera } from "../renderer/scene/camera"; +import vec4 from "../core/vmath/vec4"; +import mat4 from "../core/vmath/mat4"; export enum RenderPassStage { - FORWARD = 0, - CUSTOM = 100, + FORWARD = 100, }; -export interface QuadVertex { - position: number[]; - texCoord: number[]; -} +export class UBOGlobal { + static TIME_OFFSET: number = 0; + static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; + static SCREEN_SCALE_OFFSET: number = UBOGlobal.SCREEN_SIZE_OFFSET + 4; + static MAT_VIEW_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4; + static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16; + static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; + static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16; + static MAT_VIEW_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; + static MAT_VIEW_PROJ_INV_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_OFFSET + 16; + static CAMERA_POS_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET + 16; + static COUNT: number = UBOGlobal.CAMERA_POS_OFFSET + 4; + static SIZE: number = UBOGlobal.COUNT * 4; + + view: Float32Array = new Float32Array(UBOGlobal.COUNT); +}; + +export class UBOLocal { + static MAT_WORLD_OFFSET: number = 0; + static MAT_WORLD_VIEW_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16; + static MAT_WORLD_VIEW_PROJ_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_OFFSET + 16; + static WORLD_POS_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_PROJ_OFFSET + 16; + static COUNT: number = UBOLocal.WORLD_POS_OFFSET + 4; + static SIZE: number = UBOGlobal.COUNT * 4; + + view: Float32Array = new Float32Array(UBOLocal.COUNT); +}; + +let _vec4Array = new Float32Array(4); +let _mat4Array = new Float32Array(16); +let _outMat = new mat4; export abstract class RenderPipeline { @@ -28,6 +57,9 @@ export abstract class RenderPipeline { public abstract destroy(); public render(view: RenderView) { + + this.updateUBOs(view); + for (let i = 0; i < this._flows.length; ++i) { this._flows[i].render(view); } @@ -89,8 +121,16 @@ export abstract class RenderPipeline { return this._flows; } - public get quadIA(): GFXInputAssembler | null { - return this._quadIA; + public get quadIA(): GFXInputAssembler { + return this._quadIA; + } + + public get uboGlobal(): UBOGlobal { + return this._uboGlobal; + } + + public get globalUBO(): GFXBuffer { + return this._globalUBO; } protected createQuadInputAssembler(): boolean { @@ -174,6 +214,79 @@ export abstract class RenderPipeline { } } + protected createUBOs(): boolean { + this._globalUBO = this._root.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOGlobal.SIZE, + }); + + if(!this._globalUBO) { + return false; + } + + return true; + } + + protected destroyUBOs() { + if(this._globalUBO) { + this._globalUBO.destroy(); + this._globalUBO = null; + } + } + + protected updateUBOs(view: RenderView) { + let camera = view.camera; + camera.update(); + + // update UBOGlobal + _vec4Array[0] = this._root.frameTime; + _vec4Array[1] = 0.0; + _vec4Array[2] = 0.0; + _vec4Array[3] = 0.0; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.TIME_OFFSET); + + _vec4Array[0] = this._root.device.width; + _vec4Array[1] = this._root.device.height; + _vec4Array[2] = 1.0/_vec4Array[0]; + _vec4Array[3] = 1.0/_vec4Array[1]; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SIZE_OFFSET); + + _vec4Array[0] = 1.0; + _vec4Array[1] = 1.0; + _vec4Array[2] = 1.0; + _vec4Array[3] = 1.0; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SCALE_OFFSET); + + mat4.array(_mat4Array, camera.matView); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_OFFSET); + + mat4.invert(_outMat, camera.matView); + mat4.array(_mat4Array, _outMat); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_INV_OFFSET); + + mat4.array(_mat4Array, camera.matProj); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_OFFSET); + + mat4.invert(_outMat, camera.matProj); + mat4.array(_mat4Array, _outMat); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_INV_OFFSET); + + mat4.array(_mat4Array, camera.matViewProj); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_OFFSET); + + mat4.invert(_outMat, camera.matViewProj); + mat4.array(_mat4Array, _outMat); + this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); + + vec4.array(_vec4Array, camera.position); + _vec4Array[3] = 1.0; + this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); + + // update ubos + (this._globalUBO).update(this._uboGlobal.view); + } + protected _root: Root; protected _device: GFXDevice; protected _renderPasses: Map = new Map; @@ -181,4 +294,6 @@ export abstract class RenderPipeline { protected _quadVB: GFXBuffer | null = null; protected _quadIB: GFXBuffer | null = null; protected _quadIA: GFXInputAssembler | null = null; + protected _uboGlobal: UBOGlobal = new UBOGlobal; + protected _globalUBO: GFXBuffer | null = null; }; diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index aa58ea44d0..32447eaf43 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -49,13 +49,13 @@ export class RenderView { } public attach(camera: Camera) { - this._sceneMgr = camera.sceneMgr; + this._scene = camera.scene; this._camera = camera; this._isAttached = true; } public detach() { - this._sceneMgr = null; + this._scene = null; this._camera = null; this._isAttached = false; } @@ -92,12 +92,20 @@ export class RenderView { return this._height; } + public get camera(): Camera | null { + return this._camera; + } + + public get scene(): RenderScene | null { + return this._scene; + } + private _name: string = ""; private _window: GFXWindow | null = null; private _priority: number = 0; private _width: number = 0; private _height: number = 0; - private _sceneMgr: RenderScene | null = null; + private _scene: RenderScene | null = null; private _camera: Camera | null = null; private _isAttached: boolean = false; private _isEnable: boolean = true; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 1782923d86..8b7e00f4c1 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -39,8 +39,8 @@ export class Pass { const renderPass = cc.director.root.pipeline.getRenderPass(pass._stage); if (!renderPass) { console.error('create render pass failed'); return pass; } const bs = new GFXBlendState(); - if (info.BlendState) { - const bsInfo = Object.assign({}, info.BlendState); + if (info.blendState) { + const bsInfo = Object.assign({}, info.blendState); if (bsInfo.targets) { bsInfo.targets.forEach((t, i) => Object.assign( bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); @@ -51,8 +51,8 @@ export class Pass { pass._pipelineState = device.createPipelineState({ primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, - rs: Object.assign(new GFXRasterizerState(), info.RasterizerState), - dss: Object.assign(new GFXDepthStencilState(), info.DepthStencilState), + rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), + dss: Object.assign(new GFXDepthStencilState(), info.rasterizerState), is: new GFXInputState(), bs, shader, layout, renderPass, }); @@ -60,6 +60,7 @@ export class Pass { } get programName() { return this._programName; } + get pipelineState(): GFXPipelineState { return this._pipelineState; } protected _device: GFXDevice | null = null; protected _programName: string = ''; diff --git a/cocos/renderer/index.js b/cocos/renderer/index.js index 593e989d8e..cd824b1e0d 100644 --- a/cocos/renderer/index.js +++ b/cocos/renderer/index.js @@ -10,7 +10,7 @@ import InputAssembler from './core/input-assembler'; import View from './core/view'; import Light from './scene/light'; -import Camera from './scene/camera'; +import { Camera } from './scene/camera'; import Model from './scene/model'; import Scene from './scene/scene'; diff --git a/cocos/renderer/scene/camera.js b/cocos/renderer/scene/camera.js deleted file mode 100644 index 63dd0323b4..0000000000 --- a/cocos/renderer/scene/camera.js +++ /dev/null @@ -1,478 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { color4, vec3, mat4, lerp } from '../../core/vmath'; -import { ray } from '../../3d/geom-utils'; -import enums from '../enums'; - -let _matView = mat4.create(); -let _matProj = mat4.create(); -let _matViewProj = mat4.create(); -let _matInvViewProj = mat4.create(); -let _tmp_v3 = vec3.create(); -let _tmp2_v3 = vec3.create(); - -/** - * A representation of a camera instance - */ -export default class Camera { - /** - * Setup a default perspective camera - */ - constructor(scene, name) { - - this._scene = scene; - this._name = name; - this._enable = false; - - this._poolID = -1; - this._node = null; - - // - this._projection = enums.PROJ_PERSPECTIVE; - - // priority. the smaller one will be rendered first - this._priority = 0; - - // clear options - this._color = color4.create(); - this._depth = 1; - this._stencil = 0; - this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; - this._clearModel = null; - - // stages & framebuffer - this._stages = 0; - this._framebuffer = null; - - // projection properties - this._near = 0.01; - this._far = 1000.0; - this._fov = Math.PI/4.0; // vertical fov - this._rect = { - x: 0, y: 0, w: 1, h: 1 - }; - - // ortho properties - this._orthoHeight = 10; - } - - get scene() { - return this._scene; - } - - get name() { - return this._name; - } - - /** - * Get the hosting node of this camera - * @returns {Node} the hosting node - */ - getNode() { - return this._node; - } - - /** - * Set the hosting node of this camera - * @param {Node} node the hosting node - */ - setNode(node) { - this._node = node; - } - - /** - * Get the projection type of the camera - * @returns {number} camera projection type - */ - getType() { - return this._projection; - } - - /** - * Set the projection type of the camera - * @param {number} type camera projection type - */ - setType(type) { - this._projection = type; - } - - /** - * Get the priority of the camera - * @returns {number} camera priority - */ - getPriority() { - return this._priority; - } - - /** - * Set the priority of the camera - * @param {number} priority camera priority - */ - setPriority(priority) { - this._priority = priority; - } - - /** - * Get the orthogonal height of the camera - * @returns {number} camera height - */ - getOrthoHeight() { - return this._orthoHeight; - } - - /** - * Set the orthogonal height of the camera - * @param {number} val camera height - */ - setOrthoHeight(val) { - this._orthoHeight = val; - } - - /** - * Get the field of view of the camera - * @returns {number} camera field of view - */ - getFov() { - return this._fov; - } - - /** - * Set the field of view of the camera - * @param {number} fov camera field of view - */ - setFov(fov) { - this._fov = fov; - } - - /** - * Get the near clipping distance of the camera - * @returns {number} camera near clipping distance - */ - getNear() { - return this._near; - } - - /** - * Set the near clipping distance of the camera - * @param {number} near camera near clipping distance - */ - setNear(near) { - this._near = near; - } - - /** - * Get the far clipping distance of the camera - * @returns {number} camera far clipping distance - */ - getFar() { - return this._far; - } - - /** - * Set the far clipping distance of the camera - * @param {number} far camera far clipping distance - */ - setFar(far) { - this._far = far; - } - - /** - * Get the clear color of the camera - * @returns {color4} out the receiving color vector - */ - getColor(out) { - return color4.copy(out, this._color); - } - - /** - * Set the clear color of the camera - * @param {number} r red channel of camera clear color - * @param {number} g green channel of camera clear color - * @param {number} b blue channel of camera clear color - * @param {number} a alpha channel of camera clear color - */ - setColor(r, g, b, a) { - color4.set(this._color, r, g, b, a); - } - - /** - * Get the clear depth of the camera - * @returns {number} camera clear depth - */ - getDepth() { - return this._depth; - } - - /** - * Set the clear depth of the camera - * @param {number} depth camera clear depth - */ - setDepth(depth) { - this._depth = depth; - } - - /** - * Get the clearing stencil value of the camera - * @returns {number} camera clearing stencil value - */ - getStencil() { - return this._stencil; - } - - /** - * Set the clearing stencil value of the camera - * @param {number} stencil camera clearing stencil value - */ - setStencil(stencil) { - this._stencil = stencil; - } - - /** - * Get the clearing flags of the camera - * @returns {number} camera clearing flags - */ - getClearFlags() { - return this._clearFlags; - } - - /** - * Set the clearing flags of the camera - * @param {number} flags camera clearing flags - */ - setClearFlags(flags) { - this._clearFlags = flags; - } - - /** - * Get the rect of the camera - * @param {Object} out the receiving object - * @returns {Object} camera rect - */ - getRect(out) { - out.x = this._rect.x; - out.y = this._rect.y; - out.w = this._rect.w; - out.h = this._rect.h; - - return out; - } - - /** - * Set the rect of the camera - * @param {Number} x - [0,1] - * @param {Number} y - [0,1] - * @param {Number} w - [0,1] - * @param {Number} h - [0,1] - */ - setRect(x, y, w, h) { - this._rect.x = x; - this._rect.y = y; - this._rect.w = w; - this._rect.h = h; - } - - /** - * Get the stages of the camera - * @returns {string[]} camera stages - */ - getStages() { - return this._stages; - } - - /** - * Set the stages of the camera - * @param {number} stages camera stages - */ - setStages(stages) { - this._stages = stages; - } - - /** - * Get the framebuffer of the camera - * @returns {FrameBuffer} camera framebuffer - */ - getFramebuffer() { - return this._framebuffer; - } - - /** - * Set the framebuffer of the camera - * @param {FrameBuffer} framebuffer camera framebuffer - */ - setFramebuffer(framebuffer) { - this._framebuffer = framebuffer; - } - - _calcMatrices(width, height) { - // view matrix - this._node.getWorldRT(_matView); - mat4.invert(_matView, _matView); - - // projection matrix - let aspect = width / height; - if (this._projection === enums.PROJ_PERSPECTIVE) { - mat4.perspective(_matProj, - this._fov, - aspect, - this._near, - this._far - ); - } else { - let x = this._orthoHeight * aspect; - let y = this._orthoHeight; - mat4.ortho(_matProj, - -x, x, -y, y, this._near, this._far - ); - } - - // view-projection - mat4.mul(_matViewProj, _matProj, _matView); - // inv view-projection - mat4.invert(_matInvViewProj, _matViewProj); - } - - /** - * extract a view of this camera - * @param {View} out the receiving view - * @param {number} width framebuffer width - * @param {number} height framebuffer height - */ - extractView(out, width, height) { - if (this._framebuffer) { - width = this._framebuffer._width; - height = this._framebuffer._height; - } - - // priority - out._priority = this._priority; - - // rect - out._rect.x = this._rect.x * width; - out._rect.y = this._rect.y * height; - out._rect.w = this._rect.w * width; - out._rect.h = this._rect.h * height; - - // clear opts - out._color = this._color; - out._depth = this._depth; - out._stencil = this._stencil; - out._clearFlags = this._clearFlags; - out._clearModel = this._clearModel; - - // stages & framebuffer - out._stages = this._stages; - out._framebuffer = this._framebuffer; - - this._calcMatrices(width, height); - mat4.copy(out._matView, _matView); - mat4.copy(out._matProj, _matProj); - mat4.copy(out._matViewProj, _matViewProj); - mat4.copy(out._matInvViewProj, _matInvViewProj); - - // update view's frustum - out._frustum.update(_matViewProj, _matInvViewProj); - } - - /** - * transform a screen position to a world space ray - * @param {number} x the screen x position to be transformed - * @param {number} y the screen y position to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @param {ray} out the resulting ray - * @returns {Ray} the resulting ray - */ - screenPointToRay(x, y, width, height, out) { - out = out || ray.create(); - this._calcMatrices(width, height); - - let cx = this._rect.x * width; - let cy = this._rect.y * height; - let cw = this._rect.w * width; - let ch = this._rect.h * height; - - // far plane intersection - vec3.set(_tmp2_v3, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); - vec3.transformMat4(_tmp2_v3, _tmp2_v3, _matInvViewProj); - - if (this._projection === enums.PROJ_PERSPECTIVE) { - // camera origin - this._node.getWorldPosition(_tmp_v3); - } else { - // near plane intersection - vec3.set(_tmp_v3, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); - vec3.transformMat4(_tmp_v3, _tmp_v3, _matInvViewProj); - } - - return ray.fromPoints(out, _tmp_v3, _tmp2_v3); - } - - /** - * transform a screen position to world space - * @param {vec3} out the resulting vector - * @param {vec3} screenPos the screen position to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @returns {vec3} the resulting vector - */ - screenToWorld(out, screenPos, width, height) { - this._calcMatrices(width, height); - - let cx = this._rect.x * width; - let cy = this._rect.y * height; - let cw = this._rect.w * width; - let ch = this._rect.h * height; - - if (this._projection === enums.PROJ_PERSPECTIVE) { - // calculate screen pos in far clip plane - vec3.set(out, - (screenPos.x - cx) / cw * 2 - 1, - (screenPos.y - cy) / ch * 2 - 1, - 1.0 - ); - - // transform to world - vec3.transformMat4(out, out, _matInvViewProj); - - // lerp to depth z - this._node.getWorldPosition(_tmp_v3); - - vec3.lerp(out, _tmp_v3, out, lerp(this._near / this._far, 1, screenPos.z)); - } else { - vec3.set(out, - (screenPos.x - cx) / cw * 2 - 1, - (screenPos.y - cy) / ch * 2 - 1, - screenPos.z * 2 - 1 - ); - - // transform to world - vec3.transformMat4(out, out, _matInvViewProj); - } - - return out; - } - - /** - * transform a world space position to screen space - * @param {vec3} out the resulting vector - * @param {vec3} worldPos the world space position to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @returns {vec3} the resulting vector - */ - worldToScreen(out, worldPos, width, height) { - this._calcMatrices(width, height); - - let cx = this._rect.x * width; - let cy = this._rect.y * height; - let cw = this._rect.w * width; - let ch = this._rect.h * height; - - vec3.transformMat4(out, worldPos, _matViewProj); - out.x = cx + (out.x + 1) * 0.5 * cw; - out.y = cy + (out.y + 1) * 0.5 * ch; - out.z = out.z * 0.5 + 0.5; - - return out; - } -} diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts new file mode 100644 index 0000000000..5d1f7a4bdf --- /dev/null +++ b/cocos/renderer/scene/camera.ts @@ -0,0 +1,141 @@ +import { RenderScene } from "./render-scene"; +import Node from "../../scene-graph/node"; +import vec3 from "../../core/vmath/vec3"; +import mat4 from "../../core/vmath/mat4"; + +export enum CameraProjection { + PERSPECTIVE, + ORTHO, +}; + +export class Camera { + + constructor(scene: RenderScene, name: string) { + this._scene = scene; + this._name = name; + this._node = scene.createNode({ name: name + "Node", isStatic: false }); + this._proj = CameraProjection.PERSPECTIVE; + + let window = scene.root.mainWindow; + if (window) { + this._width = window.width; + this._height = window.height; + } else { + this._width = 1; + this._height = 1; + } + + this._aspect = this._width / this._height; + this._fov = Math.PI / 4; + this._nearClip = 1.0; + this._farClip = 10000.0; + } + + public resize(width: number, height: number) { + this._width = width; + this._height = height; + this._aspect = this._width / this._height; + } + + public update() { + // view matrix + this._node.getWorldRT(this._matView); + mat4.invert(this._matView, this._matView); + + // projection matrix + if (this._proj === CameraProjection.PERSPECTIVE) { + mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip); + } else { + let x = this._width; + let y = this._height; + mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip); + } + + // view-projection + mat4.mul(this._matViewProj, this._matProj, this._matView); + } + + public set fov(fov: number) { + this._fov = fov; + } + + public set nearClip(nearClip: number) { + this._nearClip = nearClip; + } + + public set farClip(farClip: number) { + this._farClip = farClip; + } + + public get scene(): RenderScene { + return this._scene; + } + + public get name(): string { + return this._name; + } + + public get node(): Node { + return this._node; + } + + public get width(): number { + return this._width; + } + + public get height(): number { + return this._height; + } + + public get aspect(): number { + return this._aspect; + } + + public get fov(): number { + return this._fov; + } + + public get nearClip(): number { + return this._nearClip; + } + + public get farClip(): number { + return this._farClip; + } + + public get matView(): number { + return this._matView; + } + + public get matProj(): number { + return this._matProj; + } + + public get matViewProj(): number { + return this._matViewProj; + } + + public set position(pos: vec3) { + this._node.setWorldPosition(pos.x, pos.y, pos.z); + } + + public get position(): vec3 { + this._node.getWorldPosition(this._position); + return this._position; + } + + private _scene: RenderScene; + private _name: string; + private _node: Node; + private _proj: CameraProjection; + private _width: number; + private _height: number; + private _aspect: number; + private _fov: number; + private _nearClip: number; + private _farClip: number; + private _matView: mat4 = new mat4; + private _matProj: mat4 = new mat4; + private _matViewProj: mat4 = new mat4; + private _position: vec3 = new vec3; +}; diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 13cfd68490..74bb8197f9 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -68,7 +68,7 @@ export default class Model { } } - get scene(): RenderScene { + get scene(): RenderScene | null { return this._scene; } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 56f95eed2c..d8ef313727 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,7 +1,8 @@ import Node from "../../scene-graph/node"; -import Camera from "./camera"; import Light from "./light"; import Model from "./model"; +import { Camera } from "./camera"; +import { Root } from "../../core/root"; export interface RenderSceneInfo { name: string; @@ -15,15 +16,13 @@ export interface SceneNodeInfo { export class RenderScene { - constructor() { + constructor(root: Root) { + this._root = root; } public initialize(info: RenderSceneInfo): boolean { this._name = info.name; - - let cameraNode = this.createNode({ name: "mainCamNode", isStatic: false }); this._mainCamera = this.createCamera("mainCamera"); - this._mainCamera.setNode(cameraNode); return true; } @@ -80,9 +79,8 @@ export class RenderScene { public getCamera(name: string): Camera | null { for (let i = 0; i < this._cameras.length; ++i) { - let camera = this._cameras[i]; - if (camera.getName() === name) { - return camera; + if (this._cameras[i].name === name) { + return this._cameras[i]; } } @@ -143,6 +141,10 @@ export class RenderScene { return this._modelId++; } + public get root(): Root { + return this._root; + } + public get name(): string { return this._name; } @@ -163,6 +165,7 @@ export class RenderScene { return this._models; } + private _root: Root; private _name: string = ""; private _nodes: Map = new Map; private _cameras: Camera[] = []; From 911f1d9af890ba3b4c2cf28a96b2d83257b2fa87 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 7 Jan 2019 19:07:58 +0800 Subject: [PATCH 033/267] modify copyBufferToTexture(), and add copyImageSourceToTexture() --- cocos/gfx/device.ts | 10 ++++-- cocos/gfx/input-assembler.ts | 1 - cocos/gfx/webgl/webgl-commands.ts | 4 +-- cocos/gfx/webgl/webgl-device.ts | 54 +++++++++++++--------------- cocos/pipeline/forward/test-stage.ts | 27 +++++++++++--- cocos/pipeline/render-queue.ts | 51 ++++++++++++++++++++++++++ 6 files changed, 109 insertions(+), 38 deletions(-) create mode 100644 cocos/pipeline/render-queue.ts diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index d1e3f93686..e4a1fa5c62 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -13,7 +13,7 @@ import { GFXCommandBufferInfo, GFXCommandBuffer } from './command-buffer'; import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './command-allocator'; import { GFXWindowInfo, GFXWindow } from './window'; import { GFXBindingLayoutInfo, GFXBindingLayout } from './binding-layout'; -import { GFXRect } from './define'; +import { GFXRect, GFXBufferTextureCopy } from './define'; export enum GFXFeature { }; @@ -45,12 +45,17 @@ export abstract class GFXDevice { public abstract createWindow(info: GFXWindowInfo): GFXWindow | null; public abstract present(); - public abstract copyBufferToTexture2D(buffer: ArrayBuffer, texture: GFXTexture, rect?: GFXRect); + public abstract copyBufferToTexture(buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyImageSourceToTexture(source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]); public get canvas(): HTMLCanvasElement { return this._canvas; } + public get canvas2D(): HTMLCanvasElement { + return this._canvas2D; + } + public get queue(): GFXQueue { return this._queue; } @@ -112,6 +117,7 @@ export abstract class GFXDevice { } protected _canvas: HTMLCanvasElement | null = null; + protected _canvas2D: HTMLCanvasElement | null = null; protected _deviceName: string = ""; protected _renderer: string = ""; protected _vendor: string = ""; diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index fe18052dd4..9bac9ff01f 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -114,6 +114,5 @@ export abstract class GFXInputAssembler { protected _vertexOffset: number = 0; protected _instanceCount: number = 0; protected _firstInstance: number = 0; - protected _isIndirect: boolean = false; }; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 09748aedb5..b8cc6ef947 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1987,7 +1987,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { let cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; if (cmd7.gpuBuffer && cmd7.gpuBuffer.viewUI8 && cmd7.gpuTexture) { - WebGLCmdFuncCopyBufferToTexture2D(device, cmd7.gpuBuffer.viewUI8, cmd7.gpuTexture, cmd7.regions); + WebGLCmdFuncCopyBufferToTexture(device, cmd7.gpuBuffer.viewUI8, cmd7.gpuTexture, cmd7.regions); } break; @@ -1996,7 +1996,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // for } -export function WebGLCmdFuncCopyBufferToTexture2D( +export function WebGLCmdFuncCopyBufferToTexture( device: WebGLGFXDevice, bufferView: Uint8Array, gpuTexture: WebGLGPUTexture, diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 5e28863b76..b418eec772 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -4,7 +4,7 @@ import { WebGLGFXBuffer } from './webgl-buffer'; import { WebGLGFXQueue } from './webgl-queue'; import { WebGLStateCache } from './webgl-state-cache'; import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; -import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncCopyBufferToTexture2D } from './webgl-commands'; +import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncCopyBufferToTexture } from './webgl-commands'; import { GFXTexture, GFXTextureInfo } from '../texture'; import { GFXTextureViewInfo, GFXTextureView } from '../texture-view'; import { GFXRenderPassInfo, GFXRenderPass } from '../render-pass'; @@ -31,7 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat, GFXBufferTextureCopy, GFXMemoryUsageBit, GFXTextureLayout, GFXTextureSubres, GFXRect } from '../define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat, GFXBufferTextureCopy, GFXMemoryUsageBit, GFXTextureLayout, GFXTextureSubres, GFXRect, GFXFormatInfos } from '../define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -103,6 +103,8 @@ export class WebGLGFXDevice extends GFXDevice { return false; } + this._canvas2D = document.createElement('canvas'); + console.info('WebGL device initialized.'); this._deviceName = "WebGL"; @@ -382,34 +384,28 @@ export class WebGLGFXDevice extends GFXDevice { public present() { } - public copyBufferToTexture2D(buffer: ArrayBuffer, texture: GFXTexture, rect?: GFXRect) { - + public copyBufferToTexture(buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + let bufferView = new Uint8Array(buffer); + WebGLCmdFuncCopyBufferToTexture(this, bufferView, (texture).gpuTexture, regions); + } - let x, y, w, h; + public copyImageSourceToTexture(source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - if(rect !== undefined) { - x = rect.x; - y = rect.y; - w = rect.width; - h = rect.height; - } else { - x = 0; - y = 0; - w = texture.width; - h = texture.height; + if (this._canvas2D) { + let context = this._canvas2D.getContext('2d'); + + if (context) { + this._canvas2D.width = texture.width; + this._canvas2D.height = texture.height; + context.drawImage(source, 0, 0); + + let imgData = context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height); + let bufferView = new Uint8Array(imgData.data); + + WebGLCmdFuncCopyBufferToTexture(this, bufferView, (texture).gpuTexture, regions); + } } - - let region: GFXBufferTextureCopy = { - buffOffset: 0, - buffStride: 0, - buffTexHeight: 0, - texOffset: { x: x, y: y, z: 0 }, - texExtent: { width: w, height: h, depth: 1 }, - texSubres: new GFXTextureSubres, - }; - - WebGLCmdFuncCopyBufferToTexture2D(this, bufferView, (texture).gpuTexture, [region]); } public get gl(): WebGLRenderingContext { @@ -638,9 +634,9 @@ export class WebGLGFXDevice extends GFXDevice { let glMinFilter = WebGLRenderingContext.NONE; let glMagFilter = WebGLRenderingContext.NONE; - let minFilter = (info.minFilter !== undefined? info.minFilter : GFXFilter.LINEAR); - let magFilter = (info.magFilter !== undefined? info.magFilter : GFXFilter.LINEAR); - let mipFilter = (info.mipFilter !== undefined? info.mipFilter : GFXFilter.NONE); + let minFilter = (info.minFilter !== undefined ? info.minFilter : GFXFilter.LINEAR); + let magFilter = (info.magFilter !== undefined ? info.magFilter : GFXFilter.LINEAR); + let mipFilter = (info.mipFilter !== undefined ? info.mipFilter : GFXFilter.NONE); if (minFilter === GFXFilter.LINEAR || minFilter === GFXFilter.ANISOTROPIC) { if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 8a4f67b2e3..414c8fd43d 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -28,10 +28,13 @@ let _shader_vs = `#version 100 attribute vec2 a_position; attribute vec2 a_texCoord; +//uniform mat4 u_matWorldViewProj; + varying vec2 v_texCoord; void main() { gl_Position = vec4(a_position, 0.0, 1.0); + //gl_Position = u_matWorldViewProj * vec4(a_position, 0.0, 1.0); v_texCoord = a_texCoord; }`; @@ -87,6 +90,10 @@ export class TestStage extends RenderStage { name: "test", stages: [vsStage, fsStage], blocks: [{ + binding: 0, name: "Global", uniforms: [ + { name: "u_matWorldViewProj", type: GFXType.MAT4, count: 1 }, + ] + }, { binding: 5, name: "UBO", uniforms: [ { name: "u_color", type: GFXType.FLOAT4, count: 1 }, ] @@ -224,8 +231,8 @@ export class TestStage extends RenderStage { cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); cmdBuff.bindPipelineState(this._pipelineState); cmdBuff.bindBindingLayout(this._bindingLayout); - cmdBuff.bindInputAssembler(this._pipeline.quadIA); - cmdBuff.draw(this._pipeline.quadIA); + cmdBuff.bindInputAssembler(this._pipeline.quadIA); + cmdBuff.draw(this._pipeline.quadIA); cmdBuff.endRenderPass(); cmdBuff.end(); @@ -234,6 +241,7 @@ export class TestStage extends RenderStage { private loadTexture(image: HTMLImageElement): boolean { //let canvas2d = this._device.canvas.getContext("2d"); + /* let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); if (!context) { @@ -246,7 +254,7 @@ export class TestStage extends RenderStage { let imgData = context.getImageData(0, 0, image.width, image.height); let imgBuffer: ArrayBuffer = imgData.data; - //var buffer = image.currentSrc;//arraybuffer object + */ this._texture = this._device.createTexture({ type: GFXTextureType.TEX2D, @@ -271,7 +279,17 @@ export class TestStage extends RenderStage { return false; } - this._device.copyBufferToTexture2D(imgBuffer, this._texture); + let 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, @@ -290,6 +308,7 @@ export class TestStage extends RenderStage { return false; } + this._bindingLayout.bindBuffer(0, this.pipeline.globalUBO); this._bindingLayout.bindBuffer(5, this._ubo); this._bindingLayout.bindTextureView(10, this._texView); this._bindingLayout.bindSampler(10, this._sampler); diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts new file mode 100644 index 0000000000..d33721abb1 --- /dev/null +++ b/cocos/pipeline/render-queue.ts @@ -0,0 +1,51 @@ +import { Pass } from "../renderer/core/pass"; +import Model from "../renderer/scene/model"; + +export class RenderItem { + hash: number; + model: Model; + pass: Pass; + + constructor(hash: number, model: Model, pass: Pass) { + this.hash = hash; + this.model = model; + this.pass = pass; + } +}; + +export class RenderQueue { + + constructor() { + } + + public add(model: Model, pass: Pass) { + let pso = pass.pipelineState; + + let isTransparent = pso.blendState.targets[0].blend; + + let hash: number = 0; + + if(!isTransparent) { + // Opaque objects are sorted by depth front to back, then by shader id. + hash = (0 << 63) | (pso.shader.id << 13); + + this._opaques.push({hash, model, pass}); + } else { + // Transparent objects are sorted by depth back to front, then by by shader id. + hash = (1 << 63) | (pso.shader.id << 13); + + this._transparents.push({hash, model, pass}); + } + } + + public get opaques(): RenderItem[] { + return this._opaques; + } + + public get transparents(): RenderItem[] { + return this._transparents; + } + + private _opaques: RenderItem[] = []; + private _transparents: RenderItem[] = []; +}; From 47f8711dd53842d5109f708db1c67383744f61c7 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 3 Jan 2019 18:37:26 +0800 Subject: [PATCH 034/267] quick fix: initial canvas size --- playground/simple.html | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/playground/simple.html b/playground/simple.html index a31187dcd1..df8fad253b 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -31,6 +31,13 @@ - \ No newline at end of file + From 3a5926a673a230fd0ad5da2cc47e824f61e4ae46 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 3 Jan 2019 18:53:02 +0800 Subject: [PATCH 035/267] effect initialization --- cocos/3d/assets/effect-asset.ts | 30 ++++--- cocos/3d/assets/material.js | 4 +- cocos/3d/builtin/effects.js | 96 ++++++++++++----------- cocos/gfx/shader.ts | 2 +- cocos/gfx/webgl/webgl-commands.ts | 6 +- cocos/pipeline/forward/test-stage.ts | 4 +- cocos/renderer/core/effect.ts | 49 ++++++++---- cocos/renderer/core/pass.ts | 113 +++++++++++++++++++-------- cocos/renderer/core/program-lib.js | 84 ++++++-------------- 9 files changed, 211 insertions(+), 177 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 84689d613d..c6468a67c8 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -1,9 +1,9 @@ import Asset from '../../assets/CCAsset'; import { ccclass, property } from '../../core/data/class-decorator'; -import { PassInfo } from '../../renderer/core/pass'; +import { PassInfoBase } from '../../renderer/core/pass'; export interface TechniqueInfo { - passes: PassInfo[]; + passes: PassInfoBase[]; queue?: number; priority?: number; lod?: number; @@ -16,30 +16,38 @@ export interface PropertyInfo { pass?: number; } -export interface UniformInfo { +export interface BlockMember { name: string; type: number; - bindingType: number; + count: number; +} +export interface BlockInfo { + name: string; binding: number; defines: string[]; - members?: Array< { name: string, type: number } >; + size: number; + members: BlockMember[]; +} +export interface SamplerInfo { + name: string; + binding: number; + defines: string[]; + type: number; + count: number; } export interface DefineInfo { name: string; type: string; defines: string[]; } -export interface ExtensionInfo { - name: string; - define: string; -} export interface ShaderInfo { name: string; vert: string; frag: string; defines: DefineInfo[]; - uniforms: UniformInfo[]; - extensions: ExtensionInfo[]; + blocks: BlockInfo[]; + samplers: SamplerInfo[]; + dependencies: { [name: string]: string }; } const effects: { [name: string]: EffectAsset } = {}; diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js index c57b1a4f30..052604a415 100644 --- a/cocos/3d/assets/material.js +++ b/cocos/3d/assets/material.js @@ -124,9 +124,7 @@ class Material extends Asset { } this._effectAsset = effectAsset; if (!effectAsset) return; - this._effect = Effect.parseEffect(effectAsset); - for (let def in this._defines) - this._effect.define(def, this._defines[def]); + this._effect = Effect.parseEffect(effectAsset, this._defines); for (let prop in this._props) this.setProperty(prop, this._props[prop]); } diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 0374c43b4a..d2d9f94048 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,12 +1,50 @@ export default [ + { + "name": "builtin-effect-skybox", + "techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d"}], "priority": -1000}], + "properties": {"cubeMap": {"type": 32, "value": null}}, + "shaders": [ + { + "name": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d", + "vert": "\n attribute vec3 a_position;\n \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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 rotView = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\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": []} + ], + "blocks": [], + "samplers": [ + {"name": "cubeMap", "type": 32, "count": 1, "defines": [], "binding": 0} + ], + "dependencies": {} + } + ] + }, + { + "name": "builtin-effect-sprite", + "techniques": [{"queue": 2, "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "program": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6"}], "priority": 0}], + "properties": {"mainTexture": {"type": 29, "value": null}}, + "shaders": [ + { + "name": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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": [], + "samplers": [ + {"name": "mainTexture", "type": 29, "count": 1, "defines": [], "binding": 0} + ], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-unlit", - "techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "7781d6cc411d5facce7fc3d4aeb5349e804ddd9a58c002017c53682b"}], "priority": 0}], + "techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}], "priority": 0}], "properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": null}}, "shaders": [ { - "name": "7781d6cc411d5facce7fc3d4aeb5349e804ddd9a58c002017c53682b", - "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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_texCoord1;\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_texCoord1 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c", + "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_texCoord1;\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;\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_texCoord1 * 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": []}, @@ -14,53 +52,19 @@ export default [ {"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]}, {"name": "USE_COLOR", "type": "boolean", "defines": []} ], - "uniforms": [ - {"name": "TexCoords", "type": 0, "bindingType": 1, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ - {"name": "mainTiling", "type": 14}, - {"name": "mainOffset", "type": 14} + "blocks": [ + {"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "size": 16, "members": [ + {"name": "mainTiling", "type": 14, "count": 1}, + {"name": "mainOffset", "type": 14, "count": 1} ]}, - {"name": "mainTexture", "type": 29, "bindingType": 2, "defines": ["USE_TEXTURE"], "binding": 1}, - {"name": "Constant", "type": 0, "bindingType": 1, "defines": ["USE_COLOR"], "binding": 2, "members": [ - {"name": "color", "type": 16} + {"name": "Constant", "defines": ["USE_COLOR"], "binding": 1, "size": 16, "members": [ + {"name": "color", "type": 16, "count": 1} ]} ], - "extensions": [] - } - ] - }, - { - "name": "builtin-effect-skybox", - "techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "e4ea21ace566a0976909c9b0d082bf97c4a115f78bafe08d6c5edec7"}], "priority": -1000}], - "properties": {"cubeMap": {"type": 32, "value": null}}, - "shaders": [ - { - "name": "e4ea21ace566a0976909c9b0d082bf97c4a115f78bafe08d6c5edec7", - "vert": "\n attribute vec3 a_position;\n \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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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 rotView = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\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": []} + "samplers": [ + {"name": "mainTexture", "type": 29, "count": 1, "defines": ["USE_TEXTURE"], "binding": 2} ], - "uniforms": [ - {"name": "cubeMap", "type": 32, "bindingType": 2, "defines": [], "binding": 0} - ], - "extensions": [] - } - ] - }, - { - "name": "builtin-effect-sprite", - "techniques": [{"queue": 2, "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "program": "b28a508b291d9314faba527c0f13b99420d5feebd86bd4d38554b256"}], "priority": 0}], - "properties": {"mainTexture": {"type": 29, "value": null}}, - "shaders": [ - { - "name": "b28a508b291d9314faba527c0f13b99420d5feebd86bd4d38554b256", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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": [], - "uniforms": [ - {"name": "mainTexture", "type": 29, "bindingType": 2, "defines": [], "binding": 0} - ], - "extensions": [] + "dependencies": {} } ] }, diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index 980413e9ba..41d2451f9c 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -22,7 +22,7 @@ export class GFXUniformBlock { binding: number = -1; name: string = ""; //instance : string; - uniforms: GFXUniform[] = []; + members: GFXUniform[] = []; }; export class GFXUniformSampler { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index b8cc6ef947..c348a2eac1 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -897,15 +897,15 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG binding: block.binding, name: block.name, size: 0, - glUniforms: new Array(block.uniforms.length), + glUniforms: new Array(block.members.length), isUniformPackage: true, buffer: null, }; gpuShader.glBlocks[i] = glBlock; - for (let u = 0; u < block.uniforms.length; ++u) { - let uniform = block.uniforms[u]; + for (let u = 0; u < block.members.length; ++u) { + let uniform = block.members[u]; let glType = GFXTypeToWebGLType(uniform.type); let stride = WebGLGetTypeSize(glType); let size = stride * uniform.count; diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 414c8fd43d..4b4ab54166 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -90,11 +90,11 @@ export class TestStage extends RenderStage { name: "test", stages: [vsStage, fsStage], blocks: [{ - binding: 0, name: "Global", uniforms: [ + binding: 0, name: "Global", members: [ { name: "u_matWorldViewProj", type: GFXType.MAT4, count: 1 }, ] }, { - binding: 5, name: "UBO", uniforms: [ + binding: 5, name: "UBO", members: [ { name: "u_color", type: GFXType.FLOAT4, count: 1 }, ] }], diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index fbb02f7b7c..12e270204f 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -1,12 +1,13 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { EffectAsset, PropertyInfo, ShaderInfo, UniformInfo } from '../../3d/assets/effect-asset'; +import { EffectAsset, PropertyInfo, ShaderInfo } from '../../3d/assets/effect-asset'; import { CCObject } from '../../core/data'; import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; import { GFXType } from '../../gfx/define'; import Texture2D from '../gfx/texture-2d'; import TextureCube from '../gfx/texture-cube'; -import { Pass } from './pass'; +import { PassStage } from './constants'; +import { Pass, PassInfo } from './pass'; import Technique from './technique'; const _typeMap = { @@ -37,6 +38,10 @@ const typeCheck = (value: any, type: number) => { } }; +const createPass = () => { + +}; + let _globalTechLod = 600; type PropValue = number | boolean | Vec2 | Vec3 | Vec4 | Color | Mat4 | Texture2D | TextureCube | null; @@ -47,7 +52,7 @@ interface DependencyMap { [name: string]: string; } interface ProgramMap { [name: string]: ShaderInfo; } class Effect { - public static parseEffect(effect: EffectAsset, programs: ProgramMap) { return new Effect(); } + public static parseEffect(effect: EffectAsset, defines: DefineMap) { return new Effect(); } public static parseForInspector(effect: EffectAsset) { return { props: {}, defines: {} }; } public static setGlobalLod(lod: number) { _globalTechLod = lod; } @@ -161,8 +166,8 @@ class Effect { this._defines[def.name] = def.type === 'number' ? 0 : false)); // extensions this._dependencies = {}; - this._techniques[this._activeTechIdx].passes.forEach((pass) => this._programs[pass.programName].extensions - .filter((ext) => ext.define).forEach((ext) => this._dependencies[ext.define] = ext.name)); + this._techniques[this._activeTechIdx].passes.forEach((pass) => + Object.assign(this._dependencies, this._programs[pass.programName].dependencies)); } } @@ -206,6 +211,7 @@ interface ExtractedPropInfo { displayName?: string; } const parseProperties = (() => { + interface UniformInfo { type: number; defines: string[]; } function genPropInfo(propInfo: PropertyInfo, uniformInfo: UniformInfo): ExtractedPropInfo { const type = propInfo.type || uniformInfo.type; return { @@ -216,6 +222,13 @@ const parseProperties = (() => { defines: uniformInfo.defines, }; } + function findUniformInfo(program: ShaderInfo, name: string) { + for (const b of program.blocks) { + const i = b.members.find((u) => u.name === name); + if (i) { return Object.assign({ defines: b.defines }, i); } + } + return program.samplers.find((u) => u.name === name); + } return (effect: EffectAsset, programs: ProgramMap) => { const props: { [name: string]: ExtractedPropInfo } = {}; for (const prop of Object.keys(effect.properties)) { @@ -223,11 +236,11 @@ const parseProperties = (() => { let uniformInfo: UniformInfo | undefined; // always try getting the type from shaders first if (propInfo.tech !== undefined && propInfo.pass !== undefined) { - const pname = effect.techniques[propInfo.tech].passes[propInfo.pass].program; - uniformInfo = programs[pname].uniforms.find((u) => u.name === prop); + const p = effect.techniques[propInfo.tech].passes[propInfo.pass].program; + uniformInfo = findUniformInfo(programs[p], prop); } else { for (const p of Object.keys(programs)) { - uniformInfo = programs[p].uniforms.find((u) => u.name === prop); + uniformInfo = findUniformInfo(programs[p], prop); if (uniformInfo) { break; } } } @@ -243,7 +256,7 @@ const parseProperties = (() => { }; })(); -Effect.parseEffect = (effect: EffectAsset) => { +Effect.parseEffect = (effect: EffectAsset, defines: DefineMap) => { // techniques const techNum = effect.techniques.length; const techniques = new Array(techNum); @@ -253,12 +266,14 @@ Effect.parseEffect = (effect: EffectAsset) => { const passNum = tech.passes.length; const passes: Pass[] = new Array(passNum); for (let k = 0; k < passNum; ++k) { - const passInfo = tech.passes[k]; - passInfo.device = cc.game._gfxDevice; - passInfo.bindingLayoutInfo = programs[passInfo.program].uniforms.map((u) => { - return { name: u.name, type: u.bindingType, binding: u.binding }; - }); - passes[k] = Pass.create(passInfo); + const passInfo = tech.passes[k]; + passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines); + passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || PassStage.DEFAULT); + passInfo.blocks = programs[passInfo.program].blocks; + passInfo.samplers = programs[passInfo.program].samplers; + const pass = new Pass(cc.game._gfxDevice); + pass.initialize(passInfo); + passes[k] = pass; } techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); } @@ -266,13 +281,13 @@ Effect.parseEffect = (effect: EffectAsset) => { const props = parseProperties(effect, programs); const uniforms = {}; for (const pn of Object.keys(programs)) { - programs[pn].uniforms.forEach((u) => { + programs[pn].blocks.forEach((b) => b.members.forEach((u) => { const prop = props[u.name]; uniforms[u.name] = { type: prop ? prop.type : u.type, value: prop ? prop.value : getInstanceCtor(u.type)(), }; - }); + })); } return new Effect(effect.name, techniques, programs, uniforms); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 8b7e00f4c1..9217afd21d 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,18 +1,19 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { GFXBinding } from '../../gfx/binding-layout'; +import { BlockInfo, SamplerInfo } from '../../3d/assets/effect-asset'; +import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; -import { GFXPrimitiveMode } from '../../gfx/define'; +import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; +import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; import { GFXBlendState, GFXBlendTarget, 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 { PassStage } from './constants'; -export interface PassInfo { - // generated part - device: GFXDevice; - bindingLayoutInfo: GFXBinding[]; +export interface PassInfoBase { program: string; // effect-writer part primitive?: GFXPrimitiveMode; @@ -21,23 +22,43 @@ export interface PassInfo { depthStencilState?: GFXDepthStencilState; blendState?: GFXBlendState; } +export interface PassInfo extends PassInfoBase { + // generated part + blocks: BlockInfo[]; + samplers: SamplerInfo[]; + shader: GFXShader; + renderPass: GFXRenderPass; +} export class Pass { - public static create(info: PassInfo) { - const pass = new Pass(); - const device = pass._device = info.device; - pass._programName = info.program; - pass._stage = info.stage || PassStage.DEFAULT; + protected _device: GFXDevice; + protected _programName: string = ''; + protected _stage: PassStage = PassStage.DEFAULT; + protected _pipelineState: GFXPipelineState | null = null; + protected _pipelineLayout: GFXPipelineLayout | null = null; + protected _bindingLayout: GFXBindingLayout | null = null; + protected _buffers: GFXBuffer[] = []; + protected _samplers: GFXSampler[] = []; + + public constructor(device: GFXDevice) { + this._device = device; + } + + public initialize(info: PassInfo) { + const device = this._device; + this._programName = info.program; + this._stage = info.stage || PassStage.DEFAULT; // pipeline state - const shader = device.createShader({ name: info.program, stages: [] }); - if (!shader) { console.error('create shader failed'); return pass; } - const bindingLayout = device.createBindingLayout({ bindings: info.bindingLayoutInfo }); - if (!bindingLayout) { console.error('create binding layout failed'); return pass; } - const layout = device.createPipelineLayout({ layouts: [bindingLayout] }); - if (!layout) { console.error('create pipeline layout failed'); return pass; } - const renderPass = cc.director.root.pipeline.getRenderPass(pass._stage); - if (!renderPass) { console.error('create render pass failed'); return pass; } + const 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; } const bs = new GFXBlendState(); if (info.blendState) { const bsInfo = Object.assign({}, info.blendState); @@ -48,24 +69,52 @@ export class Pass { delete bsInfo.targets; Object.assign(bs, bsInfo); } - - pass._pipelineState = device.createPipelineState({ + this._pipelineState = device.createPipelineState({ primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), - dss: Object.assign(new GFXDepthStencilState(), info.rasterizerState), + dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState), is: new GFXInputState(), bs, - shader, layout, renderPass, + shader: info.shader, + layout: this._pipelineLayout, + renderPass: info.renderPass, }); - return pass; + + for (const u of info.blocks) { + const buffer = device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: u.size, + stride: 1, // N/A for blocks + }); + if (buffer) { + this._bindingLayout.bindBuffer(u.binding, buffer); + this._buffers.push(buffer); + } else { + console.error('create buffer failed.'); + } + } + for (const u of info.samplers) { + const sampler = device.createSampler({ + name: u.name, + // TODO: specify filter modes in effect + }); + if (sampler) { + this._bindingLayout.bindSampler(u.binding, sampler); + this._samplers.push(sampler); + } else { + console.error('create sampler failed.'); + } + } + } + + 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; } } get programName() { return this._programName; } - get pipelineState(): GFXPipelineState { return this._pipelineState; } - - protected _device: GFXDevice | null = null; - protected _programName: string = ''; - protected _stage: PassStage = PassStage.DEFAULT; - protected _pipelineState: GFXPipelineState | null = null; - protected _buffers: GFXBuffer[] = []; - protected _samplers: GFXSampler[] = []; + get pipelineState() { return this._pipelineState; } } diff --git a/cocos/renderer/core/program-lib.js b/cocos/renderer/core/program-lib.js index ebb6207d1d..508daa2b1d 100644 --- a/cocos/renderer/core/program-lib.js +++ b/cocos/renderer/core/program-lib.js @@ -1,56 +1,24 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import gfx from '../gfx'; +import { GFXShaderType } from '../../gfx/define'; let _shdID = 0; -function _generateDefines(device, defs, deps) { +function _generateDefines(device, defs, tDefs, deps) { let defines = []; - for (let def in defs) { - let d = defs[def]; - let result = typeof d === 'number' ? d : d ? 1 : 0; + for (const { name, type } of tDefs) { + let d = defs[name]; + let result = (type === 'number') ? (d || 0) : (d ? 1 : 0); // fallback if extension dependency not supported - if (result && deps[def] && !device[deps[def]]) { - console.warn(`${deps[def]} not supported on this platform, disabled ${def}`); + if (result && deps[name] && !device[deps[name]]) { + console.warn(`${deps[name]} not supported on this platform, disabled ${name}`); result = 0; } - defines.push(`#define ${def} ${result}`); + defines.push(`#define ${name} ${result}`); } return defines.join('\n'); } -function _replaceMacroNums(string, defs) { - let cache = {}; - let tmp = string; - for (let def in defs) { - if (Number.isInteger(defs[def])) { - cache[def] = defs[def]; - } - } - for (let def in cache) { - let reg = new RegExp(def, 'g'); - tmp = tmp.replace(reg, cache[def]); - } - return tmp; -} - -function _unrollLoops(string) { - let pattern = /#pragma for (\w+) in range\(\s*(\d+)\s*,\s*(\d+)\s*\)([\s\S]+?)#pragma endFor/g; - function replace(match, index, begin, end, snippet) { - let unroll = ''; - let parsedBegin = parseInt(begin); - let parsedEnd = parseInt(end); - if (parsedBegin.isNaN || parsedEnd.isNaN) { - console.error('Unroll For Loops Error: begin and end of range must be an int num.'); - } - for (let i = parsedBegin; i < parsedEnd; ++i) { - unroll += snippet.replace(new RegExp(`{${index}}`, 'g'), i); - } - return unroll; - } - return string.replace(pattern, replace); -} - export default class ProgramLib { /** * @param {gfx.Device} device @@ -79,9 +47,8 @@ export default class ProgramLib { * { name: 'shadow', type: 'boolean' }, * { name: 'lightCount', type: 'number', min: 1, max: 4 } * ], - * attributes: [{ name: 'a_position', type: 'vec3' }], - * uniforms: [{ name: 'color', type: 'vec4' }], - * extensions: [{ name: 'GL_OES_standard_derivatives', defines: ['USE_NORMAL_TEXTURE'] }], + * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }], + * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, * }; * programLib.define(program); */ @@ -158,12 +125,7 @@ export default class ProgramLib { return key << 8 | (tmpl.id & 0xff); } - /** - * @param {string} name - * @param {Object} defines - * @param {Object} extensions - */ - getProgram(name, defines, extensions, effectName) { + getGFXShader(name, defines = {}) { let key = this.getKey(name, defines); let program = this._cache[key]; if (program) { @@ -172,22 +134,20 @@ export default class ProgramLib { // get template let tmpl = this._templates[name]; - let customDef = _generateDefines(this._device, defines, extensions) + '\n'; - let vert = _replaceMacroNums(tmpl.vert, defines); - vert = customDef + _unrollLoops(vert); - let frag = _replaceMacroNums(tmpl.frag, defines); - frag = customDef + _unrollLoops(frag); + let customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n'; + let vert = customDef + tmpl.vert; + let frag = customDef + tmpl.frag; - program = new gfx.Program(this._device, { - vert, - frag + program = this._device.createShader({ + name, + blocks: tmpl.blocks, + samplers: tmpl.samplers, + stages: [ + { type: GFXShaderType.VERTEX, source: vert }, + { type: GFXShaderType.FRAGMENT, source: frag }, + ], }); - program.link(); - if (!program._linked) { - console.warn(`Failed to link program from effect ${effectName}.`); - } this._cache[key] = program; - return program; } } From 2a63d5d9345c37fe72695b1889008f7991163c5d Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Sat, 5 Jan 2019 14:53:49 +0800 Subject: [PATCH 036/267] programlib.ts --- cocos/3d/assets/effect-asset.ts | 9 +- cocos/core/game.js | 2 +- cocos/renderer/core/base-renderer.js | 2 +- cocos/renderer/core/effect.ts | 17 ++- cocos/renderer/core/program-lib.js | 153 --------------------------- cocos/renderer/core/program-lib.ts | 140 ++++++++++++++++++++++++ 6 files changed, 154 insertions(+), 169 deletions(-) delete mode 100644 cocos/renderer/core/program-lib.js create mode 100644 cocos/renderer/core/program-lib.ts diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index c6468a67c8..72f2bc82a7 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -38,6 +38,7 @@ export interface SamplerInfo { export interface DefineInfo { name: string; type: string; + range?: number[]; defines: string[]; } export interface ShaderInfo { @@ -47,10 +48,10 @@ export interface ShaderInfo { defines: DefineInfo[]; blocks: BlockInfo[]; samplers: SamplerInfo[]; - dependencies: { [name: string]: string }; + dependencies: Record; } -const effects: { [name: string]: EffectAsset } = {}; +const effects: Record = {}; @ccclass('cc.EffectAsset') export class EffectAsset extends Asset { @@ -73,13 +74,13 @@ export class EffectAsset extends Asset { } } public static getAll() { return effects; } - protected static _effects: { [name: string]: EffectAsset } = {}; + protected static _effects: Record = {}; @property public techniques: TechniqueInfo[] = []; @property - public properties: { [name: string]: PropertyInfo } = {}; + public properties: Record = {}; @property public shaders: ShaderInfo[] = []; diff --git a/cocos/core/game.js b/cocos/core/game.js index 1a00132f84..3f12762b50 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -31,7 +31,7 @@ import { addon } from './utils/js'; import renderer from '../renderer'; import builtinResMgr from '../3d/builtin/init'; -import ProgramLib from '../renderer/core/program-lib'; +import { ProgramLib } from '../renderer/core/program-lib'; /** * @module cc diff --git a/cocos/renderer/core/base-renderer.js b/cocos/renderer/core/base-renderer.js index d8686c2774..7a74ba46f6 100644 --- a/cocos/renderer/core/base-renderer.js +++ b/cocos/renderer/core/base-renderer.js @@ -6,7 +6,7 @@ import { intersect } from '../../3d/geom-utils'; import enums from '../enums'; import View from './view'; -import ProgramLib from './program-lib'; +import { ProgramLib } from './program-lib'; import { RenderQueue } from './constants'; let _m3_tmp = mat3.create(); diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 12e270204f..330f1e8a11 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -47,9 +47,6 @@ let _globalTechLod = 600; type PropValue = number | boolean | Vec2 | Vec3 | Vec4 | Color | Mat4 | Texture2D | TextureCube | null; interface PropertyMap { [name: string]: { type: number, value: PropValue }; } interface DefineMap { [name: string]: number | boolean; } -interface DependencyMap { [name: string]: string; } - -interface ProgramMap { [name: string]: ShaderInfo; } class Effect { public static parseEffect(effect: EffectAsset, defines: DefineMap) { return new Effect(); } @@ -60,16 +57,16 @@ class Effect { protected _techniques: Technique[] = []; protected _properties: PropertyMap = {}; protected _defines: DefineMap = {}; - protected _dependencies: DependencyMap = {}; + protected _dependencies: Record = {}; protected _maxLOD: number = 0; protected _activeTechIdx: number = 0; - protected _programs: ProgramMap = {}; + protected _programs: Record = {}; constructor( name: string = '', techniques: Technique[] = [new Technique()], - programs: ProgramMap = {}, + programs: Record = {}, properties: PropertyMap = {}, lod = -1 ) { @@ -193,7 +190,7 @@ const _ctorMap = { const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; const getInvolvedPrograms = (effect: EffectAsset) => { - const programs: ProgramMap = {}; + const programs: Record = {}; const lib = cc.game._programLib; effect.techniques.forEach((tech) => { tech.passes.forEach((pass) => { @@ -229,8 +226,8 @@ const parseProperties = (() => { } return program.samplers.find((u) => u.name === name); } - return (effect: EffectAsset, programs: ProgramMap) => { - const props: { [name: string]: ExtractedPropInfo } = {}; + return (effect: EffectAsset, programs: Record) => { + const props: Record = {}; for (const prop of Object.keys(effect.properties)) { const propInfo = effect.properties[prop]; let uniformInfo: UniformInfo | undefined; @@ -297,7 +294,7 @@ if (CC_EDITOR) { Effect.parseForInspector = (effect: EffectAsset) => { const programs = getInvolvedPrograms(effect); const props = parseProperties(effect, programs); - const defines: { [name: string]: ExtractedPropInfo } = {}; + const defines: Record = {}; for (const pn of Object.keys(programs)) { programs[pn].defines.forEach((define) => { defines[define.name] = { diff --git a/cocos/renderer/core/program-lib.js b/cocos/renderer/core/program-lib.js deleted file mode 100644 index 508daa2b1d..0000000000 --- a/cocos/renderer/core/program-lib.js +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { GFXShaderType } from '../../gfx/define'; - -let _shdID = 0; - -function _generateDefines(device, defs, tDefs, deps) { - let defines = []; - for (const { name, type } of tDefs) { - let d = defs[name]; - let result = (type === 'number') ? (d || 0) : (d ? 1 : 0); - // fallback if extension dependency not supported - if (result && deps[name] && !device[deps[name]]) { - console.warn(`${deps[name]} not supported on this platform, disabled ${name}`); - result = 0; - } - defines.push(`#define ${name} ${result}`); - } - return defines.join('\n'); -} - -export default class ProgramLib { - /** - * @param {gfx.Device} device - * @param {Array} templates - */ - constructor(device) { - this._device = device; - this._precision = `precision highp float;\n`; - this._templates = {}; - this._cache = {}; - } - - /** - * @param {string} name - * @param {string} vert - * @param {string} frag - * @param {Object[]} defines - * - * @example: - * // this object is auto-generated from your actual shaders - * let program = { - * name: 'foobar', - * vert: vertTmpl, - * frag: fragTmpl, - * defines: [ - * { name: 'shadow', type: 'boolean' }, - * { name: 'lightCount', type: 'number', min: 1, max: 4 } - * ], - * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }], - * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, - * }; - * programLib.define(program); - */ - define(prog) { - const { name, defines } = prog; - if (this._templates[name]) return; - - prog.id = ++_shdID; - prog.vert = this._precision + prog.vert; - prog.frag = this._precision + prog.frag; - - // calculate option mask offset - let offset = 0; - for (let i = 0; i < defines.length; ++i) { - let def = defines[i]; - let cnt = 1; - - if (def.type === 'number') { - let range = def.range || []; - def.min = range[0] || 0; - def.max = range[1] || 4; - cnt = Math.ceil(Math.log2(def.max - def.min)); - - def._map = function (value) { - return (value - this.min) << this._offset; - }.bind(def); - } else { // boolean - def._map = function (value) { - if (value) { - return 1 << this._offset; - } - return 0; - }.bind(def); - } - - offset += cnt; - def._offset = offset; - } - - // store it - this._templates[name] = prog; - } - - getTemplate(name) { - return this._templates[name]; - } - - /** - * Does this library has the specified program? - * @param {string} name - * @returns {boolean} - */ - hasProgram(name) { - return this._templates[name] !== undefined; - } - - /** - * @param {string} name - * @param {Object} defines - */ - getKey(name, defines) { - let tmpl = this._templates[name]; - let key = 0; - for (let i = 0; i < tmpl.defines.length; ++i) { - let tmplDefs = tmpl.defines[i]; - let value = defines[tmplDefs.name]; - if (value === undefined) { - continue; - } - - key |= tmplDefs._map(value); - } - - return key << 8 | (tmpl.id & 0xff); - } - - getGFXShader(name, defines = {}) { - let key = this.getKey(name, defines); - let program = this._cache[key]; - if (program) { - return program; - } - - // get template - let tmpl = this._templates[name]; - let customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n'; - let vert = customDef + tmpl.vert; - let frag = customDef + tmpl.frag; - - program = this._device.createShader({ - name, - blocks: tmpl.blocks, - samplers: tmpl.samplers, - stages: [ - { type: GFXShaderType.VERTEX, source: vert }, - { type: GFXShaderType.FRAGMENT, source: frag }, - ], - }); - this._cache[key] = program; - return program; - } -} diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts new file mode 100644 index 0000000000..999f851ca9 --- /dev/null +++ b/cocos/renderer/core/program-lib.ts @@ -0,0 +1,140 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { DefineInfo, ShaderInfo } from '../../3d/assets/effect-asset'; +import { GFXShaderType } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; +import { GFXShader } from '../../gfx/shader'; + +interface DefineMap { [name: string]: number | boolean; } +function _generateDefines( + device: GFXDevice, + defs: DefineMap, + tDefs: DefineInfo[], + deps: Record +) { + const defines: string[] = []; + for (const { name } of tDefs) { + const d = defs[name]; + let result = (typeof d === 'number') ? d : (d ? 1 : 0); + // fallback if extension dependency not supported + if (result && deps[name] && !device[deps[name]]) { + console.warn(`${deps[name]} not supported on this platform, disabled ${name}`); + result = 0; + } + defines.push(`#define ${name} ${result}`); + } + return defines.join('\n'); +} + +let _shdID = 0; +interface DefineRecord extends DefineInfo { + _map: (value: any) => number; + _offset: number; +} +interface ProgramInfo extends ShaderInfo { + id: number; + defines: DefineRecord[]; +} +export class ProgramLib { + protected _device: GFXDevice; + protected _precision: string; + protected _templates: Record; + protected _cache: Record; + + constructor(device: GFXDevice) { + this._device = device; + this._precision = `precision highp float;\n`; + this._templates = {}; + this._cache = {}; + } + + /** + * @example: + * // this object is auto-generated from your actual shaders + * let program = { + * name: 'foobar', + * vert: vertTmpl, + * frag: fragTmpl, + * defines: [ + * { name: 'shadow', type: 'boolean' }, + * { name: 'lightCount', type: 'number', range: [1, 4] } + * ], + * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }], + * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, + * }; + * programLib.define(program); + */ + public define(prog: ShaderInfo) { + if (this._templates[prog.name]) { return; } + const tmpl: any = Object.assign({ id: ++_shdID }, prog); + tmpl.vert = this._precision + prog.vert; + tmpl.frag = this._precision + prog.frag; + + // calculate option mask offset + let offset = 0; + for (const def of tmpl.defines) { + let cnt = 1; + if (def.type === 'number') { + const range = def.range || [0, 4]; + cnt = Math.ceil(Math.log2(range[1] - range[0])); + def._map = ((value: number) => (value - def.range[0]) << def._offset); + } else { // boolean + def._map = ((value: any) => (value ? (1 << def._offset) : 0)); + } + offset += cnt; + def._offset = offset; + } + // store it + this._templates[name] = tmpl; + } + + public getTemplate(name: string) { + return this._templates[name]; + } + + /** + * Does this library has the specified program? + */ + public hasProgram(name: string) { + return this._templates[name] !== undefined; + } + + public getKey(name: string, defines: DefineMap) { + const tmpl = this._templates[name]; + let key = 0; + for (const tmplDef of tmpl.defines) { + const value = defines[tmplDef.name]; + if (value === undefined || !tmplDef._map) { + continue; + } + key |= tmplDef._map(value); + } + return key << 8 | (tmpl.id & 0xff); + } + + public getGFXShader(name: string, defines: DefineMap = {}) { + const key = this.getKey(name, defines); + let program = this._cache[key]; + if (program !== undefined) { + return program; + } + + // get template + const tmpl = this._templates[name]; + const customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n'; + const vert = customDef + tmpl.vert; + const frag = customDef + tmpl.frag; + + program = this._device.createShader({ + name, + blocks: tmpl.blocks, + samplers: tmpl.samplers, + stages: [ + { type: GFXShaderType.VERTEX, source: vert }, + { type: GFXShaderType.FRAGMENT, source: frag }, + ], + }); + this._cache[key] = program; + return program; + } +} From 630e8f67a0924ca63256d8c1bc6126166c5ac7f7 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Sat, 5 Jan 2019 15:53:59 +0800 Subject: [PATCH 037/267] CCObject|RawAsset|Asset.ts --- cocos/3d/assets/animation-clip.js | 14 +- cocos/3d/assets/audio-clip.js | 4 +- cocos/3d/assets/effect-asset.ts | 2 +- cocos/3d/assets/font.js | 6 +- cocos/3d/assets/material.js | 2 +- cocos/3d/assets/mesh.js | 2 +- cocos/3d/assets/physics/material.ts | 2 +- cocos/3d/assets/skeleton.js | 4 +- cocos/3d/assets/sprite.js | 4 +- cocos/assets/CCAssetLibrary.js | 8 +- cocos/assets/CCFont.js | 2 +- cocos/assets/CCGLTFAsset.js | 6 +- cocos/assets/CCJsonAsset.js | 2 +- cocos/assets/CCPrefab.js | 4 +- cocos/assets/CCSceneAsset.js | 4 +- cocos/assets/CCScripts.js | 4 +- cocos/assets/CCSpriteAtlas.js | 6 +- cocos/assets/CCSpriteFrame.js | 4 +- cocos/assets/CCTextAsset.js | 4 +- cocos/assets/{CCAsset.js => asset.ts} | 187 +++++++------------ cocos/assets/index.js | 4 +- cocos/assets/{CCRawAsset.js => raw-asset.ts} | 47 ++--- cocos/assets/texture-base.js | 2 +- cocos/components/CCComponent.js | 2 +- cocos/core/data/index.js | 2 +- cocos/core/data/instantiate-jit.js | 2 +- cocos/core/data/instantiate.js | 2 +- cocos/core/data/{object.js => object.ts} | 157 +++++++--------- cocos/core/director.js | 6 +- cocos/scene-graph/base-node.js | 2 +- cocos/scene-graph/component-scheduler.js | 6 +- cocos/scene-graph/node-activator.js | 2 +- 32 files changed, 212 insertions(+), 293 deletions(-) rename cocos/assets/{CCAsset.js => asset.ts} (68%) rename cocos/assets/{CCRawAsset.js => raw-asset.ts} (65%) rename cocos/core/data/{object.js => object.ts} (83%) diff --git a/cocos/3d/assets/animation-clip.js b/cocos/3d/assets/animation-clip.js index 1050517473..432d15bbe2 100644 --- a/cocos/3d/assets/animation-clip.js +++ b/cocos/3d/assets/animation-clip.js @@ -26,12 +26,12 @@ // @ts-check import { _decorator } from "../../core/data/index"; const { ccclass, property } = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import vec3 from "../../core/vmath/vec3"; import quat from "../../core/vmath/quat"; import { clamp } from "../../core/vmath/utils"; -/** +/** * @typedef {import("../framework/skeleton-instance").SkeletonMask} SkeletonMask * @typedef {import("../../scene-graph/node").default} Node */ @@ -205,8 +205,8 @@ export class AnimationTarget { */ export class AnimationSampler { /** - * - * @param {AnimationTarget} animationTarget + * + * @param {AnimationTarget} animationTarget */ constructor(animationTarget) { /** @@ -246,7 +246,7 @@ export class AnimationSampler { /** Sample data of this animation clip in a specific time and blend that data * with a weight together with previous data(if exist, or blank if not exists) sampled before. - * + * * @param {AnimationClip} clip * @param {Number} t The time. * @param {Number} weight The weight. @@ -316,7 +316,7 @@ export class AnimationSampler { class NodeSamplingState { /** - * + * * @param {Node} target * @param {cc.Vec3} defaultPosition * @param {cc.Vec3} defaultScale @@ -395,4 +395,4 @@ class NodeSamplingState { if (this._sumRotWeight < 1.0) this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); } -} \ No newline at end of file +} diff --git a/cocos/3d/assets/audio-clip.js b/cocos/3d/assets/audio-clip.js index eb7684cd20..b2c73509b1 100644 --- a/cocos/3d/assets/audio-clip.js +++ b/cocos/3d/assets/audio-clip.js @@ -24,7 +24,7 @@ ****************************************************************************/ // @ts-check import { _decorator } from "../../core/data/index"; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import { EventTarget } from "../../core/event/index"; const { ccclass, mixins } = _decorator; @@ -117,4 +117,4 @@ export class AudioClip extends Asset { } } -cc.AudioClip = AudioClip; \ No newline at end of file +cc.AudioClip = AudioClip; diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 72f2bc82a7..bea5b0b984 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -1,4 +1,4 @@ -import Asset from '../../assets/CCAsset'; +import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { PassInfoBase } from '../../renderer/core/pass'; diff --git a/cocos/3d/assets/font.js b/cocos/3d/assets/font.js index 319bacfd94..292ee84ecd 100644 --- a/cocos/3d/assets/font.js +++ b/cocos/3d/assets/font.js @@ -25,7 +25,7 @@ // @ts-check import { _decorator } from "../../core/data/index"; const {ccclass} = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; @ccclass('cc.Font') export default class Font extends Asset { @@ -46,7 +46,7 @@ export default class Font extends Asset { _lineHeight = 32; /** - * + * * @type {boolean} */ _useKerning = false; @@ -78,4 +78,4 @@ export default class Font extends Asset { } } -cc.Font = Font; \ No newline at end of file +cc.Font = Font; diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js index 052604a415..8f6ab714dc 100644 --- a/cocos/3d/assets/material.js +++ b/cocos/3d/assets/material.js @@ -24,7 +24,7 @@ ****************************************************************************/ // @ts-check import { ccclass, property } from "../../core/data/class-decorator"; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import TextureBase from '../../assets/texture-base'; import Effect from '../../renderer/core/effect'; import { EffectAsset } from './effect-asset'; diff --git a/cocos/3d/assets/mesh.js b/cocos/3d/assets/mesh.js index 35a2de09dd..c57d65fb44 100644 --- a/cocos/3d/assets/mesh.js +++ b/cocos/3d/assets/mesh.js @@ -26,7 +26,7 @@ // @ts-check import { _decorator } from "../../core/data/index"; const { ccclass, property } = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import gfx from "../../renderer/gfx"; import { enums as gfxEnums } from "../../renderer/gfx/enums"; import InputAssembler from "../../renderer/core/input-assembler"; diff --git a/cocos/3d/assets/physics/material.ts b/cocos/3d/assets/physics/material.ts index b44256eab7..56f62d39ef 100644 --- a/cocos/3d/assets/physics/material.ts +++ b/cocos/3d/assets/physics/material.ts @@ -2,7 +2,7 @@ // @ts-check import CANNON from 'cannon'; -import Asset from '../../../assets/CCAsset'; +import { Asset } from '../../../assets/asset'; import { ccclass, property } from '../../../core/data/class-decorator'; @ccclass('cc.PhysicalMaterial') diff --git a/cocos/3d/assets/skeleton.js b/cocos/3d/assets/skeleton.js index 3efca75a9d..a7679f2906 100644 --- a/cocos/3d/assets/skeleton.js +++ b/cocos/3d/assets/skeleton.js @@ -26,7 +26,7 @@ // @ts-check import { _decorator } from "../../core/data"; const { ccclass, property } = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import { Mat4 } from "../../core/value-types"; /** @@ -78,4 +78,4 @@ export default class Skeleton extends Asset { return this._joints; } } -cc.Skeleton = Skeleton; \ No newline at end of file +cc.Skeleton = Skeleton; diff --git a/cocos/3d/assets/sprite.js b/cocos/3d/assets/sprite.js index 93c544ea7b..48144fa563 100644 --- a/cocos/3d/assets/sprite.js +++ b/cocos/3d/assets/sprite.js @@ -25,7 +25,7 @@ // @ts-check import { _decorator } from "../../core/data/index"; const { ccclass } = _decorator; -import Asset from "../../assets/CCAsset"; +import { Asset } from "../../assets/asset"; import { vec3, mat4 } from '../../core/vmath/index'; let _t_tmp = vec3.create(0, 0, 0); @@ -200,4 +200,4 @@ export default class Sprite extends Asset { } } -cc.Sprite = Sprite; \ No newline at end of file +cc.Sprite = Sprite; diff --git a/cocos/assets/CCAssetLibrary.js b/cocos/assets/CCAssetLibrary.js index bfdf1d27a2..fb6020b08a 100644 --- a/cocos/assets/CCAssetLibrary.js +++ b/cocos/assets/CCAssetLibrary.js @@ -25,7 +25,7 @@ ****************************************************************************/ import {createMap, isChildClassOf, _getClassById} from '../core/utils/js'; -import Asset from './CCAsset'; +import { Asset } from './asset'; import {callInNextTick} from '../core/utils/misc'; import decodeUuid from '../core/utils/decode-uuid'; import Loader from '../load-pipeline/CCLoader'; @@ -348,11 +348,11 @@ let AssetLibrary = { _uuidToRawAsset[uuid] = new RawAssetEntry(mountPoint + '/' + url, type); // init resources var isSubAsset = info[2] === 1; - + if (!assetTables[mountPoint]) { assetTables[mountPoint] = new AssetTable(); - } - + } + assetTables[mountPoint].add(url, uuid, type, !isSubAsset); } } diff --git a/cocos/assets/CCFont.js b/cocos/assets/CCFont.js index 3c0cb6e939..37dcfe23e6 100644 --- a/cocos/assets/CCFont.js +++ b/cocos/assets/CCFont.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass} from '../core/data/class-decorator'; /** diff --git a/cocos/assets/CCGLTFAsset.js b/cocos/assets/CCGLTFAsset.js index 4e8c114118..b44718a902 100644 --- a/cocos/assets/CCGLTFAsset.js +++ b/cocos/assets/CCGLTFAsset.js @@ -26,7 +26,7 @@ import { _decorator } from "../core/data/index"; const { ccclass, property } = _decorator; import BufferAsset from "./CCBufferAsset"; -import Asset from "./CCAsset"; +import { Asset } from "./asset"; /** * @typedef {import("../../../types/glTF/glTF").GlTf} GlTf @@ -37,7 +37,7 @@ import Asset from "./CCAsset"; * Class for GLTF file. * * !#zh - * GLTF 资源类。
+ * GLTF 资溝类。
* * @class GLTFAsset * @extends Asset @@ -80,4 +80,4 @@ export default class GLTFAsset extends Asset { } } -cc.GLTFAsset = GLTFAsset; \ No newline at end of file +cc.GLTFAsset = GLTFAsset; diff --git a/cocos/assets/CCJsonAsset.js b/cocos/assets/CCJsonAsset.js index 9ace3831ed..07185e57a9 100644 --- a/cocos/assets/CCJsonAsset.js +++ b/cocos/assets/CCJsonAsset.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** diff --git a/cocos/assets/CCPrefab.js b/cocos/assets/CCPrefab.js index 08083bfca1..c53d4c4b79 100644 --- a/cocos/assets/CCPrefab.js +++ b/cocos/assets/CCPrefab.js @@ -27,7 +27,7 @@ import {compile} from '../core/data/instantiate-jit'; import Enum from '../core/value-types/enum'; import {obsolete} from '../core/utils/js'; -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -203,4 +203,4 @@ export default class Prefab extends Asset { } cc.Prefab = Prefab; -obsolete(cc, 'cc._Prefab', 'Prefab'); \ No newline at end of file +obsolete(cc, 'cc._Prefab', 'Prefab'); diff --git a/cocos/assets/CCSceneAsset.js b/cocos/assets/CCSceneAsset.js index 1058ad9092..dd948ec349 100644 --- a/cocos/assets/CCSceneAsset.js +++ b/cocos/assets/CCSceneAsset.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -60,4 +60,4 @@ export default class SceneAsset extends Asset { //} } -cc.SceneAsset = SceneAsset; \ No newline at end of file +cc.SceneAsset = SceneAsset; diff --git a/cocos/assets/CCScripts.js b/cocos/assets/CCScripts.js index aca55d426f..2595134a2b 100644 --- a/cocos/assets/CCScripts.js +++ b/cocos/assets/CCScripts.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass} from '../core/data/class-decorator'; /** @@ -62,4 +62,4 @@ cc._JavaScript = JavaScript; @ccclass('cc.TypeScript') export class TypeScript extends Script { } -cc._TypeScript = TypeScript; \ No newline at end of file +cc._TypeScript = TypeScript; diff --git a/cocos/assets/CCSpriteAtlas.js b/cocos/assets/CCSpriteAtlas.js index 85667e295f..e8ed5d5220 100644 --- a/cocos/assets/CCSpriteAtlas.js +++ b/cocos/assets/CCSpriteAtlas.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -64,7 +64,7 @@ export default class SpriteAtlas extends Asset { let sf = this._spriteFrames[key]; if (!sf) { return null; - } + } if (!sf.name) { sf.name = key; } @@ -88,4 +88,4 @@ export default class SpriteAtlas extends Asset { } } -cc.SpriteAtlas = SpriteAtlas; \ No newline at end of file +cc.SpriteAtlas = SpriteAtlas; diff --git a/cocos/assets/CCSpriteFrame.js b/cocos/assets/CCSpriteFrame.js index 6d28070663..70012e0056 100644 --- a/cocos/assets/CCSpriteFrame.js +++ b/cocos/assets/CCSpriteFrame.js @@ -28,7 +28,7 @@ import EventTarget from '../core/event/event-target'; import textureUtil from './texture-util'; import {addon} from '../core/utils/js'; -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; @@ -712,4 +712,4 @@ proto.initWithTexture = proto.setTexture; addon(proto, EventTarget.prototype); -cc.SpriteFrame = SpriteFrame; \ No newline at end of file +cc.SpriteFrame = SpriteFrame; diff --git a/cocos/assets/CCTextAsset.js b/cocos/assets/CCTextAsset.js index 904afcdad4..5d99e80bcb 100644 --- a/cocos/assets/CCTextAsset.js +++ b/cocos/assets/CCTextAsset.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** @@ -54,4 +54,4 @@ export default class TextAsset extends Asset { } } -cc.TextAsset = TextAsset; \ No newline at end of file +cc.TextAsset = TextAsset; diff --git a/cocos/assets/CCAsset.js b/cocos/assets/asset.ts similarity index 68% rename from cocos/assets/CCAsset.js rename to cocos/assets/asset.ts index cc051ced5e..6a50379469 100644 --- a/cocos/assets/CCAsset.js +++ b/cocos/assets/asset.ts @@ -25,7 +25,7 @@ ****************************************************************************/ import { ccclass, property } from '../core/data/class-decorator'; -import RawAsset from './CCRawAsset'; +import { RawAsset } from './raw-asset'; /** * !#en @@ -44,73 +44,92 @@ import RawAsset from './CCRawAsset'; * - _nativeAsset 的 getset 方法
* - cc.Object._serialize
* - cc.Object._deserialize
- * - * @class Asset - * @extends RawAsset */ @ccclass('cc.Asset') -export default class Asset extends RawAsset { - constructor () { - super(); - /** - * !#en - * Whether the asset is loaded or not - * !#zh - * 该资源是否已经成功加载 - * - * @property loaded - * @type {Boolean} - */ - this.loaded = true; +export class Asset extends RawAsset { + /** + * !#en Indicates whether its dependent raw assets can support deferred load + * if the owner scene (or prefab) is marked as `asyncLoadAssets`. + * !#zh 当场景或 Prefab 被标记为 `asyncLoadAssets`,禁止延迟加载该资源所依赖的其它 RawAsset。 + * + * @property {Boolean} preventDeferredLoadDependents + * @default false + * @static + */ + public static preventDeferredLoadDependents = false; + + /** + * !#en Indicates whether its native object should be preloaded from native url. + * !#zh 禁止预加载原生对象。 + * + * @property {Boolean} preventPreloadNativeObject + * @default false + * @static + */ + public static preventPreloadNativeObject = false; + + /** + * 应 AssetDB 要求提供这个方法 + */ + protected static deserialize(data: string): Asset { + return cc.deserialize(data); } + /** + * !#en + * Create a new node using this asset in the scene.
+ * If this type of asset dont have its corresponding node type, this method should be null. + * !#zh + * 使用该资源在场景中创建一个新节点。
+ * 如果这类资源没有相应的节点类型,该方法应该是空的。 + * + * @param {Function} callback + * @param {String} callback.error - null or the error info + * @param {Object} callback.node - the created node or null + */ + public createNode: null | ((callback: (err: string, node: object) => void) => void) = null; + + protected loaded = true; + + /** + * Serializable url for native asset. + */ + @property + protected _native = ''; + /** * !#en * Returns the url of this asset's native object, if none it will returns an empty string. * !#zh * 返回该资源对应的目标平台资源的 URL,如果没有将返回一个空字符串。 - * @property nativeUrl - * @type {String} - * @readOnly */ @property({ - visible: false + visible: false, }) - get nativeUrl () { + get nativeUrl(): Readonly { if (this._native) { - var name = this._native; + const name = this._native; if (name.charCodeAt(0) === 47) { // '/' // remove library tag // not imported in library, just created on-the-fly return name.slice(1); } if (cc.AssetLibrary) { - var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); + const base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); if (name.charCodeAt(0) === 46) { // '.' // imported in dir where json exist return base + name; - } - else { + } else { // imported in an independent dir return base + '/' + name; } - } - else { + } else { cc.errorID(6400); } } return ''; } - /** - * Serializable url for native asset. - * @property {String} _native - * @default "" - * @private - */ - @property - _native = "" - /** * The underlying native asset of this asset if one is available. * This property can be used to access additional details or functionality releated to the asset. @@ -121,104 +140,42 @@ export default class Asset extends RawAsset { * @type {any} */ @property - get _nativeAsset () { - } - set _nativeAsset (obj) { - } - - /** - * 应 AssetDB 要求提供这个方法 - * - * @method deserialize - * @param {String} data - * @return {Asset} - * @static - * @private - */ - static deserialize (data) { - return cc.deserialize(data); - } - - /** - * !#en Indicates whether its dependent raw assets can support deferred load if the owner scene (or prefab) is marked as `asyncLoadAssets`. - * !#zh 当场景或 Prefab 被标记为 `asyncLoadAssets`,禁止延迟加载该资源所依赖的其它 RawAsset。 - * - * @property {Boolean} preventDeferredLoadDependents - * @default false - * @static - */ - static preventDeferredLoadDependents = false; - - /** - * !#en Indicates whether its native object should be preloaded from native url. - * !#zh 禁止预加载原生对象。 - * - * @property {Boolean} preventPreloadNativeObject - * @default false - * @static - */ - static preventPreloadNativeObject = false; + get _nativeAsset() { return null; } + set _nativeAsset(obj) {} /** * Returns the string representation of the object. * * The `Asset` object overrides the `toString()` method of the `Object` object. - * JavaScript calls the toString() method automatically when an asset is to be represented as a text value or when a texture is referred to in a string concatenation. + * JavaScript calls the toString() method automatically when an asset is to be represented + * as a text value or when a texture is referred to in a string concatenation. * * For assets of the native type, it will return `this.nativeUrl`. * Otherwise, an empty string is returned. * This method may be overwritten by subclasses. - * - * @method toString - * @return {String} */ - toString () { + public toString(): string { return this.nativeUrl; } - /** - * 应 AssetDB 要求提供这个方法 - * - * @method serialize - * @return {String} - * @private - */ - serialize () { - return Editor.serialize(this); - } - /** * Set native file name for this asset. * @seealso nativeUrl - * - * @method _setRawAsset - * @param {String} filename - * @param {Boolean} [inLibrary=true] - * @private */ - _setRawAsset (filename, inLibrary) { + protected _setRawAsset(filename: string, inLibrary: boolean = true) { if (inLibrary !== false) { - this._native = filename || undefined; - } - else { + this._native = filename; + } else { this._native = '/' + filename; // simply use '/' to tag location where is not in the library } } + + /** + * 应 AssetDB 要求提供这个方法 + */ + protected serialize(): string { + return Editor.serialize(this); + } } -/** - * !#en - * Create a new node using this asset in the scene.
- * If this type of asset dont have its corresponding node type, this method should be null. - * !#zh - * 使用该资源在场景中创建一个新节点。
- * 如果这类资源没有相应的节点类型,该方法应该是空的。 - * - * @method createNode - * @param {Function} callback - * @param {String} callback.error - null or the error info - * @param {Object} callback.node - the created node or null - */ -Asset.prototype.createNode = null; - -cc.Asset = Asset; \ No newline at end of file +cc.Asset = Asset; diff --git a/cocos/assets/index.js b/cocos/assets/index.js index b39587bccc..1124f26705 100644 --- a/cocos/assets/index.js +++ b/cocos/assets/index.js @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -export {default as RawAsset} from './CCRawAsset'; -export {default as Asset} from './CCAsset'; +export { RawAsset } from './raw-asset'; +export { Asset } from './asset'; export {default as Prefab} from './CCPrefab'; export * from './CCScripts'; export {default as SceneAsset} from './CCSceneAsset'; diff --git a/cocos/assets/CCRawAsset.js b/cocos/assets/raw-asset.ts similarity index 65% rename from cocos/assets/CCRawAsset.js rename to cocos/assets/raw-asset.ts index d433c0c493..9b4c2ff473 100644 --- a/cocos/assets/CCRawAsset.js +++ b/cocos/assets/raw-asset.ts @@ -24,45 +24,34 @@ THE SOFTWARE. ****************************************************************************/ -import {isChildClassOf} from '../core/utils/js'; -import CCObject from '../core/data/object'; -import {ccclass} from '../core/data/class-decorator'; +import { ccclass } from '../core/data/class-decorator'; +import { CCObject } from '../core/data/object'; +import { isChildClassOf } from '../core/utils/js'; + +function enumerable(value: boolean) { + return (target: any, propertyKey: string) => { + const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) || {}; + if (descriptor.enumerable !== value) { + descriptor.enumerable = value; + Object.defineProperty(target, propertyKey, descriptor); + } + }; +} /** * !#en * The base class for registering asset types. * !#zh * 注册用的资源基类。 - * - * @class RawAsset - * @extends Object */ @ccclass('cc.RawAsset') -export default class RawAsset extends CCObject { - constructor () { - super(); - /** - * @property _uuid - * @type {String} - * @private - */ - Object.defineProperty(this, '_uuid', { - value: '', - writable: true, - // enumerable is false by default, to avoid uuid being assigned to empty string during destroy - }); +export class RawAsset extends CCObject { + protected static isRawAssetType(ctor: Function): boolean { + return isChildClassOf(ctor, RawAsset) && !isChildClassOf(ctor, cc.Asset); } - /** - * @method isRawAssetType - * @param {Function} ctor - * @returns {Boolean} - * @static - * @private - */ - static isRawAssetType (ctor) { - return isChildClassOf(ctor, cc.RawAsset) && !isChildClassOf(ctor, cc.Asset); - } + @enumerable(false) + protected _uuid = ''; } cc.RawAsset = RawAsset; diff --git a/cocos/assets/texture-base.js b/cocos/assets/texture-base.js index 28fc526f3e..3a9a578b40 100644 --- a/cocos/assets/texture-base.js +++ b/cocos/assets/texture-base.js @@ -29,7 +29,7 @@ import IDGenerator from '../core/utils/id-generator'; import Enum from '../core/value-types/enum'; import {addon} from '../core/utils/js'; import {enums} from '../renderer/gfx/enums'; -import Asset from './CCAsset'; +import { Asset } from './asset'; import {ccclass, property} from '../core/data/class-decorator'; /** diff --git a/cocos/components/CCComponent.js b/cocos/components/CCComponent.js index c90dcfda7f..247597ee19 100644 --- a/cocos/components/CCComponent.js +++ b/cocos/components/CCComponent.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import {getClassName, value} from '../core/utils/js'; import IDGenerator from '../core/utils/id-generator'; import {ccclass, property} from '../core/data/class-decorator'; diff --git a/cocos/core/data/index.js b/cocos/core/data/index.js index 25869cc301..8ae9b09a7b 100644 --- a/cocos/core/data/index.js +++ b/cocos/core/data/index.js @@ -27,6 +27,6 @@ import * as _decorator from './class-decorator'; cc._decorator = _decorator; export { _decorator }; export { default as CCClass } from './class'; -export { default as CCObject } from './object'; +export { CCObject } from './object'; export { default as deserialize } from './deserialize'; export { default as instantiate } from './instantiate'; diff --git a/cocos/core/data/instantiate-jit.js b/cocos/core/data/instantiate-jit.js index 4b1b0435f3..5a92e17733 100644 --- a/cocos/core/data/instantiate-jit.js +++ b/cocos/core/data/instantiate-jit.js @@ -28,7 +28,7 @@ import * as js from '../utils/js'; import CCClass from './class'; -import CCObject from './object'; +import { CCObject } from './object'; import * as Attr from './utils/attribute'; import {flattenCodeArray} from './utils/compiler'; diff --git a/cocos/core/data/instantiate.js b/cocos/core/data/instantiate.js index 2a978447f0..77d1bbde6a 100644 --- a/cocos/core/data/instantiate.js +++ b/cocos/core/data/instantiate.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import CCObject from './object'; +import { CCObject } from './object'; import ValueType from '../value-types/value-type'; import {isDomNode} from '../utils/misc'; diff --git a/cocos/core/data/object.js b/cocos/core/data/object.ts similarity index 83% rename from cocos/core/data/object.js rename to cocos/core/data/object.ts index 77811fee5b..440bbf2c05 100644 --- a/cocos/core/data/object.js +++ b/cocos/core/data/object.ts @@ -38,8 +38,8 @@ const DontDestroy = 1 << 6; const Destroying = 1 << 7; const Deactivating = 1 << 8; const LockedInEditor = 1 << 9; -//var HideInGame = 1 << 9; -var HideInHierarchy = 1 << 10; +// const HideInGame = 1 << 9; +const HideInHierarchy = 1 << 10; const IsOnEnableCalled = 1 << 11; const IsEditorOnEnableCalled = 1 << 12; @@ -54,7 +54,7 @@ const IsAnchorLocked = 1 << 19; const IsSizeLocked = 1 << 20; const IsPositionLocked = 1 << 21; -//var Hide = HideInGame | HideInEditor; +// const Hide = HideInGame | HideInEditor; // should not clone or serialize these flags const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | @@ -62,37 +62,34 @@ const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactiva IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked /*RegisteredInEditor*/); -var objectsToDestroy = []; -var deferredDestroyTimer = null; +const objectsToDestroy: CCObject[] = []; +let deferredDestroyTimer = null; -function compileDestruct (obj, ctor) { - var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; - var idToSkip = shouldSkipId ? '_id' : null; +function compileDestruct(obj: object, ctor) { + const shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; + const idToSkip = shouldSkipId ? '_id' : null; - var key, propsToReset = {}; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - if (key === idToSkip) { - continue; - } - switch (typeof obj[key]) { - case 'string': - propsToReset[key] = ''; - break; - case 'object': - case 'function': - propsToReset[key] = null; - break; - } + const propsToReset = {}; + for (const key of Object.keys(obj)) { + if (key === idToSkip) { + continue; + } + switch (typeof obj[key]) { + case 'string': + propsToReset[key] = ''; + break; + case 'object': + case 'function': + propsToReset[key] = null; + break; } } // Overwrite propsToReset according to Class if (CCClass._isCCClass(ctor)) { - var attrs = cc.Class.Attr.getClassAttrs(ctor); - var propList = ctor.__props__; - for (var i = 0; i < propList.length; i++) { - key = propList[i]; - var attrKey = key + cc.Class.Attr.DELIMETER + 'default'; + const attrs = cc.Class.Attr.getClassAttrs(ctor); + const propList = ctor.__props__; + for (const key of propList) { + const attrKey = key + cc.Class.Attr.DELIMETER + 'default'; if (attrKey in attrs) { if (shouldSkipId && key === '_id') { continue; @@ -115,26 +112,24 @@ function compileDestruct (obj, ctor) { if (CC_SUPPORT_JIT) { // compile code - var func = ''; - for (key in propsToReset) { - var statement; + let func = ''; + for (const key of Object.keys(propsToReset)) { + let statement: string; if (CCClass.IDENTIFIER_RE.test(key)) { statement = 'o.' + key + '='; - } - else { + } else { statement = 'o[' + CCClass.escapeForJS(key) + ']='; } - var val = propsToReset[key]; + let val = propsToReset[key]; if (val === '') { val = '""'; } func += (statement + val + ';\n'); } return Function('o', func); - } - else { - return function (o) { - for (var key in propsToReset) { + } else { + return (o: object) => { + for (const key of Object.keys(propsToReset)) { o[key] = propsToReset[key]; } }; @@ -149,26 +144,10 @@ function compileDestruct (obj, ctor) { * @private */ class CCObject { - constructor (name = '') { - /** - * @property {String} _name - * @default "" - * @private - */ - this._name = name; - - /** - * @property {Number} _objFlags - * @default 0 - * @private - */ - this._objFlags = 0; - } - - static _deferredDestroy () { - var deleteCount = objectsToDestroy.length; - for (var i = 0; i < deleteCount; ++i) { - var obj = objectsToDestroy[i]; + protected static _deferredDestroy() { + const deleteCount = objectsToDestroy.length; + for (let i = 0; i < deleteCount; ++i) { + const obj = objectsToDestroy[i]; if (!(obj._objFlags & Destroyed)) { obj._destroyImmediate(); } @@ -177,8 +156,7 @@ class CCObject { // but we only destroy the objects which called destory in this frame. if (deleteCount === objectsToDestroy.length) { objectsToDestroy.length = 0; - } - else { + } else { objectsToDestroy.splice(0, deleteCount); } @@ -187,20 +165,23 @@ class CCObject { } } + protected _name = ''; + protected _objFlags = 0; + + constructor(name = '') { + this._name = name; + } + // MEMBER /** * !#en The name of the object. * !#zh 该对象的名称。 - * @property {String} name - * @default "" - * @example - * obj.name = "New Obj"; */ - get name () { + get name() { return this._name; } - set name (value) { + set name(value) { this._name = value; } @@ -214,20 +195,19 @@ class CCObject { * * !#zh * 表示该对象是否可用(被 destroy 后将不可用)。
- * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 + * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。因此从下一帧开始 `isValid` 就会返回 false + * 而当前帧内 `isValid` 仍然会是 true。如果希望判断当前帧是否调用过 `destroy` + * 请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 * - * @property {Boolean} isValid - * @default true - * @readOnly * @example - * var node = new cc.Node(); + * const node = new cc.Node(); * cc.log(node.isValid); // true * node.destroy(); * cc.log(node.isValid); // true, still valid in this frame * // after a frame... * cc.log(node.isValid); // false, destroyed in the end of last frame */ - get isValid () { + get isValid(): Readonly { return !(this._objFlags & Destroyed); } @@ -241,12 +221,8 @@ class CCObject { * 销毁该对象,并释放所有它对其它对象的引用。
* 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。 * 您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} whether it is the first time the destroy being called - * @example - * obj.destroy(); */ - destroy () { + public destroy() { if (this._objFlags & Destroyed) { cc.warnID(5000); return false; @@ -270,7 +246,7 @@ class CCObject { * NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. * You can override the _destruct method if you need, for example: * _destruct: function () { - * for (var key in this) { + * for (const key in this) { * if (this.hasOwnProperty(key)) { * switch (typeof this[key]) { * case 'string': @@ -284,12 +260,10 @@ class CCObject { * } * } * - * @method _destruct - * @private */ - _destruct () { - var ctor = this.constructor; - var destruct = ctor.__destruct__; + protected _destruct() { + const ctor = this.constructor; + let destruct = ctor.__destruct__; if (!destruct) { destruct = compileDestruct(this, ctor); js.value(ctor, '__destruct__', destruct, true); @@ -297,7 +271,7 @@ class CCObject { destruct(this); } - _destroyImmediate () { + protected _destroyImmediate() { if (this._objFlags & Destroyed) { cc.errorID(5000); return; @@ -315,7 +289,7 @@ class CCObject { } } -let prototype = CCObject.prototype; +const prototype = CCObject.prototype; if (CC_EDITOR || CC_TEST) { js.get(prototype, 'isRealValid', function () { return !(this._objFlags & RealDestroyed); @@ -509,31 +483,30 @@ js.value(CCObject, 'Flags', { * @param {Boolean} [strictMode=false] - If true, Object called destroy() in this frame will also treated as invalid. * @return {Boolean} whether is valid * @example - * var node = new cc.Node(); + * const node = new cc.Node(); * cc.log(cc.isValid(node)); // true * node.destroy(); * cc.log(cc.isValid(node)); // true, still valid in this frame * // after a frame... * cc.log(cc.isValid(node)); // false, destroyed in the end of last frame */ -cc.isValid = function (value, strictMode) { +cc.isValid = (value, strictMode) => { if (typeof value === 'object') { return !!value && !(value._objFlags & (strictMode ? (Destroyed | ToDestroy) : Destroyed)); - } - else { + } else { return typeof value !== 'undefined'; } }; if (CC_EDITOR || CC_TEST) { - js.value(CCObject, '_willDestroy', function (obj) { + js.value(CCObject, '_willDestroy', (obj) => { return !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0; }); - js.value(CCObject, '_cancelDestroy', function (obj) { + js.value(CCObject, '_cancelDestroy', (obj) => { obj._objFlags &= ~ToDestroy; js.array.fastRemove(objectsToDestroy, obj); }); } cc.Object = CCObject; -export default CCObject; +export { CCObject }; diff --git a/cocos/core/director.js b/cocos/core/director.js index bddb5b76e0..5350f0b60a 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -27,7 +27,7 @@ import EventTarget from './event/event-target'; import eventManager from './platform/event-manager/CCEventManager'; -import ccobject from './data/object'; +import { CCObject } from './data/object'; import game from './game'; import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; @@ -440,7 +440,7 @@ class Director extends EventTarget { this._scene = null; // purge destroyed nodes belongs to old scene - ccobject._deferredDestroy(); + CCObject._deferredDestroy(); CC_BUILD && CC_DEBUG && console.timeEnd('Destroy'); if (onBeforeLoadScene) { @@ -916,7 +916,7 @@ class Director extends EventTarget { // User can use this event to do things after update this.emit(cc.Director.EVENT_AFTER_UPDATE); // Destroy entities that have been removed recently - ccobject._deferredDestroy(); + CCObject._deferredDestroy(); } // Render diff --git a/cocos/scene-graph/base-node.js b/cocos/scene-graph/base-node.js index ba4dfd45b2..457c9d7871 100644 --- a/cocos/scene-graph/base-node.js +++ b/cocos/scene-graph/base-node.js @@ -26,7 +26,7 @@ import * as js from '../core/utils/js'; import IdGenerator from '../core/utils/id-generator'; -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import { ccclass, property } from '../core/data/class-decorator'; const Destroying = CCObject.Flags.Destroying; diff --git a/cocos/scene-graph/component-scheduler.js b/cocos/scene-graph/component-scheduler.js index 121d83b9df..925649e49c 100644 --- a/cocos/scene-graph/component-scheduler.js +++ b/cocos/scene-graph/component-scheduler.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import { MutableForwardIterator } from '../core/utils/array'; import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; @@ -193,7 +193,7 @@ class ReusableInvoker extends LifeCycleInvoker { } } } - + invoke (dt) { if (this._neg.array.length > 0) { this._invoke(this._neg, dt); @@ -479,4 +479,4 @@ if (CC_EDITOR) { }; } -export default ComponentScheduler; \ No newline at end of file +export default ComponentScheduler; diff --git a/cocos/scene-graph/node-activator.js b/cocos/scene-graph/node-activator.js index 907826095f..aa6443538b 100644 --- a/cocos/scene-graph/node-activator.js +++ b/cocos/scene-graph/node-activator.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ComponentScheduler from './component-scheduler'; -import CCObject from '../core/data/object'; +import { CCObject } from '../core/data/object'; import { Pool, array } from '../core/utils/js'; import { tryCatchFunctor_EDITOR } from '../core/utils/misc'; From 132ca6e05b93264e6374c75ab9e4ff586351cf33 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 7 Jan 2019 10:49:20 +0800 Subject: [PATCH 038/267] [API BREAKING] material with passes --- cocos/3d/assets/effect-asset.ts | 4 +- cocos/3d/assets/index.js | 28 +- cocos/3d/assets/material.js | 147 ----------- cocos/3d/assets/material.ts | 155 +++++++++++ cocos/3d/builtin/effects.js | 86 +++--- cocos/3d/builtin/init.js | 4 +- .../renderer/particle-system-gpu-renderer.js | 2 +- .../renderer/particle-system-renderer.js | 2 +- cocos/3d/framework/renderable-component.js | 2 +- cocos/3d/framework/skybox-component.js | 2 +- cocos/pipeline/forward/forward-flow.ts | 7 +- cocos/pipeline/forward/test-material-stage.ts | 138 ++++++++++ cocos/renderer/core/effect.ts | 244 +++++------------- cocos/renderer/core/pass.ts | 157 ++++++++--- cocos/renderer/core/program-lib.ts | 8 +- cocos/renderer/core/technique.ts | 37 --- cocos/renderer/index.js | 4 +- playground/simple.html | 2 +- 18 files changed, 570 insertions(+), 459 deletions(-) delete mode 100644 cocos/3d/assets/material.js create mode 100644 cocos/3d/assets/material.ts create mode 100644 cocos/pipeline/forward/test-material-stage.ts delete mode 100644 cocos/renderer/core/technique.ts diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index bea5b0b984..e0993474ba 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -20,13 +20,14 @@ export interface BlockMember { name: string; type: number; count: number; + size: number; } export interface BlockInfo { name: string; binding: number; defines: string[]; - size: number; members: BlockMember[]; + size: number; } export interface SamplerInfo { name: string; @@ -72,6 +73,7 @@ export class EffectAsset extends Asset { return effects[n]; } } + return null; } public static getAll() { return effects; } protected static _effects: Record = {}; diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js index f44eda0443..b29eef7751 100644 --- a/cocos/3d/assets/index.js +++ b/cocos/3d/assets/index.js @@ -4,7 +4,7 @@ http://www.cocos.com Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, + of this software and associated engine source code (the 'Software'), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license to use Cocos Creator solely to develop games on your target platforms. You shall not use Cocos Creator software for developing other software or tools that's @@ -14,7 +14,7 @@ The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER @@ -23,17 +23,17 @@ THE SOFTWARE. ****************************************************************************/ -import "./animation-clip"; -import "./audio-clip"; -import "./dom-audio-clip"; -import "./bitmap-font"; -import "./material"; -import "./mesh"; -import "./opentype-font"; -import "./skeleton"; -import "./sprite"; -import "./web-audio-clip"; -import "./wx-game-audio-clip"; +import './animation-clip'; +import './audio-clip'; +import './dom-audio-clip'; +import './bitmap-font'; +import './material'; +import './mesh'; +import './opentype-font'; +import './skeleton'; +import './sprite'; +import './web-audio-clip'; +import './wx-game-audio-clip'; import { PhysicsMaterial } from './physics/material'; -cc.PhysicsMaterial = PhysicsMaterial; \ No newline at end of file +cc.PhysicsMaterial = PhysicsMaterial; diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js deleted file mode 100644 index 8f6ab714dc..0000000000 --- a/cocos/3d/assets/material.js +++ /dev/null @@ -1,147 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { ccclass, property } from "../../core/data/class-decorator"; -import { Asset } from "../../assets/asset"; -import TextureBase from '../../assets/texture-base'; -import Effect from '../../renderer/core/effect'; -import { EffectAsset } from './effect-asset'; - -@ccclass('cc.Material') -class Material extends Asset { - /** - * @type {Object} - */ - @property - _defines = {}; - - /** - * @type {Object} - */ - @property - _props = {}; - - /** - * @type {EffectAsset} - */ - @property(EffectAsset) - _effectAsset = null; - - @property - set effectAsset(val) { - if (this.effectName !== val.name) this._setEffect(val); - } - get effectAsset() { - return this._effectAsset; - } - - // helper setter - @property - set effectName(val) { - if (this.effectName !== val) this._setEffect(val); - } - get effectName() { - return this._effectAsset ? this._effectAsset.name : ''; - } - - /** - * @type {Effect} - */ - _effect = null; - - /** - * @type {Effect} - */ - get effect() { - return this._effect; - } - - /** - * - * @param {Material} mat - */ - copy(mat) { - Object.assign(this._props, mat._props); - Object.assign(this._defines, mat._defines); - this._setEffect(mat.effectAsset); - this._uuid = mat._uuid; - } - - /** - * - * @param {string} name - * @param {*} val - */ - setProperty(name, val) { - this._props[name] = val; - if (this._effect) { - if (val instanceof TextureBase) this._effect.setProperty(name, val._texture); - else this._effect.setProperty(name, val); - } - } - - /** - * - * @param {string} name - * @param {*} val - */ - define(name, val) { - this._defines[name] = val; - if (this._effect) this._effect.define(name, val); - } - - onLoaded() { - this._setEffect(this.effectAsset); - } - - _setEffect(val) { - let effectAsset = val; - if (typeof val === 'string' && !(effectAsset = cc.EffectAsset.get(val))) { - console.warn(`no effect named '${val}' found`); - return; - } - this._effectAsset = effectAsset; - if (!effectAsset) return; - this._effect = Effect.parseEffect(effectAsset, this._defines); - for (let prop in this._props) - this.setProperty(prop, this._props[prop]); - } - - static getInstantiatedMaterial(mat, rndCom) { - if (mat._owner === rndCom) { - return mat; - } - else { - let instance = new Material(); - instance.copy(mat); - instance._native = mat._native + ' (Instance)'; - instance._owner = rndCom; - return instance; - } - } -} - -export default Material; -cc.Material = Material; diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts new file mode 100644 index 0000000000..0b14306c92 --- /dev/null +++ b/cocos/3d/assets/material.ts @@ -0,0 +1,155 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { Asset } from '../../assets/asset'; +import TextureBase from '../../assets/texture-base'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { Effect } from '../../renderer/core/effect'; +import { Pass } from '../../renderer/core/pass'; +import { EffectAsset } from './effect-asset'; + +@ccclass('cc.Material') +export class Material extends Asset { + public static getInstantiatedMaterial(mat: Material, rndCom: any) { + if (mat._owner === rndCom) { + return mat; + } else { + const instance = new Material(); + instance.copy(mat); + instance._native = mat._native + ' (Instance)'; + instance._owner = rndCom; + return instance; + } + } + + @property(EffectAsset) + protected _effectAsset: EffectAsset | null = null; + @property + protected _techIdx = 0; + @property + protected _defines: Record = {}; + @property + protected _props: Array> = []; + + protected _passes: Pass[] = []; + protected _owner: any = null; + + @property + set effectAsset(val: EffectAsset | null) { + if (!val || this.effectName !== val.name) { this.update(val, false); } + } + get effectAsset() { + return this._effectAsset; + } + // helper setter + @property + set effectName(val) { + if (this.effectName !== val) { this.update(val, false); } + } + get effectName() { + return this._effectAsset ? this._effectAsset.name : ''; + } + + @property + set technique(val: number) { + this._techIdx = val; + } + get technique() { + return this._techIdx; + } + + get passes() { + return this._passes; + } + + public setDefines(defines: Record) { + this._defines = defines; + this.update(); + } + + public setProperty(handle: number, val: any, passIdx = 0) { + if (this._props.length <= passIdx) { + console.warn('illegal pass index'); + return; + } + this._props[passIdx][name] = val; + const pass = this._passes[passIdx]; + if (pass) { + if (val instanceof TextureBase) { + pass.setProperty(handle, val._texture); + } else { + pass.setProperty(handle, val); + } + } + } + + public copy(mat: Material) { + this._props.length = mat._props.length; + for (let i = 0; i < mat._props.length; i++) { + Object.assign(this._props[i], mat._props[i]); + } + Object.assign(this._defines, mat._defines); + this.update(mat.effectAsset); + this._uuid = mat._uuid; + } + + public onLoaded() { + this.update(); + } + + public update(val: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { + // get effect asset + if (typeof val === 'string') { + this._effectAsset = EffectAsset.get(val); + if (!this._effectAsset) { + console.warn(`no effect named '${val}' found`); + return; + } + } else { + this._effectAsset = val; + } + if (!this._effectAsset) { return; } + // create passes + this._passes = Effect.parseEffect(this._effectAsset, { + techIdx: this._techIdx, + defines: this._defines, + }); + // handle property values + this._props.length = this._passes.length; + if (keepProps) { + this._passes.forEach((pass, i) => { + let props = this._props[i]; + if (!props) { props = this._props[i] = {}; } + for (const p of Object.keys(props)) { + const handle = pass.getPropertyHandle(p); + pass.setProperty(handle, props[p]); + } + }); + } else { + this._props.fill({}); + } + } +} + +cc.Material = Material; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index d2d9f94048..0feefdfbec 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,4 +1,57 @@ export default [ + { + "name": "test", + "techniques": [{"queue": 0, "lod": 500, "passes": [{"stage": 100, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}], "priority": 0}], + "properties": {"u_color": {"type": 17, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": null}}, + "shaders": [ + { + "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", + "vert": "\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n varying vec2 v_texCoord;\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n", + "frag": "\n varying vec2 v_texCoord;\n uniform vec4 u_color;\n uniform sampler2D u_sampler;\n void main() {\n \n gl_FragColor = texture2D(u_sampler, v_texCoord);\n gl_FragColor.r = u_color.r;\n }\n", + "defines": [], + "blocks": [ + {"name": "Constants", "size": 16, "defines": [], "binding": 0, "members": [ + {"name": "u_color", "type": 16, "count": 1, "size": 16} + ]} + ], + "samplers": [ + {"name": "u_sampler", "type": 29, "count": 1, "defines": [], "binding": 1} + ], + "dependencies": {} + } + ] + }, + { + "name": "builtin-effect-unlit", + "techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}], "priority": 0}], + "properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": null}}, + "shaders": [ + { + "name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c", + "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_texCoord1;\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;\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_texCoord1 * 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": []}, + {"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]}, + {"name": "USE_COLOR", "type": "boolean", "defines": []} + ], + "blocks": [ + {"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "size": 16, "members": [ + {"name": "mainTiling", "type": 14, "count": 1}, + {"name": "mainOffset", "type": 14, "count": 1} + ]}, + {"name": "Constant", "defines": ["USE_COLOR"], "binding": 1, "size": 16, "members": [ + {"name": "color", "type": 16, "count": 1} + ]} + ], + "samplers": [ + {"name": "mainTexture", "type": 29, "count": 1, "defines": ["USE_TEXTURE"], "binding": 2} + ], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-skybox", "techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d"}], "priority": -1000}], @@ -36,36 +89,5 @@ export default [ "dependencies": {} } ] - }, - { - "name": "builtin-effect-unlit", - "techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}], "priority": 0}], - "properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": null}}, - "shaders": [ - { - "name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c", - "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_texCoord1;\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;\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_texCoord1 * 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": []}, - {"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]}, - {"name": "USE_COLOR", "type": "boolean", "defines": []} - ], - "blocks": [ - {"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "size": 16, "members": [ - {"name": "mainTiling", "type": 14, "count": 1}, - {"name": "mainOffset", "type": 14, "count": 1} - ]}, - {"name": "Constant", "defines": ["USE_COLOR"], "binding": 1, "size": 16, "members": [ - {"name": "color", "type": 16, "count": 1} - ]} - ], - "samplers": [ - {"name": "mainTexture", "type": 29, "count": 1, "defines": ["USE_TEXTURE"], "binding": 2} - ], - "dependencies": {} - } - ] - }, + } ]; diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index bf263c1e9f..409f143d2f 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -1,7 +1,7 @@ import Texture2D from '../../assets/texture-2d'; import TextureCube from '../assets/texture-cube'; import ImageAsset from '../../assets/image-asset'; -import Material from '../assets/material'; +import { Material } from '../assets/material'; import { EffectAsset } from '../assets/effect-asset'; import effects from './effects'; @@ -80,8 +80,8 @@ let builtinResMgr = { // default material // let defaultMtl = new Material(); // defaultMtl._uuid = 'default-material'; + // defaultMtl._defines['USE_COLOR'] = true; // defaultMtl.effectAsset = efxs[0]; - // defaultMtl.define('USE_COLOR', true); // defaultMtl.setProperty('color', cc.color('#FF00FF')); let builtins = { diff --git a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js index ad4cbe5525..e67a3cebea 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js +++ b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js @@ -1,5 +1,5 @@ import ParticleSystemRenderer from "./particle-system-renderer"; -import Material from "../../../assets/material"; +import { Material } from "../../../assets/material"; import Particle from "../particle"; import gfx from "../../../../renderer/gfx"; import { CurveUniform } from "../animator/optimized-curve"; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-renderer.js index c3bb5694fb..ee5c80f7cd 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.js +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.js @@ -1,7 +1,7 @@ import renderer from '../../../../renderer'; import { vec3, vec4, vec2, mat4 } from '../../../../core/vmath'; import gfx from '../../../../renderer/gfx'; -import Material from '../../../assets/material'; +import { Material } from '../../../assets/material'; import { RecyclePool } from '../../../memop'; import Particle from '../particle'; import RenderableComponent from '../../renderable-component'; diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.js index 149371d076..ac57a08e2d 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.js @@ -1,6 +1,6 @@ //@ts-check import { _decorator } from '../../core/data/index'; -import Material from "../assets/material"; +import { Material } from "../assets/material"; import Component from "../../components/CCComponent"; const { ccclass, property } = _decorator; diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js index 5c340b1ecf..f8201add98 100644 --- a/cocos/3d/framework/skybox-component.js +++ b/cocos/3d/framework/skybox-component.js @@ -25,7 +25,7 @@ // @ts-check import renderer from '../../renderer/index'; import { box } from '../primitive/index'; -import Material from '../assets/material'; +import { Material } from '../assets/material'; import { ccclass, property, menu, executeInEditMode } from '../../core/data/class-decorator'; import TextureCube from '../assets/texture-cube'; import Component from '../../components/CCComponent'; diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 21bbecf346..67509a697b 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,6 +1,7 @@ import { RenderFlow, RenderFlowInfo } from "../render-flow"; import { RenderPipeline } from "../render-pipeline"; -import { TestStage } from "./test-stage"; +// import { TestStage } from "./test-stage"; +import { TestMaterialStage } from "./test-material-stage"; export enum ForwardStagePriority { FORWARD = 0, @@ -33,8 +34,8 @@ export class ForwardFlow extends RenderFlow { }); */ - this.createStage(TestStage, { - name: "TestStage", + this.createStage(TestMaterialStage, { + name: "TestMaterialStage", priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts new file mode 100644 index 0000000000..bece72a16a --- /dev/null +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -0,0 +1,138 @@ +import { Material } from '../../3d/assets/material'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXBufferTextureCopy, GFXCommandBufferType, GFXFormat, + GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; +import { GFXFramebuffer } from '../../gfx/framebuffer'; +import { GFXInputAssembler } from '../../gfx/input-assembler'; +import { GFXTexture } from '../../gfx/texture'; +import { GFXTextureView } from '../../gfx/texture-view'; +import { RenderFlow } from '../render-flow'; +import { RenderStage, RenderStageInfo } from '../render-stage'; +import { RenderView } from '../render-view'; + +export class TestMaterialStage extends RenderStage { + + private _texture: GFXTexture | null = null; + private _texView: GFXTextureView | null = null; + private _material: Material = new Material(); + + constructor(flow: RenderFlow) { + super(flow); + } + + public initialize(info: RenderStageInfo): 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])) { + 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._material.inited) { + // material + this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js + const handle1 = this._material.passes[0].getPropertyHandle('u_sampler'); + this._material.setProperty(handle1, this._texView); + const handle2 = this._material.passes[0].getPropertyHandle('u_color'); + this._material.setProperty(handle2, cc.color('#ffffff')); + this._material.inited = true; + } + const cmdBuff = this._cmdBuff; + this._renderArea.width = view.width; + this._renderArea.height = view.height; + + cmdBuff.begin(); + cmdBuff.beginRenderPass(this._framebuffer, 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); + cmdBuff.draw(this._pipeline.quadIA); + cmdBuff.endRenderPass(); + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + } + + private loadTexture(image: HTMLImageElement): boolean { + 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]); + + return true; + } +} diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 330f1e8a11..b5780c163f 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -1,14 +1,13 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { EffectAsset, PropertyInfo, ShaderInfo } from '../../3d/assets/effect-asset'; +import { BlockMember, EffectAsset, PropertyInfo, SamplerInfo, ShaderInfo } from '../../3d/assets/effect-asset'; import { CCObject } from '../../core/data'; import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; import { GFXType } from '../../gfx/define'; +import { RenderPassStage } from '../../pipeline/render-pipeline'; import Texture2D from '../gfx/texture-2d'; import TextureCube from '../gfx/texture-cube'; -import { PassStage } from './constants'; import { Pass, PassInfo } from './pass'; -import Technique from './technique'; const _typeMap = { [GFXType.INT]: 'Number', @@ -28,144 +27,12 @@ const _typeMap = { default: CCObject, }; const getInstanceType = (t: number | string) => _typeMap[t] || _typeMap.default; -const typeCheck = (value: any, type: number) => { - const instanceType = getInstanceType(type); - switch (typeof value) { - case 'object': return (value === null) || (value instanceof instanceType); - case 'number': return instanceType === 'Number'; - case 'boolean': return instanceType === 'Boolean'; - default: return false; - } -}; -const createPass = () => { - -}; - -let _globalTechLod = 600; - -type PropValue = number | boolean | Vec2 | Vec3 | Vec4 | Color | Mat4 | Texture2D | TextureCube | null; -interface PropertyMap { [name: string]: { type: number, value: PropValue }; } -interface DefineMap { [name: string]: number | boolean; } - -class Effect { - public static parseEffect(effect: EffectAsset, defines: DefineMap) { return new Effect(); } - public static parseForInspector(effect: EffectAsset) { return { props: {}, defines: {} }; } - public static setGlobalLod(lod: number) { _globalTechLod = lod; } - - protected _name: string = ''; - protected _techniques: Technique[] = []; - protected _properties: PropertyMap = {}; - protected _defines: DefineMap = {}; - protected _dependencies: Record = {}; - - protected _maxLOD: number = 0; - protected _activeTechIdx: number = 0; - protected _programs: Record = {}; - - constructor( - name: string = '', - techniques: Technique[] = [new Technique()], - programs: Record = {}, - properties: PropertyMap = {}, - lod = -1 - ) { - this._name = name; - this._techniques = techniques; - this._properties = properties; - this._programs = programs; - this._defines = {}; - this._dependencies = {}; - this._maxLOD = lod; - this.selectTechnique(); - } - - set LOD(lod: number) { - if (lod === this._maxLOD) { - return; - } - this._maxLOD = lod; - this.selectTechnique(); - } - - public clear() { - this._techniques.length = 0; - this._properties = {}; - this._defines = {}; - this._dependencies = {}; - } - - public getTechnique(index: number) { - if (index < 0 || index >= this._techniques.length) { return null; } - return this._techniques[index]; - } - - public getProperty(name: string) { - if (!this._properties[name]) { - console.warn(`Failed to get property ${name}, property not found.`); - return null; - } - return this._properties[name].value; - } - - public setProperty(name: string, value: any) { - const prop = this._properties[name]; - if (!prop) { - console.warn(`Failed to set property ${name}, property not found.`); - return; - } else if (!typeCheck(value, prop.type)) { - console.warn(`Failed to set property ${name}, property type mismatch.`); - return; - } - this._properties[name].value = value; - } - - public getDefine(name: string) { - const def = this._defines[name]; - if (def !== undefined) { return def; } - console.warn(`Failed to get define ${name}, define not found.`); - return null; - } - - public define(name: string, value: number | boolean) { - if (this._defines[name] !== undefined) { - this._defines[name] = value; - } else { - console.warn(`Failed to set define ${name}, define not found.`); - } - } - - public extractDefines(out = {}) { - return Object.assign(out, this._defines); - } - - public extractDependencies(out = {}) { - return Object.assign(out, this._dependencies); - } - - public getActiveTechnique() { - return this._techniques[this._activeTechIdx]; - } - - public selectTechnique() { - const lod = this._maxLOD === -1 ? _globalTechLod : this._maxLOD; - this._activeTechIdx = 0; - for (let i = 0; i < this._techniques.length; i++) { - if (this._techniques[i].LOD <= lod) { - this._activeTechIdx = i; - break; - } - } - // defines - this._defines = {}; - this._techniques[this._activeTechIdx].passes.forEach((pass) => - this._programs[pass.programName].defines.forEach((def) => - this._defines[def.name] = def.type === 'number' ? 0 : false)); - // extensions - this._dependencies = {}; - this._techniques[this._activeTechIdx].passes.forEach((pass) => - Object.assign(this._dependencies, this._programs[pass.programName].dependencies)); - } +export interface PropertyMap { [name: string]: { type: number, value: any }; } +export interface DefineMap { [name: string]: number | boolean; } +export interface EffectInfo { + techIdx?: number; + defines?: DefineMap; } type DefaultValue = number | boolean | number[] | null; @@ -189,14 +56,20 @@ const _ctorMap = { }; const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; -const getInvolvedPrograms = (effect: EffectAsset) => { +const getInvolvedPrograms = (effect: EffectAsset, techIdx?: number) => { const programs: Record = {}; const lib = cc.game._programLib; - effect.techniques.forEach((tech) => { - tech.passes.forEach((pass) => { + if (techIdx) { + effect.techniques[techIdx].passes.forEach((pass) => { programs[pass.program] = lib.getTemplate(pass.program); }); - }); + } else { + effect.techniques.forEach((tech) => { + tech.passes.forEach((pass) => { + programs[pass.program] = lib.getTemplate(pass.program); + }); + }); + } return programs; }; @@ -206,13 +79,16 @@ interface ExtractedPropInfo { value: number | boolean | object; defines: string[]; displayName?: string; + tech: number; + pass: number; } const parseProperties = (() => { interface UniformInfo { type: number; defines: string[]; } - function genPropInfo(propInfo: PropertyInfo, uniformInfo: UniformInfo): ExtractedPropInfo { + function genPropInfo(propInfo: PropertyInfo, uniformInfo: UniformInfo, tech: number, pass: number) + : ExtractedPropInfo { const type = propInfo.type || uniformInfo.type; return { - type, + type, tech, pass, instanceType: getInstanceType(type), value: getInstanceCtor(type)(propInfo.value), displayName: propInfo.displayName, @@ -226,19 +102,32 @@ const parseProperties = (() => { } return program.samplers.find((u) => u.name === name); } + function findPassIdx(effect: EffectAsset, programName: string) { // just a heuristic + effect.techniques.forEach((tech, i) => { + tech.passes.forEach((pass, j) => { + if (pass.program === programName) { + return [ i, j ]; + } + }); + }); + return [ 0, 0 ]; + } return (effect: EffectAsset, programs: Record) => { const props: Record = {}; for (const prop of Object.keys(effect.properties)) { const propInfo = effect.properties[prop]; let uniformInfo: UniformInfo | undefined; + let techIdx = 0; + let passIdx = 0; // always try getting the type from shaders first if (propInfo.tech !== undefined && propInfo.pass !== undefined) { const p = effect.techniques[propInfo.tech].passes[propInfo.pass].program; uniformInfo = findUniformInfo(programs[p], prop); + techIdx = propInfo.tech; passIdx = propInfo.pass; } else { for (const p of Object.keys(programs)) { uniformInfo = findUniformInfo(programs[p], prop); - if (uniformInfo) { break; } + if (uniformInfo) { [techIdx, passIdx] = findPassIdx(effect, p); break; } } } // the property is not defined in all the shaders used in techs @@ -246,59 +135,53 @@ const parseProperties = (() => { console.warn(`illegal property: ${prop}`); continue; } - // TODO: different param with same name for different passes - props[prop] = genPropInfo(propInfo, uniformInfo); + props[prop] = genPropInfo(propInfo, uniformInfo, techIdx, passIdx); } return props; }; })(); -Effect.parseEffect = (effect: EffectAsset, defines: DefineMap) => { - // techniques - const techNum = effect.techniques.length; - const techniques = new Array(techNum); - const programs = getInvolvedPrograms(effect); - for (let j = 0; j < techNum; ++j) { - const tech = effect.techniques[j]; +const traverseUniforms = (shaderInfo: ShaderInfo, fn: (u: BlockMember | SamplerInfo) => any) => { + shaderInfo.blocks.forEach((b) => b.members.forEach(fn)); + shaderInfo.samplers.forEach(fn); +}; + +export class Effect { + public static parseEffect(effect: EffectAsset, info?: EffectInfo) { + // techniques + const { techIdx, defines } = info || {}; + const programs = getInvolvedPrograms(effect, techIdx || 0); + const tech = effect.techniques[techIdx || 0]; const passNum = tech.passes.length; const passes: Pass[] = new Array(passNum); + const props = parseProperties(effect, programs); for (let k = 0; k < passNum; ++k) { const passInfo = tech.passes[k]; - passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines); - passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || PassStage.DEFAULT); + const uniforms: PropertyMap = passInfo.uniforms = {}; + traverseUniforms(programs[passInfo.program], (u) => { + const prop = props[u.name]; + uniforms[u.name] = { + type: prop ? prop.type : u.type, + value: prop ? prop.value : getInstanceCtor(u.type)(), + }; + }); + passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines || {}); + passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.FORWARD); passInfo.blocks = programs[passInfo.program].blocks; passInfo.samplers = programs[passInfo.program].samplers; const pass = new Pass(cc.game._gfxDevice); pass.initialize(passInfo); passes[k] = pass; } - techniques[j] = new Technique(tech.queue, tech.priority, tech.lod, passes); + return passes; } - // uniforms - const props = parseProperties(effect, programs); - const uniforms = {}; - for (const pn of Object.keys(programs)) { - programs[pn].blocks.forEach((b) => b.members.forEach((u) => { - const prop = props[u.name]; - uniforms[u.name] = { - type: prop ? prop.type : u.type, - value: prop ? prop.value : getInstanceCtor(u.type)(), - }; - })); - } - - return new Effect(effect.name, techniques, programs, uniforms); -}; - -if (CC_EDITOR) { - Effect.parseForInspector = (effect: EffectAsset) => { + public static parseForInspector(effect: EffectAsset) { const programs = getInvolvedPrograms(effect); const props = parseProperties(effect, programs); - const defines: Record = {}; + const defines: Record = {}; for (const pn of Object.keys(programs)) { programs[pn].defines.forEach((define) => { defines[define.name] = { - type: (define.type === 'number' ? GFXType.INT : GFXType.BOOL), instanceType: getInstanceType(define.type), value: getInstanceCtor(define.type)(), defines: define.defines, @@ -306,8 +189,7 @@ if (CC_EDITOR) { }); } return { props, defines }; - }; + } } -export default Effect; cc.Effect = Effect; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 9217afd21d..602d16a917 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,9 +1,10 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { BlockInfo, SamplerInfo } from '../../3d/assets/effect-asset'; +import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; -import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; +import { GFXBindingType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, @@ -11,13 +12,14 @@ import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; -import { PassStage } from './constants'; +import { RenderPassStage } from '../../pipeline/render-pipeline'; +import { PropertyMap } from './effect'; export interface PassInfoBase { program: string; // effect-writer part primitive?: GFXPrimitiveMode; - stage?: PassStage; + stage?: RenderPassStage; rasterizerState?: GFXRasterizerState; depthStencilState?: GFXDepthStencilState; blendState?: GFXBlendState; @@ -28,28 +30,61 @@ export interface PassInfo extends PassInfoBase { samplers: SamplerInfo[]; shader: GFXShader; renderPass: GFXRenderPass; + uniforms: PropertyMap; +} + +const _type2fn = { + [GFXType.INT]: (a: Float32Array, v: any) => a[0] = v, + [GFXType.INT2]: (a: Float32Array, v: any) => vec2.array(a, v), + [GFXType.INT3]: (a: Float32Array, v: any) => vec3.array(a, v), + [GFXType.INT4]: (a: Float32Array, v: any) => vec4.array(a, v), + [GFXType.FLOAT]: (a: Float32Array, v: any) => a[0] = v, + [GFXType.FLOAT2]: (a: Float32Array, v: any) => vec2.array(a, v), + [GFXType.FLOAT3]: (a: Float32Array, v: any) => vec3.array(a, v), + [GFXType.FLOAT4]: (a: Float32Array, v: any) => vec4.array(a, v), + [GFXType.COLOR4]: (a: Float32Array, v: any) => color4.array(a, v), + [GFXType.MAT2]: (a: Float32Array, v: any) => mat2.array(a, v), + [GFXType.MAT3]: (a: Float32Array, v: any) => mat3.array(a, v), + [GFXType.MAT4]: (a: Float32Array, v: any) => mat4.array(a, v), +}; + +const bindingMask = 0x0fff0000; +const indexMask = 0x0000ffff; +const genHandle = (binding: number, index: number = 0) => (binding << 16) | index; +const parseHandle = (handle: number) => [(handle & bindingMask) >> 16, handle & indexMask]; + +interface Block { + buffer: ArrayBuffer; + views: Float32Array[]; } export class Pass { - protected _device: GFXDevice; - protected _programName: string = ''; - protected _stage: PassStage = PassStage.DEFAULT; + // internal resources protected _pipelineState: GFXPipelineState | null = null; protected _pipelineLayout: GFXPipelineLayout | null = null; protected _bindingLayout: GFXBindingLayout | null = null; protected _buffers: GFXBuffer[] = []; protected _samplers: GFXSampler[] = []; + // internal data + protected _programName: string = ''; + protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + protected _stage: RenderPassStage = RenderPassStage.FORWARD; + protected _handleMap: Record = {}; + protected _typeMap: Record = {}; + protected _blocks: Block[] = []; + // external references + protected _device: GFXDevice; + protected _shader: GFXShader | null = null; + protected _renderPass: GFXRenderPass | null = null; public constructor(device: GFXDevice) { this._device = device; } public initialize(info: PassInfo) { - const device = this._device; this._programName = info.program; - this._stage = info.stage || PassStage.DEFAULT; - // pipeline state + const device = this._device; const bindings = info.blocks.map((u) => ({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER }) ).concat(info.samplers.map((u) => @@ -59,27 +94,12 @@ export class Pass { 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; } - const bs = new GFXBlendState(); - if (info.blendState) { - const bsInfo = Object.assign({}, info.blendState); - if (bsInfo.targets) { - bsInfo.targets.forEach((t, i) => Object.assign( - bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); - } - delete bsInfo.targets; - Object.assign(bs, bsInfo); - } - this._pipelineState = device.createPipelineState({ - primitive: info.primitive || GFXPrimitiveMode.TRIANGLE_LIST, - rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), - dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState), - is: new GFXInputState(), bs, - shader: info.shader, - layout: this._pipelineLayout, - renderPass: info.renderPass, - }); + this._shader = info.shader; + this._renderPass = info.renderPass; + this.createPipelineState(info); for (const u of info.blocks) { + // create gfx buffer resource const buffer = device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, @@ -88,12 +108,32 @@ export class Pass { }); if (buffer) { this._bindingLayout.bindBuffer(u.binding, buffer); - this._buffers.push(buffer); + this._buffers[u.binding] = buffer; } else { console.error('create buffer failed.'); + return; } + // buffer data processing system + const block: Block = this._blocks[u.binding] = { + buffer: new ArrayBuffer(u.size), + views: [], + }; + u.members.reduce((acc, cur, idx) => { + // create property-specific buffer views + const view = new Float32Array(block.buffer, acc, cur.size / Float32Array.BYTES_PER_ELEMENT); + block.views.push(view); + // store handle map, type and initial value + const handle = this._handleMap[cur.name] = genHandle(u.binding, idx); + const inf = info.uniforms[cur.name]; + this._typeMap[handle] = inf.type; + _type2fn[inf.type](view, inf.value); + // proceed the counter + return acc + cur.size; + }, 0); // === u.size + buffer.update(block.buffer); } for (const u of info.samplers) { + this._handleMap[u.name] = genHandle(u.binding); const sampler = device.createSampler({ name: u.name, // TODO: specify filter modes in effect @@ -107,6 +147,28 @@ export class Pass { } } + public getPropertyHandle(name: string) { + return this._handleMap[name]; + } + + public setProperty(handle: number, value: any) { + const [ binding, idx ] = parseHandle(handle); + const block = this._blocks[binding]; + if (block) { + const type = this._typeMap[handle]; + _type2fn[type](block.views[idx], value); + this._buffers[binding].update(block.buffer); + } else if (this._bindingLayout) { + this._bindingLayout.bindTextureView(binding, value); + this._bindingLayout.update(); + } + } + + public setStates(info: PassInfoBase) { + if (this._pipelineState) { this._pipelineState.destroy(); } + this.createPipelineState(info); + } + 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; } @@ -115,6 +177,41 @@ export class Pass { if (this._pipelineState) { this._pipelineState.destroy(); this._pipelineState = null; } } + protected createPipelineState(info: PassInfoBase) { + if (info.primitive) { this._primitive = info.primitive; } + if (info.stage) { 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(); + if (info.blendState) { + const bsInfo = Object.assign({}, info.blendState); + if (bsInfo.targets) { + bsInfo.targets.forEach((t, i) => Object.assign( + bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t)); + } + delete bsInfo.targets; + Object.assign(bs, bsInfo); + } + const stateInfo = { + primitive: info.primitive || this._primitive, + rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), + dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState), + is: new GFXInputState(), bs, + shader: this._shader, + layout: this._pipelineLayout, + renderPass: this._renderPass, + }; + if (this._pipelineState) { + this._pipelineState.initialize(stateInfo); + } else { + this._pipelineState = this._device.createPipelineState(stateInfo); + } + } + get programName() { return this._programName; } - get pipelineState() { return this._pipelineState; } + get pipelineState() { return this._pipelineState; } + get bindingLayout() { return this._bindingLayout; } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 999f851ca9..f8641466c7 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -4,8 +4,8 @@ import { DefineInfo, ShaderInfo } from '../../3d/assets/effect-asset'; import { GFXShaderType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXShader } from '../../gfx/shader'; +import { DefineMap } from './effect'; -interface DefineMap { [name: string]: number | boolean; } function _generateDefines( device: GFXDevice, defs: DefineMap, @@ -66,7 +66,7 @@ export class ProgramLib { */ public define(prog: ShaderInfo) { if (this._templates[prog.name]) { return; } - const tmpl: any = Object.assign({ id: ++_shdID }, prog); + const tmpl = Object.assign({ id: ++_shdID }, prog); tmpl.vert = this._precision + prog.vert; tmpl.frag = this._precision + prog.frag; @@ -77,7 +77,7 @@ export class ProgramLib { if (def.type === 'number') { const range = def.range || [0, 4]; cnt = Math.ceil(Math.log2(range[1] - range[0])); - def._map = ((value: number) => (value - def.range[0]) << def._offset); + def._map = ((value: number) => (value - range[0]) << def._offset); } else { // boolean def._map = ((value: any) => (value ? (1 << def._offset) : 0)); } @@ -85,7 +85,7 @@ export class ProgramLib { def._offset = offset; } // store it - this._templates[name] = tmpl; + this._templates[prog.name] = tmpl; } public getTemplate(name: string) { diff --git a/cocos/renderer/core/technique.ts b/cocos/renderer/core/technique.ts deleted file mode 100644 index e119e4b0a9..0000000000 --- a/cocos/renderer/core/technique.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { RenderQueue } from './constants'; -import { Pass } from './pass'; - -let _genID = 0; - -export default class Technique { - protected _id: number = -1; - protected _renderQueue: number = RenderQueue.OPAQUE; - protected _priority: number = 0; - protected _lod: number = -1; - protected _passes: Pass[] = []; - - constructor(renderQueue = RenderQueue.OPAQUE, priority = 0, lod = -1, passes: Pass[] = []) { - this._id = _genID++; - this._renderQueue = renderQueue; - this._priority = priority; - this._lod = lod; - this._passes = passes; - } - - public setRenderQueue(renderQueue: number) { - this._renderQueue = renderQueue; - } - - get LOD() { - return this._lod; - } - - get renderQueue() { - return this._renderQueue; - } - - get passes() { - return this._passes; - } -} diff --git a/cocos/renderer/index.js b/cocos/renderer/index.js index cd824b1e0d..6d45201abb 100644 --- a/cocos/renderer/index.js +++ b/cocos/renderer/index.js @@ -4,8 +4,7 @@ import config from './config'; import { RenderQueue, PassStage } from './core/constants'; import { Pass } from './core/pass'; -import Technique from './core/technique'; -import Effect from './core/effect'; +import { Effect } from './core/effect'; import InputAssembler from './core/input-assembler'; import View from './core/view'; @@ -32,7 +31,6 @@ let renderer = { RenderQueue, PassStage, Pass, - Technique, Effect, InputAssembler, View, diff --git a/playground/simple.html b/playground/simple.html index df8fad253b..d0261aaed7 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -33,7 +33,7 @@ function onStart() { const $body = document.body; const bcr = $body.getBoundingClientRect(); - cc.view.setCanvasSize(bcr.width, bcr.height); + // cc.view.setCanvasSize(bcr.width, bcr.height); window.addEventListener('resize', () => { const bcr = $body.getBoundingClientRect(); cc.view.setCanvasSize(bcr.width, bcr.height); From 8454474bd89aa673084d6d6b9686caf2748782b6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 7 Jan 2019 19:50:09 +0800 Subject: [PATCH 039/267] test code --- playground/simple.html | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/playground/simple.html b/playground/simple.html index a31187dcd1..a9d746cfa2 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -47,9 +47,12 @@ width: mainWindow.width, height: mainWindow.height, }); - view.attach(scene.mainCamera); + let camera = scene.mainCamera; + //camera.position = vec3(0.0, 0.0, 5.0); + + //todo initialization /* let scene = new cc.Scene(); From 29576e8935a727e89f58272d547a885eae6a9502 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 7 Jan 2019 22:30:32 +0800 Subject: [PATCH 040/267] material.setProperty --- cocos/3d/assets/material.ts | 41 +++++++++++++------ cocos/pipeline/forward/test-material-stage.ts | 9 ++-- cocos/renderer/core/pass.ts | 18 ++++---- 3 files changed, 44 insertions(+), 24 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 0b14306c92..e401a4f50f 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -51,6 +51,8 @@ export class Material extends Asset { protected _defines: Record = {}; @property protected _props: Array> = []; + @property + protected _textures: Array> = []; protected _passes: Pass[] = []; protected _owner: any = null; @@ -88,26 +90,33 @@ export class Material extends Asset { this.update(); } - public setProperty(handle: number, val: any, passIdx = 0) { - if (this._props.length <= passIdx) { - console.warn('illegal pass index'); + public setProperty(name: string, val: any, passIdx = 0) { + if (passIdx >= this._passes.length) { + console.warn('illegal pass index.'); return; } this._props[passIdx][name] = val; const pass = this._passes[passIdx]; - if (pass) { - if (val instanceof TextureBase) { - pass.setProperty(handle, val._texture); - } else { - pass.setProperty(handle, val); - } + const handle = pass.getHandleFromName(name); + pass.setBlockMember(handle, val); + } + + public setTexture(name: string, val: TextureBase, passIdx = 0) { + if (passIdx >= this._passes.length) { + console.warn('illegal pass index.'); + return; } + this._textures[passIdx][name] = val; + const pass = this._passes[passIdx]; + const handle = pass.getHandleFromName(name); + pass.setTextureView(handle, val._texView); } public copy(mat: Material) { - this._props.length = mat._props.length; + this._props.length = this._textures.length = mat._props.length; for (let i = 0; i < mat._props.length; i++) { Object.assign(this._props[i], mat._props[i]); + Object.assign(this._textures[i], mat._textures[i]); } Object.assign(this._defines, mat._defines); this.update(mat.effectAsset); @@ -136,14 +145,20 @@ export class Material extends Asset { defines: this._defines, }); // handle property values - this._props.length = this._passes.length; + this._props.length = this._textures.length = this._passes.length; if (keepProps) { this._passes.forEach((pass, i) => { let props = this._props[i]; if (!props) { props = this._props[i] = {}; } for (const p of Object.keys(props)) { - const handle = pass.getPropertyHandle(p); - pass.setProperty(handle, props[p]); + const handle = pass.getHandleFromName(p); + pass.setBlockMember(handle, props[p]); + } + let textures = this._textures[i]; + if (!textures) { textures = this._textures[i] = {}; } + for (const t of Object.keys(textures)) { + const handle = pass.getHandleFromName(t); + pass.setTextureView(handle, textures[t]._texView); } }); } else { diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index bece72a16a..a3a645be25 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -73,10 +73,11 @@ export class TestMaterialStage extends RenderStage { if (!this._material.inited) { // material this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js - const handle1 = this._material.passes[0].getPropertyHandle('u_sampler'); - this._material.setProperty(handle1, this._texView); - const handle2 = this._material.passes[0].getPropertyHandle('u_color'); - this._material.setProperty(handle2, cc.color('#ffffff')); + const pass = this._material.passes[0]; + const handle1 = pass.getHandleFromName('u_sampler'); + pass.setTextureView(handle1, this._texView); + const handle2 = pass.getHandleFromName('u_color'); + pass.setBlockMember(handle2, cc.color('#ffffff')); this._material.inited = true; } const cmdBuff = this._cmdBuff; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 602d16a917..2642e1d224 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -145,20 +145,24 @@ export class Pass { console.error('create sampler failed.'); } } + this._bindingLayout.update(); } - public getPropertyHandle(name: string) { + public getHandleFromName(name: string) { return this._handleMap[name]; } - public setProperty(handle: number, value: any) { + public setBlockMember(handle: number, value: any) { const [ binding, idx ] = parseHandle(handle); const block = this._blocks[binding]; - if (block) { - const type = this._typeMap[handle]; - _type2fn[type](block.views[idx], value); - this._buffers[binding].update(block.buffer); - } else if (this._bindingLayout) { + const type = this._typeMap[handle]; + _type2fn[type](block.views[idx], value); + this._buffers[binding].update(block.buffer); + } + + public setTextureView(handle: number, value: any) { + const [ binding ] = parseHandle(handle); + if (this._bindingLayout) { this._bindingLayout.bindTextureView(binding, value); this._bindingLayout.update(); } From 633780c96883202470e7f84d9ce62290b4ba714f Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 10:22:43 +0800 Subject: [PATCH 041/267] add getBindingUnit() to BindingLayout --- cocos/gfx/binding-layout.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index e3c5e19d26..b2b6e37724 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -75,6 +75,10 @@ export abstract class GFXBindingLayout { } } + public getBindingUnit(binding: number): GFXBindingUnit { + return this._bindingUnits[binding]; + } + protected _device: GFXDevice; protected _bindingUnits: GFXBindingUnit[] = []; }; From abb02c2ef07b231455d74795e739f686a47db60d Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 10:24:13 +0800 Subject: [PATCH 042/267] API fitting --- cocos/3d/assets/material.ts | 14 +++------ cocos/pipeline/forward/test-material-stage.ts | 6 ++-- cocos/renderer/core/pass.ts | 30 +++++++++++++++---- 3 files changed, 32 insertions(+), 18 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index e401a4f50f..2e7aca848c 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -91,21 +91,15 @@ export class Material extends Asset { } public setProperty(name: string, val: any, passIdx = 0) { - if (passIdx >= this._passes.length) { - console.warn('illegal pass index.'); - return; - } + console.assert(passIdx < this._passes.length, 'illegal pass index.'); this._props[passIdx][name] = val; const pass = this._passes[passIdx]; const handle = pass.getHandleFromName(name); - pass.setBlockMember(handle, val); + pass.setUniformMember(handle, val); } public setTexture(name: string, val: TextureBase, passIdx = 0) { - if (passIdx >= this._passes.length) { - console.warn('illegal pass index.'); - return; - } + console.assert(passIdx < this._passes.length, 'illegal pass index.'); this._textures[passIdx][name] = val; const pass = this._passes[passIdx]; const handle = pass.getHandleFromName(name); @@ -152,7 +146,7 @@ export class Material extends Asset { if (!props) { props = this._props[i] = {}; } for (const p of Object.keys(props)) { const handle = pass.getHandleFromName(p); - pass.setBlockMember(handle, props[p]); + pass.setUniformMember(handle, props[p]); } let textures = this._textures[i]; if (!textures) { textures = this._textures[i] = {}; } diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index a3a645be25..28c8bb5975 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -75,11 +75,13 @@ export class TestMaterialStage extends RenderStage { this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js const pass = this._material.passes[0]; const handle1 = pass.getHandleFromName('u_sampler'); - pass.setTextureView(handle1, this._texView); + pass.setTextureView(handle1, this._texView); const handle2 = pass.getHandleFromName('u_color'); - pass.setBlockMember(handle2, cc.color('#ffffff')); + pass.setUniformMember(handle2, cc.color('#ffffff')); + pass.update(); this._material.inited = true; } + const cmdBuff = this._cmdBuff; this._renderArea.width = view.width; this._renderArea.height = view.height; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 2642e1d224..9b4c797e05 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -12,6 +12,7 @@ import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; +import { GFXTextureView } from '../../gfx/texture-view'; import { RenderPassStage } from '../../pipeline/render-pipeline'; import { PropertyMap } from './effect'; @@ -56,6 +57,7 @@ const parseHandle = (handle: number) => [(handle & bindingMask) >> 16, handle & interface Block { buffer: ArrayBuffer; views: Float32Array[]; + dirty: boolean; } export class Pass { @@ -72,6 +74,7 @@ export class Pass { protected _handleMap: Record = {}; protected _typeMap: Record = {}; protected _blocks: Block[] = []; + protected _layoutDirty: boolean = false; // external references protected _device: GFXDevice; protected _shader: GFXShader | null = null; @@ -117,6 +120,7 @@ export class Pass { const block: Block = this._blocks[u.binding] = { buffer: new ArrayBuffer(u.size), views: [], + dirty: false, }; u.members.reduce((acc, cur, idx) => { // create property-specific buffer views @@ -152,19 +156,20 @@ export class Pass { return this._handleMap[name]; } - public setBlockMember(handle: number, value: any) { + public setUniformMember(handle: number, value: any) { const [ binding, idx ] = parseHandle(handle); const block = this._blocks[binding]; const type = this._typeMap[handle]; _type2fn[type](block.views[idx], value); - this._buffers[binding].update(block.buffer); + block.dirty = true; } - public setTextureView(handle: number, value: any) { + public setTextureView(handle: number, value: GFXTextureView) { const [ binding ] = parseHandle(handle); - if (this._bindingLayout) { - this._bindingLayout.bindTextureView(binding, value); - this._bindingLayout.update(); + const bl = this._bindingLayout; + if (bl && bl.getBindingUnit(binding).texView !== value) { + bl.bindTextureView(binding, value); + this._layoutDirty = true; } } @@ -181,6 +186,19 @@ export class Pass { if (this._pipelineState) { this._pipelineState.destroy(); this._pipelineState = null; } } + public update() { + const len = this._blocks.length; + for (let i = 0; i < len; i++) { + const block = this._blocks[i]; + if (block.dirty) { + this._buffers[i].update(block.buffer); + } + } + if (this._bindingLayout && this._layoutDirty) { + this._bindingLayout.update(); + } + } + protected createPipelineState(info: PassInfoBase) { if (info.primitive) { this._primitive = info.primitive; } if (info.stage) { this._stage = info.stage; } From 3e9fb16273620534ab90dd96c7e4ce49ec2b3b04 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 13:45:46 +0800 Subject: [PATCH 043/267] don't use TS for base classes yet declaration file suffices for now. --- cocos/assets/asset.d.ts | 30 ++++ cocos/assets/{asset.ts => asset.js} | 181 ++++++++++++-------- cocos/assets/raw-asset.d.ts | 31 ++++ cocos/assets/{raw-asset.ts => raw-asset.js} | 43 +++-- cocos/core/data/object.d.ts | 29 ++++ cocos/core/data/{object.ts => object.js} | 155 ++++++++++------- 6 files changed, 320 insertions(+), 149 deletions(-) create mode 100644 cocos/assets/asset.d.ts rename cocos/assets/{asset.ts => asset.js} (69%) create mode 100644 cocos/assets/raw-asset.d.ts rename cocos/assets/{raw-asset.ts => raw-asset.js} (73%) create mode 100644 cocos/core/data/object.d.ts rename cocos/core/data/{object.ts => object.js} (83%) diff --git a/cocos/assets/asset.d.ts b/cocos/assets/asset.d.ts new file mode 100644 index 0000000000..07c9afee5c --- /dev/null +++ b/cocos/assets/asset.d.ts @@ -0,0 +1,30 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { RawAsset } from "./raw-asset"; + +export class Asset extends RawAsset { + +} diff --git a/cocos/assets/asset.ts b/cocos/assets/asset.js similarity index 69% rename from cocos/assets/asset.ts rename to cocos/assets/asset.js index 6a50379469..050dcdfabc 100644 --- a/cocos/assets/asset.ts +++ b/cocos/assets/asset.js @@ -44,92 +44,73 @@ import { RawAsset } from './raw-asset'; * - _nativeAsset 的 getset 方法
* - cc.Object._serialize
* - cc.Object._deserialize
+ * + * @class Asset + * @extends RawAsset */ @ccclass('cc.Asset') export class Asset extends RawAsset { - /** - * !#en Indicates whether its dependent raw assets can support deferred load - * if the owner scene (or prefab) is marked as `asyncLoadAssets`. - * !#zh 当场景或 Prefab 被标记为 `asyncLoadAssets`,禁止延迟加载该资源所依赖的其它 RawAsset。 - * - * @property {Boolean} preventDeferredLoadDependents - * @default false - * @static - */ - public static preventDeferredLoadDependents = false; - - /** - * !#en Indicates whether its native object should be preloaded from native url. - * !#zh 禁止预加载原生对象。 - * - * @property {Boolean} preventPreloadNativeObject - * @default false - * @static - */ - public static preventPreloadNativeObject = false; - - /** - * 应 AssetDB 要求提供这个方法 - */ - protected static deserialize(data: string): Asset { - return cc.deserialize(data); + constructor () { + super(); + /** + * !#en + * Whether the asset is loaded or not + * !#zh + * 该资源是否已经成功加载 + * + * @property loaded + * @type {Boolean} + */ + this.loaded = true; } - /** - * !#en - * Create a new node using this asset in the scene.
- * If this type of asset dont have its corresponding node type, this method should be null. - * !#zh - * 使用该资源在场景中创建一个新节点。
- * 如果这类资源没有相应的节点类型,该方法应该是空的。 - * - * @param {Function} callback - * @param {String} callback.error - null or the error info - * @param {Object} callback.node - the created node or null - */ - public createNode: null | ((callback: (err: string, node: object) => void) => void) = null; - - protected loaded = true; - - /** - * Serializable url for native asset. - */ - @property - protected _native = ''; - /** * !#en * Returns the url of this asset's native object, if none it will returns an empty string. * !#zh * 返回该资源对应的目标平台资源的 URL,如果没有将返回一个空字符串。 + * @property nativeUrl + * @type {String} + * @readOnly */ @property({ - visible: false, + visible: false }) - get nativeUrl(): Readonly { + get nativeUrl () { if (this._native) { - const name = this._native; + var name = this._native; if (name.charCodeAt(0) === 47) { // '/' // remove library tag // not imported in library, just created on-the-fly return name.slice(1); } if (cc.AssetLibrary) { - const base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); + var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); if (name.charCodeAt(0) === 46) { // '.' // imported in dir where json exist return base + name; - } else { + } + else { // imported in an independent dir return base + '/' + name; } - } else { + } + else { cc.errorID(6400); } } return ''; } + /** + * Serializable url for native asset. + * @property {String} _native + * @default "" + * @private + */ + @property + _native = "" + /** * The underlying native asset of this asset if one is available. * This property can be used to access additional details or functionality releated to the asset. @@ -140,42 +121,104 @@ export class Asset extends RawAsset { * @type {any} */ @property - get _nativeAsset() { return null; } - set _nativeAsset(obj) {} + get _nativeAsset () { + } + set _nativeAsset (obj) { + } + + /** + * 应 AssetDB 要求提供这个方法 + * + * @method deserialize + * @param {String} data + * @return {Asset} + * @static + * @private + */ + static deserialize (data) { + return cc.deserialize(data); + } + + /** + * !#en Indicates whether its dependent raw assets can support deferred load if the owner scene (or prefab) is marked as `asyncLoadAssets`. + * !#zh 当场景或 Prefab 被标记为 `asyncLoadAssets`,禁止延迟加载该资源所依赖的其它 RawAsset。 + * + * @property {Boolean} preventDeferredLoadDependents + * @default false + * @static + */ + static preventDeferredLoadDependents = false; + + /** + * !#en Indicates whether its native object should be preloaded from native url. + * !#zh 禁止预加载原生对象。 + * + * @property {Boolean} preventPreloadNativeObject + * @default false + * @static + */ + static preventPreloadNativeObject = false; /** * Returns the string representation of the object. * * The `Asset` object overrides the `toString()` method of the `Object` object. - * JavaScript calls the toString() method automatically when an asset is to be represented - * as a text value or when a texture is referred to in a string concatenation. + * JavaScript calls the toString() method automatically when an asset is to be represented as a text value or when a texture is referred to in a string concatenation. * * For assets of the native type, it will return `this.nativeUrl`. * Otherwise, an empty string is returned. * This method may be overwritten by subclasses. + * + * @method toString + * @return {String} */ - public toString(): string { + toString () { return this.nativeUrl; } + /** + * 应 AssetDB 要求提供这个方法 + * + * @method serialize + * @return {String} + * @private + */ + serialize () { + return Editor.serialize(this); + } + /** * Set native file name for this asset. * @seealso nativeUrl + * + * @method _setRawAsset + * @param {String} filename + * @param {Boolean} [inLibrary=true] + * @private */ - protected _setRawAsset(filename: string, inLibrary: boolean = true) { + _setRawAsset (filename, inLibrary) { if (inLibrary !== false) { - this._native = filename; - } else { + this._native = filename || undefined; + } + else { this._native = '/' + filename; // simply use '/' to tag location where is not in the library } } - - /** - * 应 AssetDB 要求提供这个方法 - */ - protected serialize(): string { - return Editor.serialize(this); - } } +/** + * !#en + * Create a new node using this asset in the scene.
+ * If this type of asset dont have its corresponding node type, this method should be null. + * !#zh + * 使用该资源在场景中创建一个新节点。
+ * 如果这类资源没有相应的节点类型,该方法应该是空的。 + * + * @method createNode + * @param {Function} callback + * @param {String} callback.error - null or the error info + * @param {Object} callback.node - the created node or null + */ +Asset.prototype.createNode = null; + cc.Asset = Asset; diff --git a/cocos/assets/raw-asset.d.ts b/cocos/assets/raw-asset.d.ts new file mode 100644 index 0000000000..186076cde8 --- /dev/null +++ b/cocos/assets/raw-asset.d.ts @@ -0,0 +1,31 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { CCObject } from '../core/data/object'; + +export class RawAsset extends CCObject { + _uuid: string; +} diff --git a/cocos/assets/raw-asset.ts b/cocos/assets/raw-asset.js similarity index 73% rename from cocos/assets/raw-asset.ts rename to cocos/assets/raw-asset.js index 9b4c2ff473..52b902900a 100644 --- a/cocos/assets/raw-asset.ts +++ b/cocos/assets/raw-asset.js @@ -24,34 +24,45 @@ THE SOFTWARE. ****************************************************************************/ -import { ccclass } from '../core/data/class-decorator'; -import { CCObject } from '../core/data/object'; import { isChildClassOf } from '../core/utils/js'; - -function enumerable(value: boolean) { - return (target: any, propertyKey: string) => { - const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) || {}; - if (descriptor.enumerable !== value) { - descriptor.enumerable = value; - Object.defineProperty(target, propertyKey, descriptor); - } - }; -} +import { CCObject } from '../core/data/object'; +import { ccclass } from '../core/data/class-decorator'; /** * !#en * The base class for registering asset types. * !#zh * 注册用的资源基类。 + * + * @class RawAsset + * @extends Object */ @ccclass('cc.RawAsset') export class RawAsset extends CCObject { - protected static isRawAssetType(ctor: Function): boolean { - return isChildClassOf(ctor, RawAsset) && !isChildClassOf(ctor, cc.Asset); + constructor () { + super(); + /** + * @property _uuid + * @type {String} + * @private + */ + Object.defineProperty(this, '_uuid', { + value: '', + writable: true, + // enumerable is false by default, to avoid uuid being assigned to empty string during destroy + }); } - @enumerable(false) - protected _uuid = ''; + /** + * @method isRawAssetType + * @param {Function} ctor + * @returns {Boolean} + * @static + * @private + */ + static isRawAssetType (ctor) { + return isChildClassOf(ctor, cc.RawAsset) && !isChildClassOf(ctor, cc.Asset); + } } cc.RawAsset = RawAsset; diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts new file mode 100644 index 0000000000..e24850f93b --- /dev/null +++ b/cocos/core/data/object.d.ts @@ -0,0 +1,29 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +export class CCObject { + _name: string; + name: string; +} diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.js similarity index 83% rename from cocos/core/data/object.ts rename to cocos/core/data/object.js index 440bbf2c05..28f6d03d37 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.js @@ -38,8 +38,8 @@ const DontDestroy = 1 << 6; const Destroying = 1 << 7; const Deactivating = 1 << 8; const LockedInEditor = 1 << 9; -// const HideInGame = 1 << 9; -const HideInHierarchy = 1 << 10; +//var HideInGame = 1 << 9; +var HideInHierarchy = 1 << 10; const IsOnEnableCalled = 1 << 11; const IsEditorOnEnableCalled = 1 << 12; @@ -54,7 +54,7 @@ const IsAnchorLocked = 1 << 19; const IsSizeLocked = 1 << 20; const IsPositionLocked = 1 << 21; -// const Hide = HideInGame | HideInEditor; +//var Hide = HideInGame | HideInEditor; // should not clone or serialize these flags const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | @@ -62,34 +62,37 @@ const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactiva IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked /*RegisteredInEditor*/); -const objectsToDestroy: CCObject[] = []; -let deferredDestroyTimer = null; +var objectsToDestroy = []; +var deferredDestroyTimer = null; -function compileDestruct(obj: object, ctor) { - const shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; - const idToSkip = shouldSkipId ? '_id' : null; +function compileDestruct (obj, ctor) { + var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; + var idToSkip = shouldSkipId ? '_id' : null; - const propsToReset = {}; - for (const key of Object.keys(obj)) { - if (key === idToSkip) { - continue; - } - switch (typeof obj[key]) { - case 'string': - propsToReset[key] = ''; - break; - case 'object': - case 'function': - propsToReset[key] = null; - break; + var key, propsToReset = {}; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + if (key === idToSkip) { + continue; + } + switch (typeof obj[key]) { + case 'string': + propsToReset[key] = ''; + break; + case 'object': + case 'function': + propsToReset[key] = null; + break; + } } } // Overwrite propsToReset according to Class if (CCClass._isCCClass(ctor)) { - const attrs = cc.Class.Attr.getClassAttrs(ctor); - const propList = ctor.__props__; - for (const key of propList) { - const attrKey = key + cc.Class.Attr.DELIMETER + 'default'; + var attrs = cc.Class.Attr.getClassAttrs(ctor); + var propList = ctor.__props__; + for (var i = 0; i < propList.length; i++) { + key = propList[i]; + var attrKey = key + cc.Class.Attr.DELIMETER + 'default'; if (attrKey in attrs) { if (shouldSkipId && key === '_id') { continue; @@ -112,24 +115,26 @@ function compileDestruct(obj: object, ctor) { if (CC_SUPPORT_JIT) { // compile code - let func = ''; - for (const key of Object.keys(propsToReset)) { - let statement: string; + var func = ''; + for (key in propsToReset) { + var statement; if (CCClass.IDENTIFIER_RE.test(key)) { statement = 'o.' + key + '='; - } else { + } + else { statement = 'o[' + CCClass.escapeForJS(key) + ']='; } - let val = propsToReset[key]; + var val = propsToReset[key]; if (val === '') { val = '""'; } func += (statement + val + ';\n'); } return Function('o', func); - } else { - return (o: object) => { - for (const key of Object.keys(propsToReset)) { + } + else { + return function (o) { + for (var key in propsToReset) { o[key] = propsToReset[key]; } }; @@ -144,10 +149,26 @@ function compileDestruct(obj: object, ctor) { * @private */ class CCObject { - protected static _deferredDestroy() { - const deleteCount = objectsToDestroy.length; - for (let i = 0; i < deleteCount; ++i) { - const obj = objectsToDestroy[i]; + constructor (name = '') { + /** + * @property {String} _name + * @default "" + * @private + */ + this._name = name; + + /** + * @property {Number} _objFlags + * @default 0 + * @private + */ + this._objFlags = 0; + } + + static _deferredDestroy () { + var deleteCount = objectsToDestroy.length; + for (var i = 0; i < deleteCount; ++i) { + var obj = objectsToDestroy[i]; if (!(obj._objFlags & Destroyed)) { obj._destroyImmediate(); } @@ -156,7 +177,8 @@ class CCObject { // but we only destroy the objects which called destory in this frame. if (deleteCount === objectsToDestroy.length) { objectsToDestroy.length = 0; - } else { + } + else { objectsToDestroy.splice(0, deleteCount); } @@ -165,23 +187,20 @@ class CCObject { } } - protected _name = ''; - protected _objFlags = 0; - - constructor(name = '') { - this._name = name; - } - // MEMBER /** * !#en The name of the object. * !#zh 该对象的名称。 + * @property {String} name + * @default "" + * @example + * obj.name = "New Obj"; */ - get name() { + get name () { return this._name; } - set name(value) { + set name (value) { this._name = value; } @@ -195,19 +214,20 @@ class CCObject { * * !#zh * 表示该对象是否可用(被 destroy 后将不可用)。
- * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。因此从下一帧开始 `isValid` 就会返回 false - * 而当前帧内 `isValid` 仍然会是 true。如果希望判断当前帧是否调用过 `destroy` - * 请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 + * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 * + * @property {Boolean} isValid + * @default true + * @readOnly * @example - * const node = new cc.Node(); + * var node = new cc.Node(); * cc.log(node.isValid); // true * node.destroy(); * cc.log(node.isValid); // true, still valid in this frame * // after a frame... * cc.log(node.isValid); // false, destroyed in the end of last frame */ - get isValid(): Readonly { + get isValid () { return !(this._objFlags & Destroyed); } @@ -221,8 +241,12 @@ class CCObject { * 销毁该对象,并释放所有它对其它对象的引用。
* 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。 * 您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + * @method destroy + * @return {Boolean} whether it is the first time the destroy being called + * @example + * obj.destroy(); */ - public destroy() { + destroy () { if (this._objFlags & Destroyed) { cc.warnID(5000); return false; @@ -246,7 +270,7 @@ class CCObject { * NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. * You can override the _destruct method if you need, for example: * _destruct: function () { - * for (const key in this) { + * for (var key in this) { * if (this.hasOwnProperty(key)) { * switch (typeof this[key]) { * case 'string': @@ -260,10 +284,12 @@ class CCObject { * } * } * + * @method _destruct + * @private */ - protected _destruct() { - const ctor = this.constructor; - let destruct = ctor.__destruct__; + _destruct () { + var ctor = this.constructor; + var destruct = ctor.__destruct__; if (!destruct) { destruct = compileDestruct(this, ctor); js.value(ctor, '__destruct__', destruct, true); @@ -271,7 +297,7 @@ class CCObject { destruct(this); } - protected _destroyImmediate() { + _destroyImmediate () { if (this._objFlags & Destroyed) { cc.errorID(5000); return; @@ -289,7 +315,7 @@ class CCObject { } } -const prototype = CCObject.prototype; +let prototype = CCObject.prototype; if (CC_EDITOR || CC_TEST) { js.get(prototype, 'isRealValid', function () { return !(this._objFlags & RealDestroyed); @@ -483,26 +509,27 @@ js.value(CCObject, 'Flags', { * @param {Boolean} [strictMode=false] - If true, Object called destroy() in this frame will also treated as invalid. * @return {Boolean} whether is valid * @example - * const node = new cc.Node(); + * var node = new cc.Node(); * cc.log(cc.isValid(node)); // true * node.destroy(); * cc.log(cc.isValid(node)); // true, still valid in this frame * // after a frame... * cc.log(cc.isValid(node)); // false, destroyed in the end of last frame */ -cc.isValid = (value, strictMode) => { +cc.isValid = function (value, strictMode) { if (typeof value === 'object') { return !!value && !(value._objFlags & (strictMode ? (Destroyed | ToDestroy) : Destroyed)); - } else { + } + else { return typeof value !== 'undefined'; } }; if (CC_EDITOR || CC_TEST) { - js.value(CCObject, '_willDestroy', (obj) => { + js.value(CCObject, '_willDestroy', function (obj) { return !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0; }); - js.value(CCObject, '_cancelDestroy', (obj) => { + js.value(CCObject, '_cancelDestroy', function (obj) { obj._objFlags &= ~ToDestroy; js.array.fastRemove(objectsToDestroy, obj); }); From 87a6672db52cc951ddc9a39def707c8d887fed79 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 14:17:30 +0800 Subject: [PATCH 044/267] fix pass --- cocos/3d/assets/material.ts | 12 +++++----- cocos/assets/asset.d.ts | 13 +++++++++++ cocos/assets/raw-asset.d.ts | 1 + cocos/core/data/object.d.ts | 22 +++++++++++++++++-- cocos/pipeline/forward/test-material-stage.ts | 8 +++---- cocos/renderer/core/pass.ts | 19 +++++++++++++--- 6 files changed, 60 insertions(+), 15 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 2e7aca848c..949c037baa 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -95,15 +95,15 @@ export class Material extends Asset { this._props[passIdx][name] = val; const pass = this._passes[passIdx]; const handle = pass.getHandleFromName(name); - pass.setUniformMember(handle, val); + pass.setUniform(handle, val); } public setTexture(name: string, val: TextureBase, passIdx = 0) { console.assert(passIdx < this._passes.length, 'illegal pass index.'); this._textures[passIdx][name] = val; const pass = this._passes[passIdx]; - const handle = pass.getHandleFromName(name); - pass.setTextureView(handle, val._texView); + const binding = pass.getBindingFromName(name); + pass.bindTextureView(binding, val._texView); } public copy(mat: Material) { @@ -146,13 +146,13 @@ export class Material extends Asset { if (!props) { props = this._props[i] = {}; } for (const p of Object.keys(props)) { const handle = pass.getHandleFromName(p); - pass.setUniformMember(handle, props[p]); + pass.setUniform(handle, props[p]); } let textures = this._textures[i]; if (!textures) { textures = this._textures[i] = {}; } for (const t of Object.keys(textures)) { - const handle = pass.getHandleFromName(t); - pass.setTextureView(handle, textures[t]._texView); + const binding = pass.getBindingFromName(t); + pass.bindTextureView(binding, textures[t]._texView); } }); } else { diff --git a/cocos/assets/asset.d.ts b/cocos/assets/asset.d.ts index 07c9afee5c..9055813b31 100644 --- a/cocos/assets/asset.d.ts +++ b/cocos/assets/asset.d.ts @@ -26,5 +26,18 @@ import { RawAsset } from "./raw-asset"; export class Asset extends RawAsset { + protected _native: string; + protected loaded: boolean; + public _nativeAsset: any; + public nativeUrl: string; + + static preventDeferredLoadDependents: boolean; + static preventPreloadNativeObject: boolean; + static deserialize(data: string): object; + + public createNode: (err: string, node: object) => void | null; + public toString(): string; + public serialize(): string; + protected _setRawAsset(filename: string, inLibrary: boolean): void; } diff --git a/cocos/assets/raw-asset.d.ts b/cocos/assets/raw-asset.d.ts index 186076cde8..4c5fcf5fb0 100644 --- a/cocos/assets/raw-asset.d.ts +++ b/cocos/assets/raw-asset.d.ts @@ -28,4 +28,5 @@ import { CCObject } from '../core/data/object'; export class RawAsset extends CCObject { _uuid: string; + static isRawAssetType(ctor: Function): boolean; } diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts index e24850f93b..a14ac9e6f0 100644 --- a/cocos/core/data/object.d.ts +++ b/cocos/core/data/object.d.ts @@ -24,6 +24,24 @@ ****************************************************************************/ export class CCObject { - _name: string; - name: string; + protected _name: string; + protected _objFlags: number; + + static _deferredDestroy(): void; + + public name: string; + public isValid: boolean; + public isRealValid: boolean; + + public destroy(): boolean; + public realDestroyInEditor(): void; + public _clearDeferredDestroyTimer(): void; + + protected _destruct(): void; + protected _destroyImmediate(): void; + + protected _serialize: (exporting: boolean) => object | null; + protected _deserialize: (data: object, ctx: object) => object | null; + protected _onPreDestroy: () => void | null; + protected Flags: object; } diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index 28c8bb5975..4b3b0a75c8 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -74,10 +74,10 @@ export class TestMaterialStage extends RenderStage { // material this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js const pass = this._material.passes[0]; - const handle1 = pass.getHandleFromName('u_sampler'); - pass.setTextureView(handle1, this._texView); - const handle2 = pass.getHandleFromName('u_color'); - pass.setUniformMember(handle2, cc.color('#ffffff')); + const texBinding = pass.getBindingFromName('u_sampler'); + pass.bindTextureView(texBinding, this._texView); + const colorHandle = pass.getHandleFromName('u_color'); + pass.setUniform(colorHandle, cc.color('#ffffff')); pass.update(); this._material.inited = true; } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 9b4c797e05..98f35c97e7 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -156,7 +156,11 @@ export class Pass { return this._handleMap[name]; } - public setUniformMember(handle: number, value: any) { + public getBindingFromName(name: string) { + return parseHandle(this.getHandleFromName(name))[0]; + } + + public setUniform(handle: number, value: any) { const [ binding, idx ] = parseHandle(handle); const block = this._blocks[binding]; const type = this._typeMap[handle]; @@ -164,8 +168,7 @@ export class Pass { block.dirty = true; } - public setTextureView(handle: number, value: GFXTextureView) { - const [ binding ] = parseHandle(handle); + public bindTextureView(binding: number, value: GFXTextureView) { const bl = this._bindingLayout; if (bl && bl.getBindingUnit(binding).texView !== value) { bl.bindTextureView(binding, value); @@ -173,6 +176,14 @@ export class Pass { } } + public bindSampler(binding: number, value: GFXSampler) { + const bl = this._bindingLayout; + if (bl && bl.getBindingUnit(binding).sampler !== value) { + bl.bindSampler(binding, value); + this._layoutDirty = true; + } + } + public setStates(info: PassInfoBase) { if (this._pipelineState) { this._pipelineState.destroy(); } this.createPipelineState(info); @@ -192,10 +203,12 @@ export class Pass { const block = this._blocks[i]; if (block.dirty) { this._buffers[i].update(block.buffer); + block.dirty = false; } } if (this._bindingLayout && this._layoutDirty) { this._bindingLayout.update(); + this._layoutDirty = false; } } From 83b242892c17c82637ad0b609b00e26fae5b5b84 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 14:22:54 +0800 Subject: [PATCH 045/267] fix floating uniform comparison bug --- cocos/core/vmath/vec3.js | 7 ++ cocos/gfx/webgl/webgl-commands.ts | 96 ++++++++++++++++------------ cocos/pipeline/forward/test-stage.ts | 19 ++++-- cocos/pipeline/render-pipeline.ts | 2 +- cocos/renderer/scene/camera.ts | 26 ++++++-- 5 files changed, 97 insertions(+), 53 deletions(-) diff --git a/cocos/core/vmath/vec3.js b/cocos/core/vmath/vec3.js index 09cb1e2012..2b5bcd5383 100644 --- a/cocos/core/vmath/vec3.js +++ b/cocos/core/vmath/vec3.js @@ -33,6 +33,13 @@ class vec3 { this.z = z; } + static UNIT_X = { x: 1, y: 0, z: 0 }; + static UNIT_Y = { x: 0, y: 1, z: 0 }; + static UNIT_Z = { x: 0, y: 0, z: 1 }; + static ZERO = { x: 0, y: 0, z: 0 }; + static ONE = { x: 1, y: 1, z: 1 }; + static NEG_ONE = { x: -1, y: -1, z: -1 }; + /** * Creates a vector, with components specified separately. * diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index c348a2eac1..5d02e0316e 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -4,6 +4,11 @@ import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; import { WebGLTexUnit } from "./webgl-state-cache"; +function CmpF32NotEuqal(a: number, b: number): boolean { + let c = a - b; + return (c > 0.000001 || c < -0.000001); +} + function GFXFormatToWebGLType(format: GFXFormat, device: WebGLGFXDevice): GLenum { switch (format) { case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; @@ -1075,7 +1080,7 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput count: GFXFormatInfos[attrib.format].count, stride: gpuBuffer.stride, componentCount: WebGLGetComponentCount(glType), - isNormalized: (attrib.isNormalized !== undefined? attrib.isNormalized : false), + isNormalized: (attrib.isNormalized !== undefined ? attrib.isNormalized : false), isInstanced: (attrib.isInstanced !== undefined ? attrib.isInstanced : false), offset: offsets[stream], }; @@ -1657,8 +1662,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT: { for (let m = 0; m < glUniform.count; ++m, ++offset) { - if (vf32[offset] !== glUniform.view[m]) { - + let c: number = 0; + + if (CmpF32NotEuqal(vf32[offset], glUniform.view[m])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); gl.uniform1fv(glUniform.glLoc, glUniform.view); @@ -1670,8 +1676,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_VEC2: { for (let m = 0; m < glUniform.count; ++m, offset += 2) { let idx = 2 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1]) { + if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); @@ -1684,9 +1690,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_VEC3: { for (let m = 0; m < glUniform.count; ++m, offset += 3) { let idx = 3 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2]) { + if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); @@ -1700,10 +1706,16 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_VEC4: { for (let m = 0; m < glUniform.count; ++m, offset += 4) { let idx = 4 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2] || - vf32[offset + 3] !== glUniform.view[idx + 3]) { + + var a = 12.345; + var b = ~~a; //boom! + + console.info("b: "+b); + + if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); @@ -1716,10 +1728,10 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_MAT2: { for (let m = 0; m < glUniform.count; ++m, offset += 4) { let idx = 4 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2] || - vf32[offset + 3] !== glUniform.view[idx + 3]) { + if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); @@ -1732,15 +1744,15 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.FLOAT_MAT3: { for (let m = 0; m < glUniform.count; ++m, offset += 9) { let idx = 9 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2] || - vf32[offset + 3] !== glUniform.view[idx + 3] || - vf32[offset + 4] !== glUniform.view[idx + 4] || - vf32[offset + 5] !== glUniform.view[idx + 5] || - vf32[offset + 6] !== glUniform.view[idx + 6] || - vf32[offset + 7] !== glUniform.view[idx + 7] || - vf32[offset + 8] !== glUniform.view[idx + 8]) { + if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3]) || + CmpF32NotEuqal(vf32[offset + 4], glUniform.view[idx + 4]) || + CmpF32NotEuqal(vf32[offset + 5], glUniform.view[idx + 5]) || + CmpF32NotEuqal(vf32[offset + 6], glUniform.view[idx + 6]) || + CmpF32NotEuqal(vf32[offset + 7], glUniform.view[idx + 7]) || + CmpF32NotEuqal(vf32[offset + 8], glUniform.view[idx + 8])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 9 * glUniform.count)); @@ -1751,25 +1763,25 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLRenderingContext.FLOAT_MAT4: { - let offset = glUniform.offset; for (let m = 0; m < glUniform.count; ++m, offset += 16) { let idx = 16 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2] || - vf32[offset + 3] !== glUniform.view[idx + 3] || - vf32[offset + 4] !== glUniform.view[idx + 4] || - vf32[offset + 5] !== glUniform.view[idx + 5] || - vf32[offset + 6] !== glUniform.view[idx + 6] || - vf32[offset + 7] !== glUniform.view[idx + 7] || - vf32[offset + 8] !== glUniform.view[idx + 8] || - vf32[offset + 9] !== glUniform.view[idx + 9] || - vf32[offset + 10] !== glUniform.view[idx + 10] || - vf32[offset + 11] !== glUniform.view[idx + 11] || - vf32[offset + 12] !== glUniform.view[idx + 12] || - vf32[offset + 13] !== glUniform.view[idx + 13] || - vf32[offset + 14] !== glUniform.view[idx + 14] || - vf32[offset + 15] !== glUniform.view[idx + 15]) { + + if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3]) || + CmpF32NotEuqal(vf32[offset + 4], glUniform.view[idx + 4]) || + CmpF32NotEuqal(vf32[offset + 5], glUniform.view[idx + 5]) || + CmpF32NotEuqal(vf32[offset + 6], glUniform.view[idx + 6]) || + CmpF32NotEuqal(vf32[offset + 7], glUniform.view[idx + 7]) || + CmpF32NotEuqal(vf32[offset + 8], glUniform.view[idx + 8]) || + CmpF32NotEuqal(vf32[offset + 9], glUniform.view[idx + 9]) || + CmpF32NotEuqal(vf32[offset + 10], glUniform.view[idx + 10]) || + CmpF32NotEuqal(vf32[offset + 11], glUniform.view[idx + 11]) || + CmpF32NotEuqal(vf32[offset + 12], glUniform.view[idx + 12]) || + CmpF32NotEuqal(vf32[offset + 13], glUniform.view[idx + 13]) || + CmpF32NotEuqal(vf32[offset + 14], glUniform.view[idx + 14]) || + CmpF32NotEuqal(vf32[offset + 15], glUniform.view[idx + 15])) { let begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 16 * glUniform.count)); diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 4b4ab54166..677bc3c90d 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -4,7 +4,6 @@ import { GFXCommandBuffer } from "../../gfx/command-buffer"; import { RenderView } from "../render-view"; import { GFXFramebuffer } from "../../gfx/framebuffer"; import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXTextureLayout, GFXBufferTextureCopy, GFXAddress, GFXFilter, GFXBindingType, GFXType, GFXCullMode } from "../../gfx/define"; -import { GFXInputAssembler } from "../../gfx/input-assembler"; import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; import { GFXShader } from "../../gfx/shader"; import { GFXRenderPass } from "../../gfx/render-pass"; @@ -28,13 +27,13 @@ let _shader_vs = `#version 100 attribute vec2 a_position; attribute vec2 a_texCoord; -//uniform mat4 u_matWorldViewProj; +uniform mat4 u_matViewProj; varying vec2 v_texCoord; void main() { - gl_Position = vec4(a_position, 0.0, 1.0); - //gl_Position = u_matWorldViewProj * vec4(a_position, 0.0, 1.0); + //gl_Position = vec4(a_position, 0.0, 1.0); + gl_Position = u_matViewProj * vec4(a_position, 0.0, 1.0); v_texCoord = a_texCoord; }`; @@ -91,7 +90,16 @@ export class TestStage extends RenderStage { stages: [vsStage, fsStage], blocks: [{ binding: 0, name: "Global", members: [ - { name: "u_matWorldViewProj", type: GFXType.MAT4, count: 1 }, + { name: "u_time", type: GFXType.FLOAT4, count: 1 }, + { name: "u_screenSize", type: GFXType.FLOAT4, count: 1 }, + { name: "u_screenScale", type: GFXType.FLOAT4, count: 1 }, + { name: "u_matView", type: GFXType.MAT4, count: 1 }, + { name: "u_matViewInv", type: GFXType.MAT4, count: 1 }, + { name: "u_matProj", type: GFXType.MAT4, count: 1 }, + { name: "u_matProjInv", type: GFXType.MAT4, count: 1 }, + { name: "u_matViewProj", type: GFXType.MAT4, count: 1 }, + { name: "u_matViewProjInv", type: GFXType.MAT4, count: 1 }, + { name: "u_cameraPos", type: GFXType.FLOAT4, count: 1 }, ] }, { binding: 5, name: "UBO", members: [ @@ -108,6 +116,7 @@ export class TestStage extends RenderStage { this._bindingLayout = this._device.createBindingLayout({ bindings: [ + { binding: 0, type: GFXBindingType.UNIFORM_BUFFER, name: "Global" }, { binding: 5, type: GFXBindingType.UNIFORM_BUFFER, name: "UBO" }, { binding: 10, type: GFXBindingType.SAMPLER, name: "u_sampler" }, ], diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index f56eb8f420..0f9e6fef52 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -22,7 +22,7 @@ export class UBOGlobal { static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16; static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16; - static MAT_VIEW_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; + static MAT_VIEW_PROJ_OFFSET: number = UBOGlobal.MAT_PROJ_INV_OFFSET + 16; static MAT_VIEW_PROJ_INV_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_OFFSET + 16; static CAMERA_POS_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET + 16; static COUNT: number = UBOGlobal.CAMERA_POS_OFFSET + 4; diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 5d1f7a4bdf..635d01b374 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,7 +1,6 @@ import { RenderScene } from "./render-scene"; import Node from "../../scene-graph/node"; -import vec3 from "../../core/vmath/vec3"; -import mat4 from "../../core/vmath/mat4"; +import { mat4, vec3, quat } from '../../core/vmath'; export enum CameraProjection { PERSPECTIVE, @@ -115,13 +114,28 @@ export class Camera { return this._matViewProj; } + public get position(): vec3 { + this._node.getWorldPosition(this._position); + return this._position; + } + + public set target(target: vec3) { + this._node.lookAt(target); + } + + public get direction(): vec3 { + quat.getRotation(this._rotation); + quat.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); + return this._direction; + } + public set position(pos: vec3) { this._node.setWorldPosition(pos.x, pos.y, pos.z); } - public get position(): vec3 { - this._node.getWorldPosition(this._position); - return this._position; + public set direction(dir: vec3) { + quat.rotationTo(this._rotation, vec3.UNIT_Z, dir); + this._node.setRotation(this._rotation); } private _scene: RenderScene; @@ -138,4 +152,6 @@ export class Camera { private _matProj: mat4 = new mat4; private _matViewProj: mat4 = new mat4; private _position: vec3 = new vec3; + private _rotation: quat = new quat; + private _direction: vec3 = new vec3; }; From 7d6fec475b29432e83d8ada20632cd85ac322b13 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 14:46:08 +0800 Subject: [PATCH 046/267] remove test code --- cocos/gfx/webgl/webgl-commands.ts | 5 ----- cocos/pipeline/forward/forward-flow.ts | 11 ++++++++++- playground/simple.html | 10 ++++++---- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 5d02e0316e..0d5c4acec3 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1707,11 +1707,6 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG for (let m = 0; m < glUniform.count; ++m, offset += 4) { let idx = 4 * m; - var a = 12.345; - var b = ~~a; //boom! - - console.info("b: "+b); - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 67509a697b..100369cc7a 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -2,6 +2,7 @@ import { RenderFlow, RenderFlowInfo } from "../render-flow"; import { RenderPipeline } from "../render-pipeline"; // import { TestStage } from "./test-stage"; import { TestMaterialStage } from "./test-material-stage"; +import { TestStage } from "./test-stage"; export enum ForwardStagePriority { FORWARD = 0, @@ -22,7 +23,7 @@ export class ForwardFlow extends RenderFlow { this._priority = info.priority; let mainWindow = this._pipeline.root.mainWindow; - if(!mainWindow || !mainWindow.framebuffer) { + if (!mainWindow || !mainWindow.framebuffer) { return false; } @@ -40,6 +41,14 @@ export class ForwardFlow extends RenderFlow { framebuffer: mainWindow.framebuffer, }); + /* + this.createStage(TestStage, { + name: "TestStage", + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + */ + return true; } diff --git a/playground/simple.html b/playground/simple.html index 8f4c14c512..66149dabee 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -35,8 +35,8 @@ const bcr = $body.getBoundingClientRect(); // cc.view.setCanvasSize(bcr.width, bcr.height); window.addEventListener('resize', () => { - const bcr = $body.getBoundingClientRect(); - cc.view.setCanvasSize(bcr.width, bcr.height); + const bcr = $body.getBoundingClientRect(); + cc.view.setCanvasSize(bcr.width, bcr.height); }); let root = cc.director.root; @@ -57,7 +57,9 @@ view.attach(scene.mainCamera); let camera = scene.mainCamera; - //camera.position = vec3(0.0, 0.0, 5.0); + camera.position = { x: 0.0, y: 0.0, z: 3.0 }; + camera.direction = { x: 0.0, y: 0.0, z: -1.0 }; + camera.update(); //todo initialization @@ -96,4 +98,4 @@ - + \ No newline at end of file From c2e8b864cb4a77bce408b6e0bce17c8ffd819d3b Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 16:01:42 +0800 Subject: [PATCH 047/267] rename RenderPassStage.FORWARD to RenderPassStage.DEFAULT --- cocos/pipeline/forward/forward-pipeline.ts | 2 +- cocos/renderer/core/effect.ts | 2 +- cocos/renderer/core/pass.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index ddc813292d..c850d65c29 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -36,7 +36,7 @@ export class ForwardPipeline extends RenderPipeline { return false; } - this.addRenderPass(RenderPassStage.FORWARD, windowPass); + this.addRenderPass(RenderPassStage.WINDOW, windowPass); // create UBOs this._globalUBO = this._root.device.createBuffer({ diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index b5780c163f..55eb392cab 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -166,7 +166,7 @@ export class Effect { }; }); passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines || {}); - passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.FORWARD); + passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.WINDOW); passInfo.blocks = programs[passInfo.program].blocks; passInfo.samplers = programs[passInfo.program].samplers; const pass = new Pass(cc.game._gfxDevice); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 98f35c97e7..ec42a8432f 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -70,7 +70,7 @@ export class Pass { // internal data protected _programName: string = ''; protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; - protected _stage: RenderPassStage = RenderPassStage.FORWARD; + protected _stage: RenderPassStage = RenderPassStage.WINDOW; protected _handleMap: Record = {}; protected _typeMap: Record = {}; protected _blocks: Block[] = []; From a7fdb4edf28a47f72d53af5bc72e4091054e79f8 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 16:02:44 +0800 Subject: [PATCH 048/267] rename RenderPassStage.FORWARD to RenderPassStage.DEFAULT --- cocos/pipeline/forward/forward-pipeline.ts | 2 +- cocos/renderer/core/effect.ts | 2 +- cocos/renderer/core/pass.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index c850d65c29..59634d6023 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -36,7 +36,7 @@ export class ForwardPipeline extends RenderPipeline { return false; } - this.addRenderPass(RenderPassStage.WINDOW, windowPass); + this.addRenderPass(RenderPassStage.DEFAULT, windowPass); // create UBOs this._globalUBO = this._root.device.createBuffer({ diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 55eb392cab..30dc97bd35 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -166,7 +166,7 @@ export class Effect { }; }); passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines || {}); - passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.WINDOW); + passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); passInfo.blocks = programs[passInfo.program].blocks; passInfo.samplers = programs[passInfo.program].samplers; const pass = new Pass(cc.game._gfxDevice); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index ec42a8432f..81f3caae8a 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -70,7 +70,7 @@ export class Pass { // internal data protected _programName: string = ''; protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; - protected _stage: RenderPassStage = RenderPassStage.WINDOW; + protected _stage: RenderPassStage = RenderPassStage.DEFAULT; protected _handleMap: Record = {}; protected _typeMap: Record = {}; protected _blocks: Block[] = []; From 9b2200672ef7e06113e74f511b07b6241cbfe8cd Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 16:03:37 +0800 Subject: [PATCH 049/267] rename --- cocos/pipeline/render-pipeline.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 0f9e6fef52..6287654950 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -11,7 +11,7 @@ import vec4 from "../core/vmath/vec4"; import mat4 from "../core/vmath/mat4"; export enum RenderPassStage { - FORWARD = 100, + DEFAULT = 100, }; export class UBOGlobal { From 06eb5d80606e9dd3c3fa21346260e5a68614e688 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 16:38:26 +0800 Subject: [PATCH 050/267] fix tsc errors --- cocos/3d/assets/material.ts | 50 ++++++++++++++----- cocos/3d/framework/animation-component.js | 2 +- cocos/3d/framework/camera-component.js | 2 +- cocos/3d/framework/light-component.js | 2 +- .../particle/particle-system-component.js | 2 +- cocos/3d/framework/physics/body.ts | 12 ++--- .../physics/detail/physics-based-component.ts | 2 +- cocos/3d/framework/physics/world.ts | 11 ++-- cocos/3d/framework/renderSystemActor.js | 2 +- cocos/3d/framework/renderable-component.js | 2 +- cocos/3d/framework/skybox-component.js | 2 +- cocos/animation/CCAnimation.js | 26 +++++----- cocos/audio/CCAudioSource.js | 6 +-- cocos/camera/CCCamera.js | 2 +- cocos/components/CCCanvas.js | 4 +- cocos/components/WXSubContextView.js | 8 +-- cocos/components/component.d.ts | 48 ++++++++++++++++++ .../{CCComponent.js => component.js} | 2 +- cocos/components/index.js | 4 +- cocos/components/missing-script.js | 4 +- cocos/gfx/webgl/webgl-state-cache.ts | 2 +- cocos/pipeline/forward/test-material-stage.ts | 2 + cocos/renderer/core/pass.ts | 4 +- cocos/renderer/scene/model.ts | 10 ++-- globals.d.ts | 40 +++++++++++++++ 25 files changed, 185 insertions(+), 66 deletions(-) create mode 100644 cocos/components/component.d.ts rename cocos/components/{CCComponent.js => component.js} (99%) create mode 100644 globals.d.ts diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 949c037baa..283e6084da 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -90,20 +90,44 @@ export class Material extends Asset { this.update(); } - public setProperty(name: string, val: any, passIdx = 0) { - console.assert(passIdx < this._passes.length, 'illegal pass index.'); - this._props[passIdx][name] = val; - const pass = this._passes[passIdx]; - const handle = pass.getHandleFromName(name); - pass.setUniform(handle, val); + public setProperty(name: string, val: any, passIdx?: number) { + if (passIdx === undefined) { // set property for all applicable passes + const passes = this._passes; + const len = passes.length; + for (let i = 0; i < len; i++) { + const handle = passes[i].getHandleFromName(name); + if (handle === undefined) { continue; } + passes[i].setUniform(handle, val); + this._props[i][name] = val; + } + } else { + if (CC_DEBUG && passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } + const pass = this._passes[passIdx]; + const handle = pass.getHandleFromName(name); + if (CC_DEBUG && handle === undefined) { console.warn(`illegal property name: ${name}.`); return; } + pass.setUniform(handle, val); + this._props[passIdx][name] = val; + } } - public setTexture(name: string, val: TextureBase, passIdx = 0) { - console.assert(passIdx < this._passes.length, 'illegal pass index.'); - this._textures[passIdx][name] = val; - const pass = this._passes[passIdx]; - const binding = pass.getBindingFromName(name); - pass.bindTextureView(binding, val._texView); + public setTexture(name: string, val: TextureBase, passIdx?: number) { + if (passIdx === undefined) { // set property for all applicable passes + const passes = this._passes; + const len = passes.length; + for (let i = 0; i < len; i++) { + const binding = passes[i].getBindingFromName(name); + if (binding < 0) { continue; } + passes[i].bindTextureView(binding, val._texView); + this._textures[i][name] = val; + } + } else { + if (CC_DEBUG && passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } + const pass = this._passes[passIdx]; + const binding = pass.getBindingFromName(name); + if (CC_DEBUG && binding < 0) { console.warn(`illegal texture name: ${name}.`); return; } + pass.bindTextureView(binding, val._texView); + this._textures[passIdx][name] = val; + } } public copy(mat: Material) { @@ -146,12 +170,14 @@ export class Material extends Asset { if (!props) { props = this._props[i] = {}; } for (const p of Object.keys(props)) { const handle = pass.getHandleFromName(p); + if (handle === undefined) { continue; } pass.setUniform(handle, props[p]); } let textures = this._textures[i]; if (!textures) { textures = this._textures[i] = {}; } for (const t of Object.keys(textures)) { const binding = pass.getBindingFromName(t); + if (binding === undefined) { continue; } pass.bindTextureView(binding, textures[t]._texView); } }); diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js index 961ad8488e..84ab6a847b 100644 --- a/cocos/3d/framework/animation-component.js +++ b/cocos/3d/framework/animation-component.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import Component from '../../components/CCComponent'; +import { Component } from '../../components/component'; import { ccclass, property, executionOrder, menu, executeInEditMode } from '../../core/data/class-decorator'; import Enum from '../../core/value-types/enum'; import AnimationClip, { AnimationTarget, AnimationSampler } from '../assets/animation-clip'; diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index a0ce36302e..60439c4e26 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -28,7 +28,7 @@ import { toRadian } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; import { Color, Enum, Rect } from '../../core/value-types'; import enums from '../../renderer/enums'; -import Component from '../../components/CCComponent'; +import { Component } from '../../components/component'; /** * @typedef {import('../../core/value-types/index').Color} Color diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js index 44da06f009..d504b8713f 100644 --- a/cocos/3d/framework/light-component.js +++ b/cocos/3d/framework/light-component.js @@ -27,7 +27,7 @@ import renderer from '../../renderer/index'; import { Color, Enum } from '../../core/value-types'; import { toRadian } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; -import Component from '../../components/CCComponent'; +import { Component } from '../../components/component'; /** * !#en The light source type diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.js index e0cf121e42..0c574ed451 100644 --- a/cocos/3d/framework/particle/particle-system-component.js +++ b/cocos/3d/framework/particle/particle-system-component.js @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import Component from '../../../components/CCComponent'; +import { Component } from '../../../components/component'; import { vec3, vec2, mat4, quat, randomRangeInt, pseudoRandom } from '../../../core/vmath'; import registry from '../../misc/registry'; import Gradient, { ColorKey, AlphaKey } from './animator/gradient'; diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts index ee6baedf2a..9f833163c5 100644 --- a/cocos/3d/framework/physics/body.ts +++ b/cocos/3d/framework/physics/body.ts @@ -117,7 +117,7 @@ export class PhysicsBody { return this._cannonBody.force; } - public applyForce(force: cc.Vec3, position?: cc.Vec3) { + public applyForce(force: Vec3, position?: Vec3) { if (!position) { position = this._cannonBody.position; } @@ -295,7 +295,7 @@ export class PhysicsBody { this.pullTransform(); } - private _pullScale(scale: cc.Vec3) { + private _pullScale(scale: Vec3) { let shapeUpdated = false; this._shapes.forEach((shape) => { let calcShapeOffset = false; @@ -359,9 +359,9 @@ export class PhysicsBody { export class PhysicsShape { // public __debugNodeName: string = ''; - private _scale: cc.Vec3 = new cc.Vec3(1.0, 1.0, 1.0); + private _scale: Vec3 = new Vec3(1.0, 1.0, 1.0); - private _center: cc.Vec3 = new cc.Vec3(0, 0, 0); + private _center: Vec3 = new Vec3(0, 0, 0); public _centerChanged = true; @@ -395,12 +395,12 @@ export class PhysicsShape { } export class PhysicsBoxShape extends PhysicsShape { - private _size: cc.Vec3; + private _size: Vec3; constructor(size: Vec3) { super(new CANNON.Box(new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2))); - this._size = new cc.Vec3(size.x, size.y, size.z); + this._size = new Vec3(size.x, size.y, size.z); } public get size() { diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts index 5cfadbeb12..dcde768e92 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -1,5 +1,5 @@ -import Component from '../../../../components/CCComponent'; +import { Component } from '../../../../components/component'; import { ccclass } from '../../../../core/data/class-decorator'; import { PhysicsBody } from '../body'; diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts index 6a034ebb8a..754e1b2697 100644 --- a/cocos/3d/framework/physics/world.ts +++ b/cocos/3d/framework/physics/world.ts @@ -1,4 +1,5 @@ import CANNON from 'cannon'; +import { Vec3 } from '../../../core/value-types'; import { PhysicsMaterial } from '../../assets/physics/material'; import { DataFlow, PhysicsBody, PhysicsShape } from './body'; import { ContactMaterial } from './contact-material'; @@ -45,8 +46,8 @@ export class PhysicsWorld { constructor() { this._defaultMaterial = new PhysicsMaterial(); - this._defaultContactMaterial = new ContactMaterial( - this._defaultMaterial, this._defaultMaterial, { friction: 0.3, restitution: 0.0 }); + // @ts-ignore + this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, { friction: 0.3, restitution: 0.0 }); this._cannonWorld = new CANNON.World(); setWrap(this._cannonWorld, this); @@ -82,7 +83,7 @@ export class PhysicsWorld { * Ray cast, and return information of the closest hit. * @return True if any body was hit. */ - public raycastClosest(from: cc.Vec3, to: cc.Vec3, options: RaycastOptions, result: RaycastResult): boolean { + public raycastClosest(from: Vec3, to: Vec3, options: RaycastOptions, result: RaycastResult): boolean { const hit = (this._cannonWorld as any).raycastClosest(from, to, toCannonRaycastOptions(options), result._cannonResult); return hit; } @@ -91,7 +92,7 @@ export class PhysicsWorld { * Ray cast, and stop at the first result. Note that the order is random - but the method is fast. * @return True if any body was hit. */ - public raycastAny(from: cc.Vec3, to: cc.Vec3, options: RaycastOptions, result: RaycastResult): boolean { + public raycastAny(from: Vec3, to: Vec3, options: RaycastOptions, result: RaycastResult): boolean { const hit = (this._cannonWorld as any).raycastAny(from, to, toCannonRaycastOptions(options), result._cannonResult); return hit; } @@ -100,7 +101,7 @@ export class PhysicsWorld { * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument. * @return True if any body was hit. */ - public raycastAll(from: cc.Vec3, to: cc.Vec3, options: RaycastOptions, callback: (result: RaycastResult) => void): boolean { + public raycastAll(from: Vec3, to: Vec3, options: RaycastOptions, callback: (result: RaycastResult) => void): boolean { return (this._cannonWorld as any).raycastAll(from, to, toCannonRaycastOptions(options), (cannonResult: CANNON.RaycastResult) => { const result = new RaycastResult(); result._cannonResult = cannonResult; diff --git a/cocos/3d/framework/renderSystemActor.js b/cocos/3d/framework/renderSystemActor.js index eaf5ed65d5..a570b57e9b 100644 --- a/cocos/3d/framework/renderSystemActor.js +++ b/cocos/3d/framework/renderSystemActor.js @@ -1,4 +1,4 @@ -import Component from '../../components/CCComponent'; +import { Component } from '../../components/component'; class RenderSystemActorListener { constructor() { diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.js index ac57a08e2d..533c00e606 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.js @@ -1,7 +1,7 @@ //@ts-check import { _decorator } from '../../core/data/index'; import { Material } from "../assets/material"; -import Component from "../../components/CCComponent"; +import { Component } from "../../components/component"; const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js index f8201add98..5dbd8e40ab 100644 --- a/cocos/3d/framework/skybox-component.js +++ b/cocos/3d/framework/skybox-component.js @@ -28,7 +28,7 @@ import { box } from '../primitive/index'; import { Material } from '../assets/material'; import { ccclass, property, menu, executeInEditMode } from '../../core/data/class-decorator'; import TextureCube from '../assets/texture-cube'; -import Component from '../../components/CCComponent'; +import { Component } from '../../components/component'; /** * !#en The Skybox Component diff --git a/cocos/animation/CCAnimation.js b/cocos/animation/CCAnimation.js index 587ed549d5..6314d5d338 100644 --- a/cocos/animation/CCAnimation.js +++ b/cocos/animation/CCAnimation.js @@ -62,7 +62,7 @@ var EventType = cc.Enum({ /** * !#en Emit when pause animation * !#zh 暂停播放时触发 - * @property {String} PAUSE + * @property {String} PAUSE * @static */ PAUSE: 'pause', @@ -91,7 +91,7 @@ var EventType = cc.Enum({ /** * !#en The animation component is used to play back animations. - * + * * Animation provide several events to register: * - play : Emit when begin playing animation * - stop : Emit when stop playing animation @@ -101,7 +101,7 @@ var EventType = cc.Enum({ * - finished : Emit when finish playing animation * * !#zh Animation 组件用于播放动画。 - * + * * Animation 提供了一系列可注册的事件: * - play : 开始播放时 * - stop : 停止播放时 @@ -109,14 +109,14 @@ var EventType = cc.Enum({ * - resume : 恢复播放时 * - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时 * - finished : 动画播放完成时 - * + * * @class Animation * @extends Component * @uses EventTarget */ var Animation = cc.Class({ name: 'cc.Animation', - extends: require('./CCComponent'), + extends: require('./component'), mixins: [EventTarget], editor: CC_EDITOR && { @@ -305,7 +305,7 @@ var Animation = cc.Class({ if (state) { this.enabled = true; - + var animator = this._animator; if (animator.isPlaying && state.isPlaying) { if (state.isPaused) { @@ -488,7 +488,7 @@ var Animation = cc.Class({ }, /** - * !#en + * !#en * Remove clip from the animation list. This will remove the clip and any animation states based on it. * If there are animation states depand on the clip are playing or clip is defaultClip, it will not delete the clip. * But if force is true, then will always remove the clip and any animation states based on it. If clip is defaultClip, defaultClip will be reset to null @@ -521,7 +521,7 @@ var Animation = cc.Class({ else { if (!CC_TEST) cc.warnID(3902); return; - } + } } if (state && state.isPlaying) { @@ -537,7 +537,7 @@ var Animation = cc.Class({ }); if (state) { - delete this._nameToState[state.name]; + delete this._nameToState[state.name]; } }, @@ -565,7 +565,7 @@ var Animation = cc.Class({ /** - * !#en + * !#en * Register animation event callback. * The event arguments will provide the AnimationState which emit the event. * When play an animation, will auto register the event callback to the AnimationState, and unregister the event callback from the AnimationState when animation stopped. @@ -577,7 +577,7 @@ var Animation = cc.Class({ * @param {String} type - A string representing the event type to listen for. * @param {Function} callback - The callback that will be invoked when the event is dispatched. * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {cc.AnimationState} state + * @param {cc.AnimationState} state * @param {Object} [target] - The target (this object) to invoke the callback, can be null * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. @@ -592,7 +592,7 @@ var Animation = cc.Class({ * onPlay: function (type, state) { * // callback * } - * + * * // register event to all animation * animation.on('play', this.onPlay, this); */ @@ -658,7 +658,7 @@ var Animation = cc.Class({ _createStates: function() { this._nameToState = js.createMap(true); - + // create animation states var state = null; var defaultClipState = false; diff --git a/cocos/audio/CCAudioSource.js b/cocos/audio/CCAudioSource.js index ff525592d9..fd49ab31bd 100644 --- a/cocos/audio/CCAudioSource.js +++ b/cocos/audio/CCAudioSource.js @@ -24,9 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -const misc = require('../utils/misc'); -const Component = require('./CCComponent'); -const AudioClip = require('../assets/CCAudioClip'); +import * as misc from '../core/utils/misc'; +import { Component } from './component'; +import AudioClip from '../assets/CCAudioClip'; /** * !#en Audio Source. diff --git a/cocos/camera/CCCamera.js b/cocos/camera/CCCamera.js index b08129c519..bafb0e903f 100644 --- a/cocos/camera/CCCamera.js +++ b/cocos/camera/CCCamera.js @@ -29,7 +29,7 @@ import AffineTrans from '../core/value-types/affine-transform'; import mat4 from '../core/vmath/mat4'; import vec2 from '../core/vmath/vec2'; import vec3 from '../core/vmath/vec3'; -import Component from '../components/CCComponent'; +import { Component } from '../components/component'; // TODO fix import from renderer import { Camera as Renderer_Camera} from '../renderer/scene/camera'; import {default as Renderer_View} from '../renderer/core/view'; diff --git a/cocos/components/CCCanvas.js b/cocos/components/CCCanvas.js index c74ac8df5f..6fe2a72a16 100644 --- a/cocos/components/CCCanvas.js +++ b/cocos/components/CCCanvas.js @@ -25,7 +25,7 @@ ****************************************************************************/ import Camera from '../camera/CCCamera'; -import Component from './CCComponent'; +import { Component } from './component'; import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from '../core/data/class-decorator'; /** @@ -240,4 +240,4 @@ export default class Canvas extends Component { } } -cc.Canvas = Canvas; \ No newline at end of file +cc.Canvas = Canvas; diff --git a/cocos/components/WXSubContextView.js b/cocos/components/WXSubContextView.js index 183c617e2a..48e9e393fa 100644 --- a/cocos/components/WXSubContextView.js +++ b/cocos/components/WXSubContextView.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -const Component = require('./CCComponent'); +import { Component } from './component'; const ImageAsset = require('../assets/image-asset'); let WXSubContextView; @@ -37,7 +37,7 @@ if (!CC_EDITOR && !CC_WECHATGAME) { else { /** * !#en WXSubContextView is a view component which controls open data context viewport in Wechat game platform.
- * The component's node size decide the viewport of the sub context content in main context, + * The component's node size decide the viewport of the sub context content in main context, * the entire sub context texture will be scaled to the node's bounding box area.
* This component provides multiple important features:
* 1. Sub context could use its own resolution size and policy.
@@ -45,7 +45,7 @@ else { * 3. Resolution of sub context content could be increased.
* 4. User touch input is transformed to the correct viewport.
* 5. Texture update is handled by this component. User don't need to worry.
- * One important thing to be noted, whenever the node's bounding box change, + * One important thing to be noted, whenever the node's bounding box change, * you need to manually reset the viewport of sub context using updateSubContextViewport. * !#zh WXSubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。
* 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。
@@ -134,4 +134,4 @@ else { } -cc.WXSubContextView = module.exports = WXSubContextView; \ No newline at end of file +cc.WXSubContextView = module.exports = WXSubContextView; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts new file mode 100644 index 0000000000..7e20bc95d2 --- /dev/null +++ b/cocos/components/component.d.ts @@ -0,0 +1,48 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { CCObject } from '../core/data/object'; +import { getClassName, value } from '../core/utils/js'; +import IDGenerator from '../core/utils/id-generator'; +import { ccclass, property } from '../core/data/class-decorator'; +import Node from '../scene-graph/node'; + +export class Component extends CCObject { + node: Node; + uuid: string; + enabled: boolean; + enabledInHierarchy: boolean; + + addComponent(typeOrClassName: Function | string): Component; + getComponent(typeOrClassName: Function | string): Component; + getComponents(typeOrClassName: Function | string): Component[]; + getComponentInChildren(typeOrClassName: Function | string): Component; + getComponentsInChildren(typeOrClassName: Function | string): Component[]; + schedule(callback: Function, interval: number, repeat: number, delay: number): void; + scheduleOnce(callback: Function, delay: number): void; + unschedule(callback: Function): void; + unscheduleAllCallbacks(): void; +} diff --git a/cocos/components/CCComponent.js b/cocos/components/component.js similarity index 99% rename from cocos/components/CCComponent.js rename to cocos/components/component.js index 247597ee19..af3bba71c3 100644 --- a/cocos/components/CCComponent.js +++ b/cocos/components/component.js @@ -722,4 +722,4 @@ value(Component, '_registerEditorProps', function (cls, props) { Component.prototype.__scriptUuid = ''; cc.Component = Component; -export default Component; +export { Component }; diff --git a/cocos/components/index.js b/cocos/components/index.js index 8f1c1b533c..ff64fef8c1 100644 --- a/cocos/components/index.js +++ b/cocos/components/index.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -export {default as Component} from './CCComponent'; +export {Component} from './component'; export {default as EventHandler} from './CCComponentEventHandler'; export {default as MissingScript} from './missing-script'; -export {default as Canvas} from './CCCanvas'; \ No newline at end of file +export {default as Canvas} from './CCCanvas'; diff --git a/cocos/components/missing-script.js b/cocos/components/missing-script.js index 6dae7bc849..4ee8d0ceab 100644 --- a/cocos/components/missing-script.js +++ b/cocos/components/missing-script.js @@ -26,7 +26,7 @@ import {_getClassById} from '../core/utils/js'; import {BUILTIN_CLASSID_RE} from '../core/utils/misc'; -import Component from './CCComponent'; +import { Component } from './component'; import {ccclass, property, inspector} from '../core/data/class-decorator'; /* @@ -48,7 +48,7 @@ class MissingClass { @ccclass('cc.MissingScript') @inspector('packages://inspector/inspectors/comps/missing-script.js') export default class MissingScript extends Component { - + //_scriptUuid: { // get: function () { // var id = this._$erialized.__type__; diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index da11d4ae31..f8a7476758 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -33,7 +33,7 @@ export class WebGLStateCache { this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); this.viewport = { left: 0.0, top: 0.0, width: 0.0, height: 0.0, minDepth: 0.0, maxDepth: 0.0}; - this.scissorRect = { left: 0.0, top: 0.0, width: 0.0, height: 0.0}; + this.scissorRect = { x: 0.0, y: 0.0, width: 0.0, height: 0.0}; this.rs = new GFXRasterizerState; this.dss = new GFXDepthStencilState; this.bs = new GFXBlendState; diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index 4b3b0a75c8..d84722e3aa 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -70,6 +70,7 @@ export class TestMaterialStage extends RenderStage { } public render(view: RenderView) { + // @ts-ignore if (!this._material.inited) { // material this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js @@ -79,6 +80,7 @@ export class TestMaterialStage extends RenderStage { const colorHandle = pass.getHandleFromName('u_color'); pass.setUniform(colorHandle, cc.color('#ffffff')); pass.update(); + // @ts-ignore this._material.inited = true; } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 98f35c97e7..a5850a1d9f 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -157,7 +157,9 @@ export class Pass { } public getBindingFromName(name: string) { - return parseHandle(this.getHandleFromName(name))[0]; + const handle = this.getHandleFromName(name); + if (handle === undefined) { return -1; } + return parseHandle(handle)[0]; } public setUniform(handle: number, value: any) { diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 74bb8197f9..14c3e7d6d6 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -7,7 +7,7 @@ import { vec3 } from '../../core/vmath'; import { Vec3 } from '../../core/value-types'; import { Node } from '../../scene-graph'; import InputAssembler from '../core/input-assembler'; -import Effect from '../core/effect'; +import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; @@ -133,8 +133,8 @@ export default class Model { setEffect(effect: Effect) { if (effect) { this._effect = effect; - this._defines = effect.extractDefines(Object.create(null)); - this._dependencies = effect.extractDependencies(Object.create(null)); + // this._defines = effect.extractDefines(Object.create(null)); + // this._dependencies = effect.extractDependencies(Object.create(null)); } else { this._effect = null; this._defines = Object.create(null); @@ -167,7 +167,7 @@ export default class Model { out.node = this._node; out.ia = this._inputAssembler; out.effect = this._effect; - out.defines = this._effect ? this._effect.extractDefines(this._defines) : this._defines; - out.dependencies = this._effect ? this._effect.extractDependencies(this._dependencies) : this._dependencies; + // out.defines = this._effect ? this._effect.extractDefines(this._defines) : this._defines; + // out.dependencies = this._effect ? this._effect.extractDependencies(this._dependencies) : this._dependencies; } } diff --git a/globals.d.ts b/globals.d.ts new file mode 100644 index 0000000000..dc9638e18b --- /dev/null +++ b/globals.d.ts @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +declare const CC_BUILD: boolean; +declare const CC_TEST: boolean; +declare const CC_EDITOR: boolean; +declare const CC_PREVIEW: boolean; +declare const CC_DEV: boolean; +declare const CC_DEBUG: boolean; +declare const CC_JSB: boolean; +declare const CC_WECHATGAME_SUB: boolean; +declare const CC_WECHATGAME: boolean; +declare const CC_QQPLAY: boolean; +declare const CC_RUNTIME: boolean; +declare const CC_SUPPORT_JIT: boolean; + +declare const cc: any; From dcdef09d6f21e1153e584a082f977cff2aa55fdc Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 16:46:06 +0800 Subject: [PATCH 051/267] add GFXDevice.copyFramebufferToBuffer() --- cocos/core/vmath/quat.js | 11 +++++++++ cocos/gfx/device.ts | 1 + cocos/gfx/framebuffer.ts | 4 ++++ cocos/gfx/webgl/webgl-device.ts | 34 +++++++++++++++++++++++++++- cocos/gfx/webgl/webgl-framebuffer.ts | 4 ++-- 5 files changed, 51 insertions(+), 3 deletions(-) diff --git a/cocos/core/vmath/quat.js b/cocos/core/vmath/quat.js index ef6fc7bd51..d5694a765c 100644 --- a/cocos/core/vmath/quat.js +++ b/cocos/core/vmath/quat.js @@ -733,6 +733,17 @@ class quat { return out; } + /** + * Convert a quaternion back to euler angle (in degrees). + * + * @param {vec3} out - Euler angle stored as a vec3 + * @param {number} q - the quaternion to be converted + * @returns {vec3} out. + */ + static toAxisX(out) { + + } + /** * Convert a quaternion back to euler angle (in degrees). * diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index e4a1fa5c62..1c97dc83bf 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -47,6 +47,7 @@ export abstract class GFXDevice { public abstract copyBufferToTexture(buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); public abstract copyImageSourceToTexture(source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyFramebufferToBuffer(srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]); public get canvas(): HTMLCanvasElement { return this._canvas; diff --git a/cocos/gfx/framebuffer.ts b/cocos/gfx/framebuffer.ts index 580d033097..adb1751031 100644 --- a/cocos/gfx/framebuffer.ts +++ b/cocos/gfx/framebuffer.ts @@ -30,6 +30,10 @@ export abstract class GFXFramebuffer { return this._depthStencilView; } + public get isOffscreen(): boolean { + return this._isOffscreen; + } + protected _device: GFXDevice; protected _renderPass: GFXRenderPass | null = null; protected _colorViews: GFXTextureView[] = []; diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index b418eec772..306b1f346e 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -31,7 +31,7 @@ import { WebGLGFXFramebuffer } from './webgl-framebuffer'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { GFXWindow, GFXWindowInfo } from '../window'; import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat, GFXBufferTextureCopy, GFXMemoryUsageBit, GFXTextureLayout, GFXTextureSubres, GFXRect, GFXFormatInfos } from '../define'; +import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat, GFXBufferTextureCopy, GFXMemoryUsageBit, GFXTextureLayout, GFXTextureSubres, GFXRect, GFXFormatInfos, GFXFormatSize } from '../define'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; const WebGLPrimitives: GLenum[] = [ @@ -408,6 +408,38 @@ export class WebGLGFXDevice extends GFXDevice { } } + public copyFramebufferToBuffer(srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]) { + let gl = this._webGLRC; + let gpuFramebuffer = (srcFramebuffer).gpuFramebuffer; + + let curFBO = this.stateCache.glFramebuffer; + + if (this.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); + this.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer; + } + + let view = new Uint8Array(dstBuffer); + + for (let r = 0; r < regions.length; ++r) { + let region = regions[r]; + let buffOffset = region.buffOffset; + region.buffTexHeight * region.buffStride; + + let w = region.texExtent.width; + let h = region.texExtent.height; + + let memSize = GFXFormatSize(GFXFormat.RGBA8, w, h, 1); + let data = view.subarray(buffOffset, buffOffset + memSize); + + gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, data); + } + + if (this.stateCache.glFramebuffer !== curFBO) { + gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, curFBO); + this.stateCache.glFramebuffer = curFBO; + } + } + public get gl(): WebGLRenderingContext { return this._webGLRC; } diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index 9ea8bd8d62..2ca91f0ef0 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -38,8 +38,8 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { return this._device; } - public get gpuFramebuffer() : WebGLGPUFramebuffer | null { - return this._gpuFramebuffer; + public get gpuFramebuffer() : WebGLGPUFramebuffer { + return this._gpuFramebuffer; } private _gpuFramebuffer : WebGLGPUFramebuffer | null = null; From d76d93fae157c970199ba20a1c80d3bf0f6d01cd Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 17:14:17 +0800 Subject: [PATCH 052/267] merge origin --- .gitignore | 1 + cocos/3d/assets/index.js | 11 +++++------ cocos/3d/assets/physics/material.ts | 1 + cocos/3d/framework/physics/world.ts | 7 ++++--- cocos/core/index.js | 10 +++++----- cocos/renderer/scene/camera.ts | 6 +++--- index.js | 1 + 7 files changed, 20 insertions(+), 17 deletions(-) diff --git a/.gitignore b/.gitignore index a3c739bd6c..780af89deb 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,6 @@ node_modules /package /tools/jsdoc_toolkit/jsdoc_toolkit-2.4.0 /.project +/dist npm-debug.log DebugInfos.json diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js index 4c54325731..6df8f5d3d3 100644 --- a/cocos/3d/assets/index.js +++ b/cocos/3d/assets/index.js @@ -24,11 +24,11 @@ ****************************************************************************/ export { default as AnimationClip } from "./animation-clip"; -export { default as AudioClip } from "./audio-clip"; -export { default as DomAudioClip } from "./dom-audio-clip"; -export { default as BitmapFont } from "./bitmap-font"; -export { default as EffectAsset } from "./effect-asset"; -export { default as Material } from "./material"; +export { AudioClip } from "./audio-clip"; +export { DOMAudioClip } from "./dom-audio-clip"; +export { BitmapFont } from "./bitmap-font"; +export { EffectAsset } from "./effect-asset"; +export { Material } from "./material"; export { default as Mesh } from "./mesh"; export { default as OpentypeFont } from "./opentype-font"; export { default as Skeleton } from "./skeleton"; @@ -37,4 +37,3 @@ export { default as WebAudioClip } from "./web-audio-clip"; export { default as WxGameAudioClip } from "./wx-game-audio-clip"; export { PhysicsMaterial } from './physics/material'; -cc.PhysicsMaterial = PhysicsMaterial; diff --git a/cocos/3d/assets/physics/material.ts b/cocos/3d/assets/physics/material.ts index 56f62d39ef..6e7d6293f2 100644 --- a/cocos/3d/assets/physics/material.ts +++ b/cocos/3d/assets/physics/material.ts @@ -52,3 +52,4 @@ export class PhysicsMaterial extends Asset { return this._cannonMaterial; } } +cc.PhysicsMaterial = PhysicsMaterial; diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts index f15ec1e9fe..20d1a7aec3 100644 --- a/cocos/3d/framework/physics/world.ts +++ b/cocos/3d/framework/physics/world.ts @@ -1,5 +1,4 @@ import CANNON from 'cannon'; -import { Vec3 } from '../../../core/value-types'; import { PhysicsMaterial } from '../../assets/physics/material'; import { DataFlow, PhysicsBody, PhysicsShape } from './body'; import { ContactMaterial } from './contact-material'; @@ -47,8 +46,10 @@ export class PhysicsWorld { constructor() { this._defaultMaterial = new PhysicsMaterial(); - // @ts-ignore - this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, { friction: 0.3, restitution: 0.0 }); + const mtl = new PhysicsMaterial(); + mtl.friction = 0.3; + mtl.restitution = 0; + this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, mtl); this._cannonWorld = new CANNON.World(); setWrap(this._cannonWorld, this); diff --git a/cocos/core/index.js b/cocos/core/index.js index cbcf9b802a..3456282aa4 100644 --- a/cocos/core/index.js +++ b/cocos/core/index.js @@ -34,10 +34,10 @@ export * from './event'; export * from './platform'; export * from './value-types'; // Cause error: -// export * from './CCGame'; -import './CCGame'; -export * from './CCScheduler'; +// export * from './game'; +import './game'; +export * from './scheduler'; // Cause error: -// export * from './CCDirector'; -import './CCDirector'; +// export * from './director'; +import './director'; export { vmath }; diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 5d1f7a4bdf..f973928401 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -103,15 +103,15 @@ export class Camera { return this._farClip; } - public get matView(): number { + public get matView(): mat4 { return this._matView; } - public get matProj(): number { + public get matProj(): mat4 { return this._matProj; } - public get matViewProj(): number { + public get matViewProj(): mat4 { return this._matViewProj; } diff --git a/index.js b/index.js index c68709743e..bb1f4cb2c0 100644 --- a/index.js +++ b/index.js @@ -38,5 +38,6 @@ export * from './cocos/load-pipeline'; export * from './cocos/components'; export * from './cocos/animation'; export * from './cocos/3d'; +export * from './cocos/gfx'; // export default cc; From 6af7b4cf7409b1af2dcf033d31ffff12506391c1 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Tue, 8 Jan 2019 17:27:06 +0800 Subject: [PATCH 053/267] adapt model --- cocos/3d/assets/mesh.js | 111 ++++++++++++++++----- cocos/3d/framework/model-component.js | 11 +-- cocos/renderer/scene/model.ts | 42 ++++++-- cocos/renderer/utils.js | 134 ++++++++++++++++++-------- 4 files changed, 220 insertions(+), 78 deletions(-) diff --git a/cocos/3d/assets/mesh.js b/cocos/3d/assets/mesh.js index c57d65fb44..16f7f76ddf 100644 --- a/cocos/3d/assets/mesh.js +++ b/cocos/3d/assets/mesh.js @@ -24,7 +24,7 @@ ****************************************************************************/ // @ts-check -import { _decorator } from "../../core/data/index"; +import { _decorator } from "../../core/data"; const { ccclass, property } = _decorator; import { Asset } from "../../assets/asset"; import gfx from "../../renderer/gfx"; @@ -32,6 +32,7 @@ import { enums as gfxEnums } from "../../renderer/gfx/enums"; import InputAssembler from "../../renderer/core/input-assembler"; import BufferRange from "./utils/buffer-range"; import { Vec3 } from "../../core/value-types"; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../../gfx/define"; /** * A vertex bundle describes a serials of vertex attributes. @@ -132,7 +133,7 @@ export default class Mesh extends Asset { super(); /** - * @type {InputAssembler[]} + * @type {GFXInputAssembler[]} */ this._subMeshes = null; @@ -165,12 +166,19 @@ export default class Mesh extends Asset { } const buffer = this._getBuffer(); const vertexBuffers = this._vertexBundles.map((vertexBundle) => { - return new gfx.VertexBuffer( - cc.game._renderContext, - new gfx.VertexFormat(vertexBundle._formats), - gfx.USAGE_STATIC, - new Uint8Array(buffer, vertexBundle._data._offset, vertexBundle._data._length), - vertexBundle._verticesCount); + let vb = cc.director.root.device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vertexBundle._data._length, + stride: vertexBundle._data._length / vertexBundle._verticesCount, + }); + + if (!vb) { + return null; + } + + vb.update(new Uint8Array(buffer, vertexBundle._data._offset, vertexBundle._data._length)); + return vb; }); this._subMeshes = this._primitives.map((primitive) => { if (primitive._vertexBundelIndices.length === 0) { @@ -180,15 +188,74 @@ export default class Mesh extends Asset { // Currently, an IA only has one vertex buffer. const vertexBuffer = vertexBuffers[primitive._vertexBundelIndices[0]]; - const indexBuffer = new gfx.IndexBuffer( - cc.game._renderContext, - primitive._indexUnit, - gfx.USAGE_STATIC, - new DataView(buffer, primitive._indices._offset, primitive._indices._length), - primitive._indices._length / this._getIndexUnitSize(primitive._indexUnit) - ); - return new InputAssembler(vertexBuffer, indexBuffer); + let ib = cc.director.root.device.createBuffer({ + usage: GFXBufferUsageBit.INDEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: primitive._indices._length, + stride: this._getIndexUnitSize(primitive._indexUnit), + }); + + if (!ib) { + return null; + } + + ib.update(new DataView(buffer, primitive._indices._offset, primitive._indices._length)); + + let attributes = []; + + let vertexBundle = this._vertexBundles[primitive._vertexBundelIndices[0]]; + for (let i = 0; i < vertexBundle._formats.length; i++) { + let gfxAttr = {}; + gfxAttr.name = vertexBundle._formats[i].name; + let gfxFormat; + switch (vertexBundle._formats[i].num) { + case 1: + gfxFormat = 'R'; + break; + case 2: + gfxFormat = 'RG'; + break; + case 3: + gfxFormat = 'RGB'; + break; + case 4: + gfxFormat = 'RGBA'; + break; + } + switch (vertexBundle._formats[i].type) { + case gfx.ATTR_TYPE_INT8: + gfxFormat += '8I'; + break; + case gfx.ATTR_TYPE_UINT8: + gfxFormat += '8UI'; + break; + case gfx.ATTR_TYPE_INT16: + gfxFormat += '16I'; + break; + case gfx.ATTR_TYPE_UINT16: + gfxFormat += '16UI'; + break; + case gfx.ATTR_TYPE_INT32: + gfxFormat += '32I'; + break; + case gfx.ATTR_TYPE_UINT32: + gfxFormat += '32UI'; + break; + case gfx.ATTR_TYPE_FLOAT32: + gfxFormat += '32F'; + break; + } + gfxAttr.format = GFXFormat[gfxFormat]; + gfxAttr.normalize = vertexBundle._formats[i].normalize; + attributes.push(gfxAttr); + } + + return cc.director.root.device.createInputAssembler({ + attributes, + vertexBuffers: [vertexBuffer], + indexBuffer: ib, + }); }); } @@ -259,12 +326,12 @@ export default class Mesh extends Asset { _getIndexUnitSize(indexUnit) { switch (indexUnit) { - case gfxEnums.INDEX_FMT_UINT8: - return 1; - case gfxEnums.INDEX_FMT_UINT16: - return 2; - case gfxEnums.INDEX_FMT_UINT32: - return 3; + case gfxEnums.INDEX_FMT_UINT8: + return 1; + case gfxEnums.INDEX_FMT_UINT16: + return 2; + case gfxEnums.INDEX_FMT_UINT32: + return 3; } return 1; } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 65da63e0d4..c8a4310491 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -207,13 +207,8 @@ export default class ModelComponent extends RenderableComponent { this._updateModelParams(); - if (this.enabled) { - for (let i = 0; i < oldModels.length; ++i) { - this.scene.removeModel(oldModels[i]); - } - for (let i = 0; i < this._models.length; ++i) { - this.scene.addModel(this._models[i]); - } + for (let i = 0; i < oldModels.length; ++i) { + this._renderScene.destroyModel(oldModels[i]); } } @@ -252,7 +247,7 @@ export default class ModelComponent extends RenderableComponent { * @param {Material} material */ _updateModelMaterial(model, material) { - model.setEffect((material ? material.effect : null) || this._getBuiltinMaterial().effect); + model.setMaterial(material ? material : this._getBuiltinMaterial()); } _updateCastShadow() { diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 74bb8197f9..d7d77d4c27 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,7 +1,7 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { aabb } from '../../3d/geom-utils'; -import { GFXInputAttribute } from '../../gfx/input-assembler'; -import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXInputAttribute, GFXInputAssembler } from '../../gfx/input-assembler'; +import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit, GFXCommandBufferType } from '../../gfx/define'; import { RenderScene } from './render-scene'; import { vec3 } from '../../core/vmath'; import { Vec3 } from '../../core/value-types'; @@ -10,6 +10,7 @@ import InputAssembler from '../core/input-assembler'; import Effect from '../core/effect'; import { Pass } from '../core/pass'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { Material } from '../../3d/assets/material'; /** * A representation of a model @@ -23,7 +24,7 @@ export default class Model { _poolID: number; _isEnable: boolean; _node: Node; - _inputAssembler: InputAssembler; + _inputAssembler: GFXInputAssembler | null; _effect: Effect | null; _defines: Object; _dependencies: Object; @@ -33,7 +34,7 @@ export default class Model { _castShadow: boolean; _boundingShape: aabb; _bsModelSpace: aabb; - _passes: Pass[]; + _material: Material | null; _cmdBuffers: GFXCommandBuffer[]; /** * Setup a default empty model @@ -56,7 +57,7 @@ export default class Model { this._userKey = -1; this._castShadow = false; this._boundingShape = null; - this._passes = new Array(); + this._material = null; this._cmdBuffers = new Array(); } @@ -122,7 +123,7 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - setInputAssembler(ia: InputAssembler) { + setInputAssembler(ia: GFXInputAssembler) { this._inputAssembler = ia; } @@ -142,6 +143,33 @@ export default class Model { } } + setMaterial(material: Material) { + this._material = material; + for (let i = 0; i < this._material.passes.length; i++) { + this.recordCommandBuffer(i); + } + } + + recordCommandBuffer(index: number) { + let pass = this._material.passes[index]; + let cmdBufferInfo = { + allocator: cc.director.root.device.commandAllocator, + type: GFXCommandBufferType.SECONDARY, + }; + if (this._cmdBuffers[index] == null) + this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); + else { + this._cmdBuffers[index].destroy(); + this._cmdBuffers[index].initialize(cmdBufferInfo); + } + this._cmdBuffers[index].begin(); + this._cmdBuffers[index].bindPipelineState(pass.pipelineState); + this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); + this._cmdBuffers[index].bindInputAssembler(this._inputAssembler); + this._cmdBuffers[index].draw(this._inputAssembler); + this._cmdBuffers[index].end(); + } + /** * Set the user key * @param {number} key @@ -151,7 +179,7 @@ export default class Model { } getPassList(): Pass[] { - return this._passes; + return (this._material).passes; } getCmdBufferList(): GFXCommandBuffer[] { diff --git a/cocos/renderer/utils.js b/cocos/renderer/utils.js index 38b7e48345..8ec7b9c712 100644 --- a/cocos/renderer/utils.js +++ b/cocos/renderer/utils.js @@ -2,64 +2,116 @@ import gfx from './gfx'; import InputAssembler from './core/input-assembler'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from '../gfx/define'; /** * @param {gfx.Device} device * @param {Object} data */ export function createIA(device, data) { - if (!data.positions) { - console.error('The data must have positions field'); - return null; - } + if (!data.positions) { + console.error('The data must have positions field'); + return null; + } - let verts = []; - let vcount = data.positions.length / 3; + let verts = []; + let vcount = data.positions.length / 3; - for (let i = 0; i < vcount; ++i) { - verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]); + for (let i = 0; i < vcount; ++i) { + verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]); + if (data.normals) { + verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]); + } + if (data.uvs) { + verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]); + } + if (data.colors) { + verts.push(data.colors[3 * i], data.uvs[3 * i + 1], data.colors[3 * i + 2]); + } + } + + let vfmt = []; + vfmt.push({ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); if (data.normals) { - verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]); + vfmt.push({ name: gfx.ATTR_NORMAL, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); } if (data.uvs) { - verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]); + vfmt.push({ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }); } if (data.colors) { - verts.push(data.colors[3 * i], data.uvs[3 * i + 1], data.colors[3 * i + 2]); + vfmt.push({ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); } - } - let vfmt = []; - vfmt.push({ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - if (data.normals) { - vfmt.push({ name: gfx.ATTR_NORMAL, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - } - if (data.uvs) { - vfmt.push({ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }); - } - if (data.colors) { - vfmt.push({ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); - } + let vb = cc.director.root.device.createBuffer({ + usage: GFXBufferUsageBit.VERTEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: verts.length * 4, + stride: verts.length * 4 / vcount, + }); - let vb = new gfx.VertexBuffer( - device, - new gfx.VertexFormat(vfmt), - gfx.USAGE_STATIC, - new Float32Array(verts), - vcount - ); + vb.update(new Float32Array(verts)); - let ib = null; - if (data.indices) { - ib = new gfx.IndexBuffer( - device, - gfx.INDEX_FMT_UINT16, - gfx.USAGE_STATIC, - new Uint16Array(data.indices), - data.indices.length - ); - } + let ib = cc.director.root.device.createBuffer({ + usage: GFXBufferUsageBit.INDEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: data.indices.length * 2, + stride: 2, + }); - return new InputAssembler(vb, ib, data.primitiveType); + ib.update(new Uint16Array(data.indices)); + + let attributes = []; + + for (let i = 0; i < vfmt.length; i++) { + let gfxAttr = {}; + gfxAttr.name = vfmt[i].name; + let gfxFormat; + switch (vfmt[i].num) { + case 1: + gfxFormat = 'R'; + break; + case 2: + gfxFormat = 'RG'; + break; + case 3: + gfxFormat = 'RGB'; + break; + case 4: + gfxFormat = 'RGBA'; + break; + } + switch (vfmt[i].type) { + case gfx.ATTR_TYPE_INT8: + gfxFormat += '8I'; + break; + case gfx.ATTR_TYPE_UINT8: + gfxFormat += '8UI'; + break; + case gfx.ATTR_TYPE_INT16: + gfxFormat += '16I'; + break; + case gfx.ATTR_TYPE_UINT16: + gfxFormat += '16UI'; + break; + case gfx.ATTR_TYPE_INT32: + gfxFormat += '32I'; + break; + case gfx.ATTR_TYPE_UINT32: + gfxFormat += '32UI'; + break; + case gfx.ATTR_TYPE_FLOAT32: + gfxFormat += '32F'; + break; + } + gfxAttr.format = GFXFormat[gfxFormat]; + gfxAttr.normalize = vfmt[i].normalize; + attributes.push(gfxAttr); + } + + return cc.director.root.device.createInputAssembler({ + attributes, + vertexBuffers: [vb], + indexBuffer: ib, + }); } From 31987ffefdab77c1440ffdf931294b329d5183b1 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 17:28:14 +0800 Subject: [PATCH 054/267] merge latest --- cocos/core/vmath/quat.js | 834 ---------------------------------- cocos/core/vmath/vec3.js | 934 --------------------------------------- cocos/core/vmath/vec3.ts | 7 + 3 files changed, 7 insertions(+), 1768 deletions(-) delete mode 100644 cocos/core/vmath/quat.js delete mode 100644 cocos/core/vmath/vec3.js diff --git a/cocos/core/vmath/quat.js b/cocos/core/vmath/quat.js deleted file mode 100644 index d5694a765c..0000000000 --- a/cocos/core/vmath/quat.js +++ /dev/null @@ -1,834 +0,0 @@ -import vec3 from './vec3'; -import vec4 from './vec4'; -import mat3 from './mat3'; -import { toDegree } from './utils'; - -let halfToRad = 0.5 * Math.PI / 180.0; - -/** - * Mathematical quaternion. - * - * A quaternion is a hypercomplex number represented by w + xi + yj + zk, where - * x, y, z and w are real numbers(called here its components), and i, j, and k are the fundamental quaternion units. - */ -class quat { - /** - * Creates a quaternion, with components specified separately. - * - * @param {number} x - Value assigned to x component. - * @param {number} y - Value assigned to y component. - * @param {number} z - Value assigned to z component. - * @param {number} w - Value assigned to w component. - */ - constructor(x = 0, y = 0, z = 0, w = 1) { - /** - * The x component. - * @type {number} - * */ - this.x = x; - - /** - * The y component. - * @type {number} - * */ - this.y = y; - - /** - * The z component. - * @type {number} - * */ - this.z = z; - - /** - * The w component. - * @type {number} - * */ - this.w = w; - } - - /** - * Creates a quaternion, with components specified separately. - * - * @param {number} x - Value assigned to x component. - * @param {number} y - Value assigned to y component. - * @param {number} z - Value assigned to z component. - * @param {number} w - Value assigned to w component. - * @return {quat} The newly created quaternion. - */ - static create(x = 0, y = 0, z = 0, w = 1) { - return new quat(x, y, z, w); - } - - /** - * Clone a quaternion. - * - * @param {quat} a - Quaternion to clone. - * @returns {quat} The newly created quaternion. - */ - static clone(a) { - return new quat(a.x, a.y, a.z, a.w); - } - - /** - * Copy content of a quaternion into another. - * - * @param {quat} out - Quaternion to modified. - * @param {quat} a - The specified quaternion. - * @returns {quat} out. - */ - static copy(out, a) { - return vec4.copy(out, a); - } - - /** - * Sets the components of a quaternion to the given values. - * - * @param {quat} out - The quaternion to modified. - * @param {Number} x - Value set to x component. - * @param {Number} y - Value set to y component. - * @param {Number} z - Value set to z component. - * @param {Number} w - Value set to w component. - * @returns {quat} out. - */ - static set(out, x, y, z, w) { - out.x = x; - out.y = y; - out.z = z; - out.w = w; - return out; - } - - /** - * Sets a quaternion as identity quaternion. - * - * @param {quat} out - Quaternion to set. - * @returns {quat} out. - */ - static identity(out) { - out.x = 0; - out.y = 0; - out.z = 0; - out.w = 1; - return out; - } - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param {quat} out - Quaternion to set. - * @param {vec3} a - The initial vector. - * @param {vec3} b - The destination vector. - * @returns {quat} out. - */ - static rotationTo(out, a, b) { - let rotationToIIFE = (function () { - let tmpvec3 = vec3.create(0, 0, 0); - let xUnitVec3 = vec3.create(1, 0, 0); - let yUnitVec3 = vec3.create(0, 1, 0); - - return function (out, a, b) { - let dot = vec3.dot(a, b); - if (dot < -0.999999) { - vec3.cross(tmpvec3, xUnitVec3, a); - if (vec3.magnitude(tmpvec3) < 0.000001) { - vec3.cross(tmpvec3, yUnitVec3, a); - } - vec3.normalize(tmpvec3, tmpvec3); - quat.fromAxisAngle(out, tmpvec3, Math.PI); - return out; - } else if (dot > 0.999999) { - out.x = 0; - out.y = 0; - out.z = 0; - out.w = 1; - return out; - } else { - vec3.cross(tmpvec3, a, b); - out.x = tmpvec3.x; - out.y = tmpvec3.y; - out.z = tmpvec3.z; - out.w = 1 + dot; - return quat.normalize(out, out); - } - }; - })(); - - return rotationToIIFE(out, a, b); - } - - /** - * Gets the rotation axis and angle for a given - * quaternion. If a quaternion is created with - * fromAxisAngle, this method will return the same - * values as provided in the original parameter list - * OR functionally equivalent values. - * Example: The quaternion formed by axis [0, 0, 1] and - * angle -90 is the same as the quaternion formed by - * [0, 0, 1] and 270. This method favors the latter. - * @param {vec3} out_axis - Vector to store the rotation axis. - * @param {quat} q - Quaternion to be decomposed. - * @return {Number} - Angle, in radians, of the rotation. - */ - static getAxisAngle(out_axis, q) { - let rad = Math.acos(q.w) * 2.0; - let s = Math.sin(rad / 2.0); - if (s != 0.0) { - out_axis.x = q.x / s; - out_axis.y = q.y / s; - out_axis.z = q.z / s; - } else { - // If s is zero, return any axis (no rotation - axis does not matter) - out_axis.x = 1; - out_axis.y = 0; - out_axis.z = 0; - } - return rad; - } - - /** - * Multiply two quaternions. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - The first operand. - * @param {quat} b - The second operand. - * @returns {quat} out. - */ - static multiply(out, a, b) { - let ax = a.x, ay = a.y, az = a.z, aw = a.w, - bx = b.x, by = b.y, bz = b.z, bw = b.w; - - out.x = ax * bw + aw * bx + ay * bz - az * by; - out.y = ay * bw + aw * by + az * bx - ax * bz; - out.z = az * bw + aw * bz + ax * by - ay * bx; - out.w = aw * bw - ax * bx - ay * by - az * bz; - return out; - } - - /** - * Alias of {@link quat.multiply}. - */ - static mul(out, a, b) { - return quat.multiply(out, a, b); - } - - /** - * Scales a quaternion with a number. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to scale. - * @param {quat} b - The scale number. - * @returns {quat} out. - * */ - static scale(out, a, b) { - out.x = a.x * b; - out.y = a.y * b; - out.z = a.z * b; - out.w = a.w * b; - return out; - } - - /** - * Rotates a quaternion by the given angle about the X axis. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to rotate. - * @param {number} rad - Angle (in radians) to rotate. - * @returns {quat} out. - */ - static rotateX(out, a, rad) { - rad *= 0.5; - - let ax = a.x, ay = a.y, az = a.z, aw = a.w, - bx = Math.sin(rad), bw = Math.cos(rad); - - out.x = ax * bw + aw * bx; - out.y = ay * bw + az * bx; - out.z = az * bw - ay * bx; - out.w = aw * bw - ax * bx; - return out; - } - - /** - * Rotates a quaternion by the given angle about the Y axis. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to rotate. - * @param {number} rad - Angle (in radians) to rotate. - * @returns {quat} out. - */ - static rotateY(out, a, rad) { - rad *= 0.5; - - let ax = a.x, ay = a.y, az = a.z, aw = a.w, - by = Math.sin(rad), bw = Math.cos(rad); - - out.x = ax * bw - az * by; - out.y = ay * bw + aw * by; - out.z = az * bw + ax * by; - out.w = aw * bw - ay * by; - return out; - } - - /** - * Rotates a quaternion by the given angle about the Z axis. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to rotate. - * @param {number} rad - Angle (in radians) to rotate. - * @returns {quat} out. - */ - static rotateZ(out, a, rad) { - rad *= 0.5; - - let ax = a.x, ay = a.y, az = a.z, aw = a.w, - bz = Math.sin(rad), bw = Math.cos(rad); - - out.x = ax * bw + ay * bz; - out.y = ay * bw - ax * bz; - out.z = az * bw + aw * bz; - out.w = aw * bw - az * bz; - return out; - } - - /** - * Rotates a quaternion by the given angle about a world space axis. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} rot - Quaternion to rotate. - * @param {vec3} axis - The axis around which to rotate in world space. - * @param {number} rad - Angle (in radians) to rotate. - * @returns {quat} out. - */ - static rotateAround(out, rot, axis, rad) { - let rotateAroundIIFE = (function () { - let v3_tmp = vec3.create(0, 0, 0); - let q_tmp = quat.create(); - - return function (out, rot, axis, rad) { - // get inv-axis (local to rot) - quat.invert(q_tmp, rot); - vec3.transformQuat(v3_tmp, axis, q_tmp); - // rotate by inv-axis - quat.fromAxisAngle(q_tmp, v3_tmp, rad); - quat.mul(out, rot, q_tmp); - - return out; - }; - })(); - return rotateAroundIIFE(out, rot, axis, rad); - } - - /** - * Rotates a quaternion by the given angle about a local space axis. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} rot - Quaternion to rotate. - * @param {vec3} axis - The axis around which to rotate in local space. - * @param {number} rad - Angle (in radians) to rotate. - * @returns {quat} out. - */ - static rotateAroundLocal(out, rot, axis, rad) { - let rotateAroundLocalIIFE = (function () { - let q_tmp = quat.create(); - - return function (out, rot, axis, rad) { - quat.fromAxisAngle(q_tmp, axis, rad); - quat.mul(out, rot, q_tmp); - - return out; - }; - })(); - - return rotateAroundLocalIIFE(out, rot, axis, rad); - } - - /** - * Calculates the W component of a quaternion from the X, Y, and Z components. - * Assumes that quaternion is 1 unit in length. - * Any existing W component will be ignored. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to calculate W. - * @returns {quat} out. - */ - static calculateW(out, a) { - let x = a.x, y = a.y, z = a.z; - - out.x = x; - out.y = y; - out.z = z; - out.w = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); - return out; - } - - /** - * Calculates the dot product of two quaternions. - * - * @param {quat} a - The first operand. - * @param {quat} b - The second operand. - * @returns {Number} - The dot product of a and b. - */ - static dot(a, b) { - return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; - } - - /** - * Performs a linear interpolation between two quaternions. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - The first operand. - * @param {quat} b - The second operand. - * @param {Number} t - The interpolation coefficient. - * @returns {quat} out. - */ - static lerp(out, a, b, t) { - let ax = a.x, - ay = a.y, - az = a.z, - aw = a.w; - out.x = ax + t * (b.x - ax); - out.y = ay + t * (b.y - ay); - out.z = az + t * (b.z - az); - out.w = aw + t * (b.w - aw); - return out; - } - - /** - * Performs a spherical linear interpolation between two quaternions. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - The first operand. - * @param {quat} b - The second operand. - * @param {Number} t - The interpolation coefficient. - * @returns {quat} out. - */ - static slerp(out, a, b, t) { - // benchmarks: - // http://jsperf.com/quaternion-slerp-implementations - - let ax = a.x, ay = a.y, az = a.z, aw = a.w, - bx = b.x, by = b.y, bz = b.z, bw = b.w; - - let omega, cosom, sinom, scale0, scale1; - - // calc cosine - cosom = ax * bx + ay * by + az * bz + aw * bw; - // adjust signs (if necessary) - if (cosom < 0.0) { - cosom = -cosom; - bx = -bx; - by = -by; - bz = -bz; - bw = -bw; - } - // calculate coefficients - if ((1.0 - cosom) > 0.000001) { - // standard case (slerp) - omega = Math.acos(cosom); - sinom = Math.sin(omega); - scale0 = Math.sin((1.0 - t) * omega) / sinom; - scale1 = Math.sin(t * omega) / sinom; - } else { - // "from" and "to" quaternions are very close - // ... so we can do a linear interpolation - scale0 = 1.0 - t; - scale1 = t; - } - // calculate final values - out.x = scale0 * ax + scale1 * bx; - out.y = scale0 * ay + scale1 * by; - out.z = scale0 * az + scale1 * bz; - out.w = scale0 * aw + scale1 * bw; - - return out; - } - - /** - * Performs a spherical linear interpolation with two control points. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - The first operand. - * @param {quat} b - The second operand. - * @param {quat} c - The third operand. - * @param {quat} d - The fourth operand. - * @param {Number} t - The interpolation coefficient. - * @returns {quat} out - */ - static sqlerp(out, a, b, c, d, t) { - let sqlerpIIFE = (function () { - let temp1 = quat.create(); - let temp2 = quat.create(); - - return function (out, a, b, c, d, t) { - quat.slerp(temp1, a, d, t); - quat.slerp(temp2, b, c, t); - quat.slerp(out, temp1, temp2, 2 * t * (1 - t)); - - return out; - }; - }()); - return sqlerpIIFE(out, a, b, c, d, t); - } - - /** - * Calculates the inverse of a quaternion. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to calculate inverse of. - * @returns {quat} out. - */ - static invert(out, a) { - let a0 = a.x, a1 = a.y, a2 = a.z, a3 = a.w; - let dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; - let invDot = dot ? 1.0 / dot : 0; - - // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 - - out.x = -a0 * invDot; - out.y = -a1 * invDot; - out.z = -a2 * invDot; - out.w = a3 * invDot; - return out; - } - - /** - * Calculates the conjugate of a quaternion. - * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to calculate conjugate of. - * @returns {quat} out. - */ - static conjugate(out, a) { - out.x = -a.x; - out.y = -a.y; - out.z = -a.z; - out.w = a.w; - return out; - } - - /** - * Calculates the length of a quaternion. - * - * @param {quat} a - The quaternion. - * @returns {Number} Length of the quaternion. - */ - static magnitude(a) { - let x = a.x, - y = a.y, - z = a.z, - w = a.w; - return Math.sqrt(x * x + y * y + z * z + w * w); - } - - /** - *Alias of {@link quat.magnitude}. - */ - static mag(a) { - return quat.magnitude(a); - } - - /** - * Calculates the squared length of a quaternion. - * - * @param {quat} a - The quaternion. - * @returns {Number} Squared length of the quaternion. - */ - static squaredMagnitude(a) { - let x = a.x, - y = a.y, - z = a.z, - w = a.w; - return x * x + y * y + z * z + w * w; - } - - /** - *Alias of {@link quat.squaredMagnitude} - */ - static sqrMag(a) { - return quat.squaredMagnitude(a); - } - - /** - * Normalizes a quaternion. - * - * @param {quat} out - Quaternion to store result. - * @param {quat} a - Quaternion to normalize. - * @returns {quat} out. - * @function - */ - static normalize(out, a) { - let x = a.x, - y = a.y, - z = a.z, - w = a.w; - let len = x * x + y * y + z * z + w * w; - if (len > 0) { - len = 1 / Math.sqrt(len); - out.x = x * len; - out.y = y * len; - out.z = z * len; - out.w = w * len; - } - return out; - } - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {quat} out - Quaternion to store result. - * @param {vec3} xAxis - Vector representing the local "right" direction. - * @param {vec3} yAxis - Vector representing the local "up" direction. - * @param {vec3} zAxis - Vector representing the viewing direction. - * @returns {quat} out. - */ - static fromAxes(out, xAxis, yAxis, zAxis) { - let fromAxesIIFE = (function () { - let matr = mat3.create(); - - return function (out, xAxis, yAxis, zAxis) { - mat3.set(matr, - xAxis.x, xAxis.y, xAxis.z, - yAxis.x, yAxis.y, yAxis.z, - zAxis.x, zAxis.y, zAxis.z - ); - return quat.normalize(out, quat.fromMat3(out, matr)); - }; - })(); - return fromAxesIIFE(out, xAxis, yAxis, zAxis); - } - - /** - * Calculates a quaternion from view direction and up direction - * - * @param {quat} out - Quaternion to store result. - * @param {vec3} view - View direction (must be normalized). - * @param {vec3} [up] - Up direction, default is (0,1,0) (must be normalized). - * - * @returns {quat} out. - */ - static fromViewUp(out, view, up) { - let fromViewUpIIFE = (function () { - let matr = mat3.create(); - - return function (out, view, up) { - mat3.fromViewUp(matr, view, up); - if (!matr) { - return null; - } - - return quat.normalize(out, quat.fromMat3(out, matr)); - }; - })(); - return fromViewUpIIFE(out, view, up); - } - - /** - * Sets a quaternion from the given angle and rotation axis, - * then returns it. - * - * @param {quat} out - Quaternion to store result. - * @param {vec3} axis - The axis around which to rotate. - * @param {Number} rad - The angle in radians. - * @returns {quat} out. - **/ - static fromAxisAngle(out, axis, rad) { - rad = rad * 0.5; - let s = Math.sin(rad); - out.x = s * axis.x; - out.y = s * axis.y; - out.z = s * axis.z; - out.w = Math.cos(rad); - return out; - } - - /** - * Creates a quaternion from the given 3x3 rotation matrix. - * - * NOTE: The resultant quaternion is not normalized, so you should be sure - * to re-normalize the quaternion yourself where necessary. - * - * @param {quat} out - Quaternion to store result. - * @param {mat3} m - The rotation matrix. - * @returns {quat} out. - * @function - */ - static fromMat3(out, m) { - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - - let m00 = m.m00, m01 = m.m03, m02 = m.m06, - m10 = m.m01, m11 = m.m04, m12 = m.m07, - m20 = m.m02, m21 = m.m05, m22 = m.m08; - - let trace = m00 + m11 + m22; - - if (trace > 0) { - let s = 0.5 / Math.sqrt(trace + 1.0); - - out.w = 0.25 / s; - out.x = (m21 - m12) * s; - out.y = (m02 - m20) * s; - out.z = (m10 - m01) * s; - - } else if ((m00 > m11) && (m00 > m22)) { - let s = 2.0 * Math.sqrt(1.0 + m00 - m11 - m22); - - out.w = (m21 - m12) / s; - out.x = 0.25 * s; - out.y = (m01 + m10) / s; - out.z = (m02 + m20) / s; - - } else if (m11 > m22) { - let s = 2.0 * Math.sqrt(1.0 + m11 - m00 - m22); - - out.w = (m02 - m20) / s; - out.x = (m01 + m10) / s; - out.y = 0.25 * s; - out.z = (m12 + m21) / s; - - } else { - let s = 2.0 * Math.sqrt(1.0 + m22 - m00 - m11); - - out.w = (m10 - m01) / s; - out.x = (m02 + m20) / s; - out.y = (m12 + m21) / s; - out.z = 0.25 * s; - } - - return out; - } - - /** - * Creates a quaternion from the given euler angle x, y, z. - * - * @param {quat} out - Quaternion to store result. - * @param {number} x - Angle to rotate around X axis in degrees. - * @param {number} y - Angle to rotate around Y axis in degrees. - * @param {number} z - Angle to rotate around Z axis in degrees. - * @returns {quat} out. - * @function - */ - static fromEuler(out, x, y, z) { - x *= halfToRad; - y *= halfToRad; - z *= halfToRad; - - let sx = Math.sin(x); - let cx = Math.cos(x); - let sy = Math.sin(y); - let cy = Math.cos(y); - let sz = Math.sin(z); - let cz = Math.cos(z); - - out.x = sx * cy * cz + cx * sy * sz; - out.y = cx * sy * cz + sx * cy * sz; - out.z = cx * cy * sz - sx * sy * cz; - out.w = cx * cy * cz - sx * sy * sz; - - return out; - } - - /** - * Convert a quaternion back to euler angle (in degrees). - * - * @param {vec3} out - Euler angle stored as a vec3 - * @param {number} q - the quaternion to be converted - * @returns {vec3} out. - */ - static toAxisX(out) { - - } - - /** - * Convert a quaternion back to euler angle (in degrees). - * - * @param {vec3} out - Euler angle stored as a vec3 - * @param {number} q - the quaternion to be converted - * @returns {vec3} out. - */ - static toEuler(out, q) { - let x = q.x, y = q.y, z = q.z, w = q.w; - let heading, attitude, bank; - let test = x * y + z * w; - if (test > 0.499999) { // singularity at north pole - heading = 2 * Math.atan2(x,w); - attitude = Math.PI/2; - bank = 0; - } - if (test < -0.499999) { // singularity at south pole - heading = -2 * Math.atan2(x,w); - attitude = - Math.PI/2; - bank = 0; - } - if(isNaN(heading)){ - let sqx = x*x; - let sqy = y*y; - let sqz = z*z; - heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // heading - attitude = Math.asin(2*test); // attitude - bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank - } - - // Keep angles [0..360]. - out.y = toDegree(heading) + (heading < 0 ? 360 : 0); - out.z = toDegree(attitude) + (attitude < 0 ? 360 : 0); - out.x = toDegree(bank) + (bank < 0 ? 360 : 0); - - return out; - } - - /** - * Returns string representation of a quaternion. - * - * @param {quat} a - The quaternion. - * @returns {String} - String representation of this quaternion. - */ - static str(a) { - return `quat(${a.x}, ${a.y}, ${a.z}, ${a.w})`; - } - - /** - * Store components of a quaternion into array. - * - * @param {Array} out - Array to store result. - * @param {quat} q - The quaternion. - * @returns {Array} out. - */ - static array(out, q) { - out[0] = q.x; - out[1] = q.y; - out[2] = q.z; - out[3] = q.w; - - return out; - } - - /** - * Returns whether the specified quaternions are equal. (Compared using ===) - * - * @param {quat} a - The first quaternion. - * @param {quat} b - The second quaternion. - * @returns {Boolean} True if the quaternions are equal, false otherwise. - */ - static exactEquals(a, b) { - return vec4.exactEquals(a, b); - } - - /** - * Returns whether the specified quaternions are approximately equal. - * - * @param {quat} a The first quaternion. - * @param {quat} b The second quaternion. - * @returns {Boolean} True if the quaternions are approximately equal, false otherwise. - */ - static equals(a, b) { - return vec4.equals(a, b); - } -} - -export default quat; diff --git a/cocos/core/vmath/vec3.js b/cocos/core/vmath/vec3.js deleted file mode 100644 index 2b5bcd5383..0000000000 --- a/cocos/core/vmath/vec3.js +++ /dev/null @@ -1,934 +0,0 @@ -import { EPSILON, random } from './utils'; - -/** - * Mathematical 3-dimensional vector. - * - * x, y, z is alias of the first, second, third component of vector, respectively. - */ -class vec3 { - /** - * Creates a vector, with components specified separately. - * - * @param {number} x - Value assigned to x component. - * @param {number} y - Value assigned to y component. - * @param {number} z - Value assigned to z component. - */ - constructor(x = 0, y = 0, z = 0) { - /** - * The x component. - * @type {number} - * */ - this.x = x; - - /** - * The y component. - * @type {number} - * */ - this.y = y; - - /** - * The z component. - * @type {number} - * */ - this.z = z; - } - - static UNIT_X = { x: 1, y: 0, z: 0 }; - static UNIT_Y = { x: 0, y: 1, z: 0 }; - static UNIT_Z = { x: 0, y: 0, z: 1 }; - static ZERO = { x: 0, y: 0, z: 0 }; - static ONE = { x: 1, y: 1, z: 1 }; - static NEG_ONE = { x: -1, y: -1, z: -1 }; - - /** - * Creates a vector, with components specified separately. - * - * @param {number} x - Value assigned to x component. - * @param {number} y - Value assigned to y component. - * @param {number} z - Value assigned to z component. - * @return {vec3} The newly created vector. - */ - static create(x = 0, y = 0, z = 0) { - return new vec3(x, y, z); - } - - /** - * Creates a zero vector. - * - * @return {vec3} The newly created vector. - */ - static zero(out) { - out.x = 0; - out.y = 0; - out.z = 0; - return out; - } - - /** - * Clone a vector. - * - * @param {vec3} a - Vector to clone. - * @returns {vec3} The newly created vector. - */ - static clone(a) { - return new vec3(a.x, a.y, a.z); - } - - /** - * Copy content of a vector into another. - * - * @param {vec3} out - The vector to modified. - * @param {vec3} a - The specified vector. - * @returns {vec3} out. - */ - static copy(out, a) { - out.x = a.x; - out.y = a.y; - out.z = a.z; - return out; - } - - /** - * Sets the components of a vector to the given values. - * - * @param {vec3} out - The vector to modified. - * @param {Number} x - Value set to x component. - * @param {Number} y - Value set to y component. - * @param {Number} z - Value set to z component. - * @returns {vec3} out. - */ - static set(out, x, y, z) { - out.x = x; - out.y = y; - out.z = z; - return out; - } - - /** - * Add two vectors. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static add(out, a, b) { - out.x = a.x + b.x; - out.y = a.y + b.y; - out.z = a.z + b.z; - return out; - } - - /** - * Subtract two vectors. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static subtract(out, a, b) { - out.x = a.x - b.x; - out.y = a.y - b.y; - out.z = a.z - b.z; - return out; - } - - /** - * Alias of {@link vec3.subtract}. - */ - static sub(out, a, b) { - return vec3.subtract(out, a, b); - } - - /** - * Performs multiply on each component of two vectors respectively. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static multiply(out, a, b) { - out.x = a.x * b.x; - out.y = a.y * b.y; - out.z = a.z * b.z; - return out; - } - - /** - * Alias of {@link vec3.multiply}. - */ - static mul(out, a, b) { - return vec3.multiply(out, a, b); - } - - /** - * Performs division on each component of two vectors respectively. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static divide(out, a, b) { - out.x = a.x / b.x; - out.y = a.y / b.y; - out.z = a.z / b.z; - return out; - } - - /** - * Alias of {@link vec3.divide}. - */ - static div(out, a, b) { - return vec3.divide(out, a, b); - } - - /** - * Performs Math.ceil on each component of a vector. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to perform operation. - * @returns {vec3} out. - */ - static ceil(out, a) { - out.x = Math.ceil(a.x); - out.y = Math.ceil(a.y); - out.z = Math.ceil(a.z); - return out; - } - - /** - * Performs Math.floor on each component of a vector. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to perform operation. - * @returns {vec3} out. - */ - static floor(out, a) { - out.x = Math.floor(a.x); - out.y = Math.floor(a.y); - out.z = Math.floor(a.z); - return out; - } - - /** - * Performs Math.min on each component of two vectors respectively. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static min(out, a, b) { - out.x = Math.min(a.x, b.x); - out.y = Math.min(a.y, b.y); - out.z = Math.min(a.z, b.z); - return out; - } - - /** - * Performs Math.min on each component of two vectors respectively. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static max(out, a, b) { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.z = Math.max(a.z, b.z); - return out; - } - - /** - * Performs Math.round on each component of a vector. - * - * It doesn't matter that any amount of these parameters refer to same vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to perform operation. - * @returns {vec3} out. - */ - static round(out, a) { - out.x = Math.round(a.x); - out.y = Math.round(a.y); - out.z = Math.round(a.z); - return out; - } - - /** - * Scales a vector with a number. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to scale. - * @param {number} b - The scale number. - * @returns {vec3} out. - * */ - static scale(out, a, b) { - out.x = a.x * b; - out.y = a.y * b; - out.z = a.z * b; - return out; - } - - /** - * Add two vectors after scaling the second operand by a number. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @param {number} scale - The scale number before adding. - * @returns {vec3} out. - */ - static scaleAndAdd(out, a, b, scale) { - out.x = a.x + (b.x * scale); - out.y = a.y + (b.y * scale); - out.z = a.z + (b.z * scale); - return out; - } - - /** - * Calculates the euclidian distance between two vectors. - * - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {number} Distance between a and b. - */ - static distance(a, b) { - let x = b.x - a.x, - y = b.y - a.y, - z = b.z - a.z; - return Math.sqrt(x * x + y * y + z * z); - } - - /** - * Alias of {@link vec3.distance}. - */ - static dist(a, b) { - return vec3.distance(a, b); - } - - /** - * Calculates the squared euclidian distance between two vectors. - * - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {number} Squared distance between a and b. - */ - static squaredDistance(a, b) { - let x = b.x - a.x, - y = b.y - a.y, - z = b.z - a.z; - return x * x + y * y + z * z; - } - - /** - * Alias of {@link vec3.squaredDistance}. - */ - static sqrDist(a, b) { - return vec3.squaredDistance(a, b); - } - - /** - * Calculates the length of a vector. - * - * @param {vec3} a - The vector. - * @returns {Number} Length of the vector. - */ - static magnitude(a) { - let x = a.x, - y = a.y, - z = a.z; - return Math.sqrt(x * x + y * y + z * z); - } - - /** - *Alias of {@link vec3.magnitude}. - */ - static mag(a) { - return vec3.magnitude(a); - } - - /** - * Calculates the squared length of a vector. - * - * @param {vec3} a - The vector. - * @returns {Number} Squared length of the vector. - */ - static squaredMagnitude(a) { - let x = a.x, - y = a.y, - z = a.z; - return x * x + y * y + z * z; - } - - /** - *Alias of {@link vec3.squaredMagnitude} - */ - static sqrMag(a) { - return vec3.squaredMagnitude(a); - } - - /** - * Negates each component of a vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to negate. - * @returns {vec3} out. - */ - static negate(out, a) { - out.x = -a.x; - out.y = -a.y; - out.z = -a.z; - return out; - } - - /** - * Inverts the components of a vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to invert. - * @returns {vec3} out. - */ - static inverse(out, a) { - out.x = 1.0 / a.x; - out.y = 1.0 / a.y; - out.z = 1.0 / a.z; - return out; - } - - /** - * Safely inverts the components of a vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to invert. - * @returns {vec3} out. - */ - static inverseSafe(out, a) { - let x = a.x, - y = a.y, - z = a.z; - - if (Math.abs(x) < EPSILON) { - out.x = 0; - } else { - out.x = 1.0 / x; - } - - if (Math.abs(y) < EPSILON) { - out.y = 0; - } else { - out.y = 1.0 / y; - } - - if (Math.abs(z) < EPSILON) { - out.z = 0; - } else { - out.z = 1.0 / z; - } - - return out; - } - - /** - * Normalizes a vector. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to normalize. - * @returns {vec3} out. - */ - static normalize(out, a) { - let x = a.x, - y = a.y, - z = a.z; - - let len = x * x + y * y + z * z; - if (len > 0) { - //TODO: evaluate use of glm_invsqrt here? - len = 1 / Math.sqrt(len); - out.x = x * len; - out.y = y * len; - out.z = z * len; - } - return out; - } - - /** - * Calculates the dot product of two vectors. - * - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {Number} Dot product of a and b. - */ - static dot(a, b) { - return a.x * b.x + a.y * b.y + a.z * b.z; - } - - /** - * Calculates the cross product of two vectors. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {vec3} out. - */ - static cross(out, a, b) { - let ax = a.x, ay = a.y, az = a.z, - bx = b.x, by = b.y, bz = b.z; - - out.x = ay * bz - az * by; - out.y = az * bx - ax * bz; - out.z = ax * by - ay * bx; - return out; - } - - /** - * Performs a linear interpolation between two vectors. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @param {Number} t - The interpolation coefficient. - * @returns {vec3} out. - */ - static lerp(out, a, b, t) { - let ax = a.x, - ay = a.y, - az = a.z; - out.x = ax + t * (b.x - ax); - out.y = ay + t * (b.y - ay); - out.z = az + t * (b.z - az); - return out; - } - - /** - * Performs a hermite interpolation with two control points. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @param {vec3} c - The third operand. - * @param {vec3} d - The fourth operand. - * @param {Number} t - The interpolation coefficient. - * @returns {vec3} out. - */ - static hermite(out, a, b, c, d, t) { - let factorTimes2 = t * t, - factor1 = factorTimes2 * (2 * t - 3) + 1, - factor2 = factorTimes2 * (t - 2) + t, - factor3 = factorTimes2 * (t - 1), - factor4 = factorTimes2 * (3 - 2 * t); - - out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; - out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; - out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; - - return out; - } - - /** - * Performs a bezier interpolation with two control points. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @param {vec3} c - The third operand. - * @param {vec3} d - The fourth operand. - * @param {Number} t - The interpolation coefficient. - * @returns {vec3} out. - */ - static bezier(out, a, b, c, d, t) { - let inverseFactor = 1 - t, - inverseFactorTimesTwo = inverseFactor * inverseFactor, - factorTimes2 = t * t, - factor1 = inverseFactorTimesTwo * inverseFactor, - factor2 = 3 * t * inverseFactorTimesTwo, - factor3 = 3 * factorTimes2 * inverseFactor, - factor4 = factorTimes2 * t; - - out.x = a.x * factor1 + b.x * factor2 + c.x * factor3 + d.x * factor4; - out.y = a.y * factor1 + b.y * factor2 + c.y * factor3 + d.y * factor4; - out.z = a.z * factor1 + b.z * factor2 + c.z * factor3 + d.z * factor4; - - return out; - } - - /** - * Generates a random vector uniformly distributed on a sphere centered at the origin. - * - * @param {vec3} out - Vector to store result. - * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit length vector will be returned. - * @returns {vec3} out. - */ - static random(out, scale) { - scale = scale || 1.0; - - let phi = random() * 2.0 * Math.PI; - let theta = Math.acos(random() * 2 - 1); - - out.x = Math.sin(theta) * Math.cos(phi) * scale; - out.y = Math.sin(theta) * Math.sin(phi) * scale; - out.z = Math.cos(theta) * scale; - return out; - } - - /** - * Transforms a point vector with a 4x4 matrix, - * i.e. 4th vector component is implicitly '1'. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to transform. - * @param {mat4} m - The matrix. - * @returns {vec3} out. - */ - static transformMat4(out, a, m) { - let x = a.x, y = a.y, z = a.z, - rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15; - rhw = rhw ? 1 / rhw : 1; - out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw; - out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw; - out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw; - return out; - } - - /** - * Transforms a normal vector with a 4x4 matrix, - * i.e. 4th vector component is implicitly '0'. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to transform. - * @param {mat4} m - The matrix. - * @returns {vec3} out. - */ - static transformMat4Normal(out, a, m) { - let x = a.x, y = a.y, z = a.z, - rhw = m.m03 * x + m.m07 * y + m.m11 * z; - rhw = rhw ? 1 / rhw : 1; - out.x = (m.m00 * x + m.m04 * y + m.m08 * z) * rhw; - out.y = (m.m01 * x + m.m05 * y + m.m09 * z) * rhw; - out.z = (m.m02 * x + m.m06 * y + m.m10 * z) * rhw; - return out; - } - - /** - * Transforms a vector with a 3x3 matrix. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to transform. - * @param {mat3} m - The matrix. - * @returns {vec3} out. - */ - static transformMat3(out, a, m) { - let x = a.x, y = a.y, z = a.z; - out.x = x * m.m00 + y * m.m03 + z * m.m06; - out.y = x * m.m01 + y * m.m04 + z * m.m07; - out.z = x * m.m02 + y * m.m05 + z * m.m08; - return out; - } - - /** - * Transforms a vector with a quaternion. - * - * @param {vec3} out - Vector to store result. - * @param {vec3} a - Vector to transform. - * @param {quat} q - The quaternion. - * @returns {vec3} out. - */ - static transformQuat(out, a, q) { - // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations - - let x = a.x, y = a.y, z = a.z; - let qx = q.x, qy = q.y, qz = q.z, qw = q.w; - - // calculate quat * vec - let ix = qw * x + qy * z - qz * y; - let iy = qw * y + qz * x - qx * z; - let iz = qw * z + qx * y - qy * x; - let iw = -qx * x - qy * y - qz * z; - - // calculate result * inverse quat - out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; - out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; - out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; - return out; - } - - /** - * Rotates a 3D vector around the x-axis. - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The point to rotate. - * @param {vec3} b - The origin of the rotation. - * @param {Number} c - The angle of rotation. - * @returns {vec3} out. - */ - static rotateX(out, a, b, c) { - // Translate point to the origin - let px = a.x - b.x; - let py = a.y - b.y; - let pz = a.z - b.z; - - //perform rotation - let rx = px; - let ry = py * Math.cos(c) - pz * Math.sin(c); - let rz = py * Math.sin(c) + pz * Math.cos(c); - - //translate to correct position - out.x = rx + b.x; - out.y = ry + b.y; - out.z = rz + b.z; - - return out; - } - - /** - * Rotates a 3D vector around the y-axis. - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The point to rotate. - * @param {vec3} b - The origin of the rotation. - * @param {Number} c - The angle of rotation. - * @returns {vec3} out. - */ - static rotateY(out, a, b, c) { - //Translate point to the origin - let px = a.x - b.x; - let py = a.y - b.y; - let pz = a.z - b.z; - - //perform rotation - let rx = pz * Math.sin(c) + px * Math.cos(c); - let ry = py; - let rz = pz * Math.cos(c) - px * Math.sin(c); - - //translate to correct position - out.x = rx + b.x; - out.y = ry + b.y; - out.z = rz + b.z; - - return out; - } - - /** - * Rotates a 3D vector around the z-axis. - * @param {vec3} out - Vector to store result. - * @param {vec3} a - The point to rotate. - * @param {vec3} b - The origin of the rotation. - * @param {Number} c - The angle of rotation. - * @returns {vec3} out. - */ - static rotateZ(out, a, b, c) { - //Translate point to the origin - let px = a.x - b.x; - let py = a.y - b.y; - let pz = a.z - b.z; - - //perform rotation - let rx = px * Math.cos(c) - py * Math.sin(c); - let ry = px * Math.sin(c) + py * Math.cos(c); - let rz = pz; - - //translate to correct position - out.x = rx + b.x; - out.y = ry + b.y; - out.z = rz + b.z; - - return out; - } - - /** - * Returns string representation of a vector. - * - * @param {vec3} a - The vector. - * @returns {String} - String representation of this vector. - */ - static str(a) { - return `vec3(${a.x}, ${a.y}, ${a.z})`; - } - - /** - * Store components of a vector into array. - * - * @param {Array} out - Array to store result. - * @param {vec3} v - The vector. - * @returns {Array} out. - */ - static array(out, v) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; - - return out; - } - - /** - * Returns whether the specified vectors are equal. (Compared using ===) - * - * @param {vec3} a - The first vector. - * @param {vec3} b - The second vector. - * @returns {Boolean} True if the vectors are equal, false otherwise. - */ - static exactEquals(a, b) { - return a.x === b.x && a.y === b.y && a.z === b.z; - } - - /** - * Returns whether the specified vectors are approximately equal. - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {Boolean} True if the vectors are approximately equal, false otherwise. - */ - static equals(a, b) { - let a0 = a.x, a1 = a.y, a2 = a.z; - let b0 = b.x, b1 = b.y, b2 = b.z; - return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && - Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && - Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))); - } - - /** - * Perform some operation over an array of vec3s. - * - * @param {Array} a the array of vectors to iterate over. - * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed. - * @param {Number} offset Number of elements to skip at the beginning of the array. - * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array. - * @param {Function} fn Function to call for each vector in the array. - * @param {Object} [arg] additional argument to pass to fn. - * @returns {Array} a. - */ - static forEach(a, stride, offset, count, fn, arg) { - return vec3._forEach(a, stride, offset, count, fn, arg); - } - - /** - * Gets the angle between two vectors. - * @param {vec3} a - The first operand. - * @param {vec3} b - The second operand. - * @returns {Number} - The angle in radians. - */ - static angle(a, b) { - return vec3._angle(a, b); - } - - /** - * Projects a vector onto a plane represented by its normal. - * @param {vec3} out The result vector. - * @param {vec3} a The vector. - * @param {vec3} n The plane's normal. - */ - static projectOnPlane(out, a, n) { - return vec3.sub(out, a, vec3.project(out, a, n)); - } - - /** - * Projects a vector onto another vector. - * @param {vec3} out The result vector. - * @param {vec3} a The vector to project. - * @param {vec3} b The vector onto which the projection performs. - */ - static project(out, a, b) { - let sqrLen = vec3.squaredMagnitude(b); - if (sqrLen < 0.000001) - return vec3.set(out, 0, 0, 0); - else - return vec3.scale(out, b, vec3.dot(a, b) / sqrLen); - } -} - -/** -* Perform some operation over an array of vec3s. -* -* @param {Array} a the array of vectors to iterate over. -* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed. -* @param {Number} offset Number of elements to skip at the beginning of the array. -* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array. -* @param {Function} fn Function to call for each vector in the array. -* @param {Object} [arg] additional argument to pass to fn. -* @returns {Array} a. -* @ignore. -*/ -vec3._forEach = (function () { - let vec = vec3.create(0, 0, 0); - - return function (a, stride, offset, count, fn, arg) { - let i, l; - if (!stride) { - stride = 3; - } - - if (!offset) { - offset = 0; - } - - if (count) { - l = Math.min((count * stride) + offset, a.length); - } else { - l = a.length; - } - - for (i = offset; i < l; i += stride) { - vec.x = a[i]; - vec.y = a[i + 1]; - vec.z = a[i + 2]; - fn(vec, vec, arg); - a[i] = vec.x; - a[i + 1] = vec.y; - a[i + 2] = vec.z; - } - - return a; - }; -})(); - -/** - * Get the angle between two 3D vectors. - * @param {vec3} a The first operand. - * @param {vec3} b The second operand. - * @returns {Number} The angle in radians. - * @ignore - */ -vec3._angle = (function () { - let tempA = vec3.create(0, 0, 0); - let tempB = vec3.create(0, 0, 0); - - return function (a, b) { - vec3.copy(tempA, a); - vec3.copy(tempB, b); - - vec3.normalize(tempA, tempA); - vec3.normalize(tempB, tempB); - - let cosine = vec3.dot(tempA, tempB); - - if (cosine > 1.0) { - return 0; - } - - if (cosine < -1.0) { - return Math.PI; - } - - return Math.acos(cosine); - }; -})(); - -export default vec3; \ No newline at end of file diff --git a/cocos/core/vmath/vec3.ts b/cocos/core/vmath/vec3.ts index 83dc826ed5..690d6fb21a 100644 --- a/cocos/core/vmath/vec3.ts +++ b/cocos/core/vmath/vec3.ts @@ -8,6 +8,13 @@ import { EPSILON, random } from './utils'; * x, y, z is alias of the first, second, third component of vector, respectively. */ export default class vec3 { + public static UNIT_X = { x: 1, y: 0, z: 0 }; + public static UNIT_Y = { x: 0, y: 1, z: 0 }; + public static UNIT_Z = { x: 0, y: 0, z: 1 }; + public static ZERO = { x: 0, y: 0, z: 0 }; + public static ONE = { x: 1, y: 1, z: 1 }; + public static NEG_ONE = { x: -1, y: -1, z: -1 }; + /** * Creates a vector, with components specified separately. * From 59fdd376f8d18ecedae81113bd3b47cdffe93398 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 17:34:50 +0800 Subject: [PATCH 055/267] commit modified files --- cocos/gfx/device.ts | 16 ++++++-- cocos/gfx/framebuffer.ts | 1 + cocos/gfx/webgl/webgl-binding-layout.ts | 4 +- cocos/gfx/webgl/webgl-buffer.ts | 4 +- cocos/gfx/webgl/webgl-commands.ts | 44 +-------------------- cocos/gfx/webgl/webgl-device.ts | 43 ++++++++++---------- cocos/gfx/webgl/webgl-gpu-objects.ts | 4 +- cocos/gfx/webgl/webgl-input-assembler.ts | 4 +- cocos/gfx/webgl/webgl-pipeline-layout.ts | 4 +- cocos/gfx/webgl/webgl-pipeline-state.ts | 4 +- cocos/gfx/webgl/webgl-sampler.ts | 4 +- cocos/gfx/webgl/webgl-shader.ts | 4 +- cocos/gfx/webgl/webgl-texture-view.ts | 4 +- cocos/gfx/webgl/webgl-window.ts | 6 +-- cocos/renderer/scene/camera.ts | 50 ++++++++++++++++++++++++ 15 files changed, 110 insertions(+), 86 deletions(-) diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 1c97dc83bf..e37c42ef07 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -13,7 +13,7 @@ import { GFXCommandBufferInfo, GFXCommandBuffer } from './command-buffer'; import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './command-allocator'; import { GFXWindowInfo, GFXWindow } from './window'; import { GFXBindingLayoutInfo, GFXBindingLayout } from './binding-layout'; -import { GFXRect, GFXBufferTextureCopy } from './define'; +import { GFXRect, GFXBufferTextureCopy, GFXFormat } from './define'; export enum GFXFeature { }; @@ -69,8 +69,8 @@ export abstract class GFXDevice { return this._height; } - public get mainWindow(): GFXWindow | null { - return this._mainWindow; + public get mainWindow(): GFXWindow { + return this._mainWindow; } public get commandAllocator(): GFXCommandAllocator { @@ -113,6 +113,14 @@ export abstract class GFXDevice { return this._stencilBits; } + public get colorFormat(): GFXFormat { + return this._colorFmt; + } + + public get depthStencilFormat(): GFXFormat { + return this._depthStencilFmt; + } + public genShaderId(): number { return this._shaderIdGen++; } @@ -135,5 +143,7 @@ export abstract class GFXDevice { protected _maxVertexTextureUnits: number = 0; protected _depthBits: number = 0; protected _stencilBits: number = 0; + protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; + protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; protected _shaderIdGen: number = 0; }; diff --git a/cocos/gfx/framebuffer.ts b/cocos/gfx/framebuffer.ts index adb1751031..c5a6f3d7ef 100644 --- a/cocos/gfx/framebuffer.ts +++ b/cocos/gfx/framebuffer.ts @@ -1,6 +1,7 @@ import { GFXDevice } from './device'; import { GFXTextureView } from './texture-view'; import { GFXRenderPass } from './render-pass'; +import { GFXFormat } from './define'; export interface GFXFramebufferInfo { renderPass: GFXRenderPass; diff --git a/cocos/gfx/webgl/webgl-binding-layout.ts b/cocos/gfx/webgl/webgl-binding-layout.ts index 76343d2154..9cabcec35f 100644 --- a/cocos/gfx/webgl/webgl-binding-layout.ts +++ b/cocos/gfx/webgl/webgl-binding-layout.ts @@ -46,8 +46,8 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { return this._device; } - public get gpuBindingLayout(): WebGLGPUBindingLayout | null { - return this._gpuBindingLayout; + public get gpuBindingLayout(): WebGLGPUBindingLayout { + return this._gpuBindingLayout; } private _gpuBindingLayout: WebGLGPUBindingLayout | null = null; diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index f9e5cf21a8..078ed87aed 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -55,8 +55,8 @@ export class WebGLGFXBuffer extends GFXBuffer { return this._device; } - public get gpuBuffer(): WebGLGPUBuffer | null { - return this._gpuBuffer; + public get gpuBuffer(): WebGLGPUBuffer { + return this._gpuBuffer; } private _gpuBuffer: WebGLGPUBuffer | null = null; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 0d5c4acec3..a1221a7f4e 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -893,7 +893,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // create uniform blocks - if (gpuShader.blocks && gpuShader.blocks.length > 0) { + if (gpuShader.blocks.length > 0) { gpuShader.glBlocks = new Array(gpuShader.blocks.length); for (let i = 0; i < gpuShader.blocks.length; ++i) { let block = gpuShader.blocks[i]; @@ -937,7 +937,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // create uniform samplers - if (gpuShader.samplers && gpuShader.samplers.length > 0) { + if (gpuShader.samplers.length > 0) { gpuShader.glSamplers = new Array(gpuShader.samplers.length); for (let i = 0; i < gpuShader.samplers.length; ++i) { @@ -1087,46 +1087,6 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput offsets[stream] += size; } - - /* - if (gpuInputAssembler.gpuShader) { - let attribCount = gpuInputAssembler.gpuShader.glInputs.length; - gpuInputAssembler.glAttribs = new Array(attribCount); - - let offsets = [0, 0, 0, 0, 0, 0, 0, 0]; - - for (let i = 0; i < attribCount; ++i) { - let glInput = gpuInputAssembler.gpuShader.glInputs[i]; - let glAttrib = gpuInputAssembler.glAttribs[i]; - glAttrib.glLoc = glInput.glLoc; - glAttrib.glType = glInput.glType; - glAttrib.size = glInput.size; - glAttrib.componentCount = WebGLGetComponentCount(glAttrib.glType); - - for (let j = 0; j < gpuInputAssembler.attributes.length; ++j) { - let attrib = gpuInputAssembler.attributes[j]; - - let stream = attrib.stream !== undefined ? attrib.stream : 0; - - if (glInput.name === attrib.name && stream < gpuInputAssembler.gpuVertexBuffers.length) { - - let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; - glAttrib.count = GFXFormatInfos[attrib.format].count; - glAttrib.stride = gpuBuffer.stride; - glAttrib.glBuffer = gpuBuffer.glBuffer; - - if (attrib.isInstanced) { - glAttrib.isInstanced = attrib.isInstanced; - } - - glAttrib.offset = offsets[stream]; - offsets[stream] += glInput.size; - break; - } - } - } - } - */ } export function WebGLCmdFuncDestroyInputAssembler(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 306b1f346e..ae57c065b4 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -130,11 +130,28 @@ export class WebGLGFXDevice extends GFXDevice { this._width = this._canvas.width; this._height = this._canvas.height; + this._colorFmt = GFXFormat.RGBA8; + + if (this._depthBits === 24) { + if (this._stencilBits === 8) { + this._depthStencilFmt = GFXFormat.D24S8; + } else { + this._depthStencilFmt = GFXFormat.D24; + } + } else { + if (this._stencilBits === 8) { + this._depthStencilFmt = GFXFormat.D16S8; + } else { + this._depthStencilFmt = GFXFormat.D16; + } + } console.info("RENDERER: " + this._renderer); console.info("VENDOR: " + this._vendor); console.info("VERSION: " + this._version); - console.info("SCREEN_SIZE: " + this._width + "x" + this._height); + console.info("SCREEN_SIZE: " + this._width + " x " + this._height); + console.info("COLOR_FORMAT: " + GFXFormatInfos[this._colorFmt].name); + console.info("DEPTH_STENCIL_FORMAT: " + GFXFormatInfos[this._depthStencilFmt].name); console.info("MAX_VERTEX_ATTRIBS: " + this._maxVertexAttributes); console.info("MAX_VERTEX_UNIFORM_VECTORS: " + this._maxVertexUniformVectors); @@ -176,21 +193,7 @@ export class WebGLGFXDevice extends GFXDevice { // init states this.initStates(gl); - let depthStencilFmt; - if (this._depthBits === 24) { - if (this._stencilBits === 8) { - depthStencilFmt = GFXFormat.D24S8; - } else { - depthStencilFmt = GFXFormat.D24; - } - } else { - if (this._stencilBits === 8) { - depthStencilFmt = GFXFormat.D16S8; - } else { - depthStencilFmt = GFXFormat.D16; - } - } // create queue this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); @@ -202,8 +205,8 @@ export class WebGLGFXDevice extends GFXDevice { top: this._webGLRC.canvas.offsetTop, width: this._webGLRC.drawingBufferWidth, height: this._webGLRC.drawingBufferHeight, - colorFmt: GFXFormat.RGBA8, - depthStencilFmt: depthStencilFmt, + colorFmt: this._colorFmt, + depthStencilFmt: this._depthStencilFmt, }); this._cmdAllocator = this.createCommandAllocator({}); @@ -430,7 +433,7 @@ export class WebGLGFXDevice extends GFXDevice { let memSize = GFXFormatSize(GFXFormat.RGBA8, w, h, 1); let data = view.subarray(buffOffset, buffOffset + memSize); - + gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, data); } @@ -732,8 +735,8 @@ export class WebGLGFXDevice extends GFXDevice { let gpuShader: WebGLGPUShader = { objType: WebGLGPUObjectType.SHADER, name: info.name ? info.name : "", - blocks: info.blocks, - samplers: info.samplers, + blocks: (info.blocks !== undefined ? info.blocks : []), + samplers: (info.samplers !== undefined ? info.samplers : []), gpuStages: gpuStages, glProgram: 0, diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 9bfd803b83..1f2ddcf769 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -175,8 +175,8 @@ export class WebGLGPUShaderStage { export class WebGLGPUShader extends WebGLGPUObject { name: string = ""; - blocks?: GFXUniformBlock[]; - samplers?: GFXUniformSampler[]; + blocks: GFXUniformBlock[] = []; + samplers: GFXUniformSampler[] = []; gpuStages: WebGLGPUShaderStage[] = []; glProgram: WebGLProgram = 0; diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index e74a2d8b99..b6d47c1fa1 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -47,8 +47,8 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { return this._device; } - public get gpuInputAssembler(): WebGLGPUInputAssembler | null { - return this._gpuInputAssembler; + public get gpuInputAssembler(): WebGLGPUInputAssembler { + return this._gpuInputAssembler; } private _gpuInputAssembler: WebGLGPUInputAssembler | null = null; diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts index e42563dc34..75aeb0f5de 100644 --- a/cocos/gfx/webgl/webgl-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -27,8 +27,8 @@ export class WebGLGFXPipelineLayout extends GFXPipelineLayout { return this._device; } - public get gpuPipelineLayout(): WebGLGPUPipelineLayout | null { - return this._gpuPipelineLayout; + public get gpuPipelineLayout(): WebGLGPUPipelineLayout { + return this._gpuPipelineLayout; } private _gpuPipelineLayout: WebGLGPUPipelineLayout | null = null; diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts index 79d379121e..f53d765f20 100644 --- a/cocos/gfx/webgl/webgl-pipeline-state.ts +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -36,8 +36,8 @@ export class WebGLGFXPipelineState extends GFXPipelineState { return this._device; } - public get gpuPipelineState(): WebGLGPUPipelineState | null { - return this._gpuPipelineState; + public get gpuPipelineState(): WebGLGPUPipelineState { + return this._gpuPipelineState; } private _gpuPipelineState: WebGLGPUPipelineState | null = null; diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts index b4f57c19c7..372dd84c42 100644 --- a/cocos/gfx/webgl/webgl-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -81,8 +81,8 @@ export class WebGLGFXSampler extends GFXSampler { return this._device; } - public get gpuSampler() : WebGLGPUSampler | null { - return this._gpuSampler; + public get gpuSampler() : WebGLGPUSampler { + return this._gpuSampler; } private _gpuSampler : WebGLGPUSampler | null = null; diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts index a0fe6ad917..2f5119686a 100644 --- a/cocos/gfx/webgl/webgl-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -38,8 +38,8 @@ export class WebGLGFXShader extends GFXShader { return this._device; } - public get gpuShader(): WebGLGPUShader | null { - return this._gpuShader; + public get gpuShader(): WebGLGPUShader { + return this._gpuShader; } private _gpuShader: WebGLGPUShader | null = null; diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts index aa9e0a289a..920169270a 100644 --- a/cocos/gfx/webgl/webgl-texture-view.ts +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -49,8 +49,8 @@ export class WebGLGFXTextureView extends GFXTextureView { return this._device; } - public get gpuTextureView(): WebGLGPUTextureView | null { - return this._gpuTextureView; + public get gpuTextureView(): WebGLGPUTextureView { + return this._gpuTextureView; } private _gpuTextureView: WebGLGPUTextureView | null = null; diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index 742c43264a..15fec7b617 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -11,15 +11,15 @@ export class WebGLGFXWindow extends GFXWindow { public initialize(info: GFXWindowInfo): boolean { - if(info.title) { + if(info.title !== undefined) { this._title = info.title; } - if(info.left) { + if(info.left !== undefined) { this._left = info.left; } - if(info.top) { + if(info.top !== undefined) { this._top = info.top; } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 635d01b374..f8aa88ff6c 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -2,6 +2,13 @@ import { RenderScene } from "./render-scene"; import Node from "../../scene-graph/node"; import { mat4, vec3, quat } from '../../core/vmath'; +export enum NodeSpace +{ + LOCAL, + PARENT, + WORLD, +}; + export enum CameraProjection { PERSPECTIVE, ORTHO, @@ -119,6 +126,49 @@ export class Camera { return this._position; } + public rotate(axis: vec3, rad: number, ns?: NodeSpace) { + quat.fromAxisAngle(this._rotation, axis, rad); + let space = (ns !== undefined? ns : NodeSpace.LOCAL); + if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + this._node.setRotation(this._rotation); + } else if (space === NodeSpace.WORLD) { + this._node.setWorldRotation(this._rotation); + } + } + + public pitch(rad: number, ns?: NodeSpace) { + let space = (ns !== undefined? ns : NodeSpace.LOCAL); + if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + this._node.getRotation(this._rotation); + this.rotate(this._rotation, rad, ns); + } else if (space === NodeSpace.WORLD) { + this._node.getWorldRotation(this._rotation); + this.rotate(this._rotation, rad, ns); + } + } + + public yaw(rad: number, ns?: NodeSpace) { + let space = (ns !== undefined? ns : NodeSpace.LOCAL); + if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + this._node.getRotation(this._rotation); + this.rotate(this._rotation, rad, ns); + } else if (space === NodeSpace.WORLD) { + this._node.getWorldRotation(this._rotation); + this.rotate(this._rotation, rad, ns); + } + } + + public roll(rad: number, ns?: NodeSpace) { + let space = (ns !== undefined? ns : NodeSpace.LOCAL); + if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + this._node.getRotation(this._rotation); + this.rotate(this._rotation, rad, ns); + } else if (space === NodeSpace.WORLD) { + this._node.getWorldRotation(this._rotation); + this.rotate(this._rotation, rad, ns); + } + } + public set target(target: vec3) { this._node.lookAt(target); } From d0eade4621faf1729b49b6a8414863bfd722f14f Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 17:49:32 +0800 Subject: [PATCH 056/267] fix compilation error --- cocos/core/vmath/quat.ts | 2 +- cocos/pipeline/forward/forward-flow.ts | 4 ++-- cocos/renderer/scene/camera.ts | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/core/vmath/quat.ts b/cocos/core/vmath/quat.ts index a23f28ec23..348b037cb9 100644 --- a/cocos/core/vmath/quat.ts +++ b/cocos/core/vmath/quat.ts @@ -92,7 +92,7 @@ export default class quat { * @param b - The destination vector. * @return out. */ - public static rotationTo (out: Out, a: quat, b: quat) { + public static rotationTo (out: Out, a: vec3, b: vec3) { const dot = vec3.dot(a, b); if (dot < -0.999999) { vec3.cross(tmpVec3, tmpXUnitVec3, a); diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 100369cc7a..d028bc9eef 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -35,19 +35,19 @@ export class ForwardFlow extends RenderFlow { }); */ + /* this.createStage(TestMaterialStage, { name: "TestMaterialStage", priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); + */ - /* this.createStage(TestStage, { name: "TestStage", priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - */ return true; } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 5a0c609eb3..cc2435d8fc 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,6 +1,6 @@ import { RenderScene } from "./render-scene"; import Node from "../../scene-graph/node"; -import { mat4, vec3, quat } from '../../core/vmath'; +import { vec3, mat4, quat } from "../../core/vmath"; export enum NodeSpace { @@ -174,8 +174,8 @@ export class Camera { } public get direction(): vec3 { - quat.getRotation(this._rotation); - quat.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); + this._node.getRotation(this._rotation); + vec3.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); return this._direction; } From 02601c9bedafcd9fe1bfc0cea6b949ea88b45ea8 Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 8 Jan 2019 18:04:15 +0800 Subject: [PATCH 057/267] modify lint --- tslint.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tslint.json b/tslint.json index 1ba95e26a4..3304af09b8 100644 --- a/tslint.json +++ b/tslint.json @@ -8,7 +8,10 @@ "quotemark": [ true, "single" ], "no-console": false, "space-before-function-paren": true, - "max-classes-per-file": false + "max-classes-per-file": false, + "variable-name": false, + "object-literal-sort-keys": false, + "ban-types": false }, "rulesDirectory": [] } \ No newline at end of file From 59723a976feb2a063c21741ada4e51b5381c674a Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 8 Jan 2019 16:05:03 +0800 Subject: [PATCH 058/267] rename to ts, tslint auto fix --- ...lbacks-invoker.js => callbacks-invoker.ts} | 78 +++++++++---------- .../{event-target.js => event-target.ts} | 16 ++-- cocos/core/event/{event.js => event.ts} | 20 ++--- cocos/core/event/{index.js => index.ts} | 2 +- 4 files changed, 55 insertions(+), 61 deletions(-) rename cocos/core/event/{callbacks-invoker.js => callbacks-invoker.ts} (83%) rename cocos/core/event/{event-target.js => event-target.ts} (96%) rename cocos/core/event/{event.js => event.ts} (96%) rename cocos/core/event/{index.js => index.ts} (96%) diff --git a/cocos/core/event/callbacks-invoker.js b/cocos/core/event/callbacks-invoker.ts similarity index 83% rename from cocos/core/event/callbacks-invoker.js rename to cocos/core/event/callbacks-invoker.ts index 5f05aec478..71ad886bad 100644 --- a/cocos/core/event/callbacks-invoker.js +++ b/cocos/core/event/callbacks-invoker.ts @@ -35,10 +35,10 @@ class CallbackList { this.containCanceled = false; } - removeBy (array, value) { + public removeBy (array, value) { var callbacks = this.callbacks; var targets = this.targets; - for (var i = 0; i < array.length; ++i) { + for (let i = 0; i < array.length; ++i) { if (array[i] === value) { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); @@ -47,14 +47,14 @@ class CallbackList { } } - cancel (index) { + public cancel (index) { this.callbacks[index] = this.targets[index] = null; this.containCanceled = true; } - cancelAll () { - let callbacks = this.callbacks; - let targets = this.targets; + public cancelAll () { + const callbacks = this.callbacks; + const targets = this.targets; for (let i = 0; i < callbacks.length; i++) { callbacks[i] = targets[i] = null; } @@ -62,14 +62,14 @@ class CallbackList { } // filter all removed callbacks and compact array - purgeCanceled () { + public purgeCanceled () { this.removeBy(this.callbacks, null); this.containCanceled = false; } } const MAX_SIZE = 16; -let callbackListPool = new js.Pool(function (list) { +const callbackListPool = new js.Pool(function (list) { list.callbacks.length = 0; list.targets.length = 0; list.isInvoking = false; @@ -98,7 +98,7 @@ CallbacksHandler.prototype = { * @param {Object} [target] - can be null */ add (key, callback, target) { - var list = this._callbackTable[key]; + let list = this._callbackTable[key]; if (!list) { list = this._callbackTable[key] = callbackListPool.get(); } @@ -116,13 +116,13 @@ CallbacksHandler.prototype = { * @return {Boolean} */ hasEventListener (key, callback, target) { - var list = this._callbackTable[key]; + const list = this._callbackTable[key]; if (!list) { return false; } // check any valid callback - var callbacks = list.callbacks; + const callbacks = list.callbacks; if (!callback) { // Make sure no cancelled callbacks if (list.isInvoking) { @@ -132,14 +132,13 @@ CallbacksHandler.prototype = { } } return false; - } - else { + } else { return callbacks.length > 0; } } target = target || null; - var targets = list.targets; + const targets = list.targets; for (let i = 0; i < callbacks.length; ++i) { if (callbacks[i] === callback && targets[i] === target) { return true; @@ -156,30 +155,27 @@ CallbacksHandler.prototype = { removeAll (keyOrTarget) { if (typeof keyOrTarget === 'string') { // remove by key - let list = this._callbackTable[keyOrTarget]; + const list = this._callbackTable[keyOrTarget]; if (list) { if (list.isInvoking) { list.cancelAll(); - } - else { + } else { callbackListPool.put(list); delete this._callbackTable[keyOrTarget]; } } - } - else if (keyOrTarget) { + } else if (keyOrTarget) { // remove by target - for (let key in this._callbackTable) { - let list = this._callbackTable[key]; + for (const key in this._callbackTable) { + const list = this._callbackTable[key]; if (list.isInvoking) { - let targets = list.targets; + const targets = list.targets; for (let i = 0; i < targets.length; ++i) { if (targets[i] === keyOrTarget) { list.cancel(i); } } - } - else { + } else { list.removeBy(list.targets, keyOrTarget); } } @@ -193,17 +189,16 @@ CallbacksHandler.prototype = { * @param {Object} [target] */ remove (key, callback, target) { - var list = this._callbackTable[key]; + const list = this._callbackTable[key]; if (list) { target = target || null; - var callbacks = list.callbacks; - var targets = list.targets; - for (var i = 0; i < callbacks.length; ++i) { + const callbacks = list.callbacks; + const targets = list.targets; + for (let i = 0; i < callbacks.length; ++i) { if (callbacks[i] === callback && targets[i] === target) { if (list.isInvoking) { list.cancel(i); - } - else { + } else { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); } @@ -211,7 +206,7 @@ CallbacksHandler.prototype = { } } } - } + }, }; /** @@ -236,21 +231,20 @@ js.mixin(CallbacksInvoker.prototype, { * @param {any} [p5] */ emit (key, p1, p2, p3, p4, p5) { - var list = this._callbackTable[key]; + const list = this._callbackTable[key]; if (list) { - var rootInvoker = !list.isInvoking; + const rootInvoker = !list.isInvoking; list.isInvoking = true; - var callbacks = list.callbacks; - var targets = list.targets; - for (var i = 0, len = callbacks.length; i < len; ++i) { - var callback = callbacks[i]; + const callbacks = list.callbacks; + const targets = list.targets; + for (let i = 0, len = callbacks.length; i < len; ++i) { + const callback = callbacks[i]; if (callback) { - var target = targets[i]; + const target = targets[i]; if (target) { callback.call(target, p1, p2, p3, p4, p5); - } - else { + } else { callback(p1, p2, p3, p4, p5); } } @@ -263,7 +257,7 @@ js.mixin(CallbacksInvoker.prototype, { } } } - } + }, }); if (CC_TEST) { @@ -272,5 +266,5 @@ if (CC_TEST) { export { CallbacksHandler, - CallbacksInvoker + CallbacksInvoker, }; diff --git a/cocos/core/event/event-target.js b/cocos/core/event/event-target.ts similarity index 96% rename from cocos/core/event/event-target.js rename to cocos/core/event/event-target.ts index 9013108e6a..4f36dba9c1 100644 --- a/cocos/core/event/event-target.js +++ b/cocos/core/event/event-target.ts @@ -103,8 +103,9 @@ js.mixin(EventTarget.prototype, { if ( !this.hasEventListener(type, callback, target) ) { this.add(type, callback, target); - if (target && target.__eventTargets) + if (target && target.__eventTargets) { target.__eventTargets.push(this); + } } return callback; }, @@ -133,8 +134,7 @@ js.mixin(EventTarget.prototype, { off (type, callback, target) { if (!callback) { this.removeAll(type); - } - else { + } else { this.remove(type, callback, target); if (target && target.__eventTargets) { @@ -181,11 +181,11 @@ js.mixin(EventTarget.prototype, { * }, node); */ once (type, callback, target) { - var eventType_hasOnceListener = '__ONCE_FLAG:' + type; - var hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); + const eventType_hasOnceListener = '__ONCE_FLAG:' + type; + const hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { - var self = this; - var onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { + const self = this; + const onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { self.off(type, onceWrapper, target); self.remove(eventType_hasOnceListener, callback, target); callback.call(this, arg1, arg2, arg3, arg4, arg5); @@ -225,7 +225,7 @@ js.mixin(EventTarget.prototype, { */ dispatchEvent (event) { this.invoke(event.type, event); - } + }, }); cc.EventTarget = EventTarget; diff --git a/cocos/core/event/event.js b/cocos/core/event/event.ts similarity index 96% rename from cocos/core/event/event.js rename to cocos/core/event/event.ts index 12b5a4053a..ac80e2e6d9 100644 --- a/cocos/core/event/event.js +++ b/cocos/core/event/event.ts @@ -107,7 +107,7 @@ class Event { * @method unuse * @returns {String} */ - unuse () { + public unuse () { this.type = cc.Event.NO_TYPE; this.target = null; this.currentTarget = null; @@ -122,7 +122,7 @@ class Event { * @method reuse * @returns {String} */ - reuse (type, bubbles) { + public reuse (type, bubbles) { this.type = type; this.bubbles = bubbles || false; } @@ -132,7 +132,7 @@ class Event { * !#zh 停止传递当前事件。 * @method stopPropagation */ - stopPropagation () { + public stopPropagation () { this._propagationStopped = true; } @@ -142,7 +142,7 @@ class Event { * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 * @method stopPropagationImmediate */ - stopPropagationImmediate () { + public stopPropagationImmediate () { this._propagationImmediateStopped = true; } @@ -152,7 +152,7 @@ class Event { * @method isStopped * @returns {Boolean} */ - isStopped () { + public isStopped () { return this._propagationStopped || this._propagationImmediateStopped; } @@ -167,7 +167,7 @@ class Event { * @method getCurrentTarget * @returns {Node} The target with which the event associates. */ - getCurrentTarget () { + public getCurrentTarget () { return this.currentTarget; } @@ -177,12 +177,12 @@ class Event { * @method getType * @returns {String} */ - getType () { + public getType () { return this.type; } } -//event type +// event type /** * !#en Code for event without type. * !#zh 没有类型的事件 @@ -225,7 +225,7 @@ Event.KEYBOARD = 'keyboard'; */ Event.ACCELERATION = 'acceleration'; -//event phase +// event phase /** * !#en Events not currently dispatched are in this phase * !#zh 尚未派发事件阶段 @@ -266,4 +266,4 @@ Event.AT_TARGET = 2; Event.BUBBLING_PHASE = 3; cc.Event = Event; -export default Event; \ No newline at end of file +export default Event; diff --git a/cocos/core/event/index.js b/cocos/core/event/index.ts similarity index 96% rename from cocos/core/event/index.js rename to cocos/core/event/index.ts index 298fb5ea72..7a652d3cbb 100644 --- a/cocos/core/event/index.js +++ b/cocos/core/event/index.ts @@ -25,4 +25,4 @@ ****************************************************************************/ export { default as Event } from './event'; -export { default as EventTarget } from './event-target'; \ No newline at end of file +export { default as EventTarget } from './event-target'; From 857b901d52fcd581f367f7087c05fdeece90bf9c Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 8 Jan 2019 17:18:56 +0800 Subject: [PATCH 059/267] fix event related ts files --- cocos/core/event/callbacks-invoker.ts | 122 +++++------ cocos/core/event/event-target.ts | 107 +++++----- cocos/core/event/event.ts | 285 +++++++++++--------------- 3 files changed, 220 insertions(+), 294 deletions(-) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 71ad886bad..56ded45fa0 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -28,16 +28,17 @@ import * as js from '../utils/js'; const fastRemoveAt = js.array.fastRemoveAt; class CallbackList { - constructor () { - this.callbacks = []; - this.targets = []; // same length with callbacks, nullable - this.isInvoking = false; - this.containCanceled = false; - } + public callbacks: Array = []; + + public targets: Array = []; // same length with callbacks, nullable + + public isInvoking = false; + + public containCanceled = false; public removeBy (array, value) { - var callbacks = this.callbacks; - var targets = this.targets; + const callbacks = this.callbacks; + const targets = this.targets; for (let i = 0; i < array.length; ++i) { if (array[i] === value) { fastRemoveAt(callbacks, i); @@ -47,7 +48,7 @@ class CallbackList { } } - public cancel (index) { + public cancel (index: number) { this.callbacks[index] = this.targets[index] = null; this.containCanceled = true; } @@ -69,7 +70,7 @@ class CallbackList { } const MAX_SIZE = 16; -const callbackListPool = new js.Pool(function (list) { +const callbackListPool = new js.Pool((list: CallbackList) => { list.callbacks.length = 0; list.targets.length = 0; list.isInvoking = false; @@ -79,6 +80,10 @@ callbackListPool.get = function () { return this._get() || new CallbackList(); }; +interface ICallbackTable { + [x: string]: CallbackList | undefined; +} + /** * The CallbacksHandler is an abstract class that can register and unregister callbacks by key. * Subclasses should implement their own methods about how to invoke the callbacks. @@ -86,36 +91,31 @@ callbackListPool.get = function () { * * @private */ -function CallbacksHandler () { - this._callbackTable = js.createMap(true); -} -CallbacksHandler.prototype = { - constructor: CallbacksHandler, +export class CallbacksHandler { + protected _callbackTable: ICallbackTable = js.createMap(true); + /** - * @method add - * @param {String} key - * @param {Function} callback - * @param {Object} [target] - can be null + * @param key + * @param callback + * @param [target] - can be null */ - add (key, callback, target) { + public add (key: string, callback: Function, target: object | null = null) { let list = this._callbackTable[key]; if (!list) { - list = this._callbackTable[key] = callbackListPool.get(); + list = this._callbackTable[key] = callbackListPool.get() as CallbackList; } list.callbacks.push(callback); list.targets.push(target || null); - }, + } /** * Check if the specified key has any registered callback. If a callback is also specified, * it will only return true if the callback is registered. - * @method hasEventListener - * @param {String} key - * @param {Function} [callback] - * @param {Object} [target] - * @return {Boolean} + * @param key + * @param [callback] + * @param [target] */ - hasEventListener (key, callback, target) { + public hasEventListener (key: string, callback?: Function, target: Object | null = null) { const list = this._callbackTable[key]; if (!list) { return false; @@ -126,8 +126,8 @@ CallbacksHandler.prototype = { if (!callback) { // Make sure no cancelled callbacks if (list.isInvoking) { - for (let i = 0; i < callbacks.length; i++) { - if (callbacks[i]) { + for (const cb of callbacks) { + if (cb) { return true; } } @@ -145,14 +145,13 @@ CallbacksHandler.prototype = { } } return false; - }, + } /** * Removes all callbacks registered in a certain event type or all callbacks registered with a certain target - * @method removeAll - * @param {String|Object} keyOrTarget - The event key to be removed or the target to be removed + * @param keyOrTarget - The event key to be removed or the target to be removed */ - removeAll (keyOrTarget) { + public removeAll (keyOrTarget?: string | object) { if (typeof keyOrTarget === 'string') { // remove by key const list = this._callbackTable[keyOrTarget]; @@ -167,20 +166,22 @@ CallbacksHandler.prototype = { } else if (keyOrTarget) { // remove by target for (const key in this._callbackTable) { - const list = this._callbackTable[key]; - if (list.isInvoking) { - const targets = list.targets; - for (let i = 0; i < targets.length; ++i) { - if (targets[i] === keyOrTarget) { - list.cancel(i); + if (this._callbackTable.hasOwnProperty(key)) { + const list = this._callbackTable[key]!; + if (list.isInvoking) { + const targets = list.targets; + for (let i = 0; i < targets.length; ++i) { + if (targets[i] === keyOrTarget) { + list.cancel(i); + } } + } else { + list.removeBy(list.targets, keyOrTarget); } - } else { - list.removeBy(list.targets, keyOrTarget); } } } - }, + } /** * @method remove @@ -188,7 +189,7 @@ CallbacksHandler.prototype = { * @param {Function} callback * @param {Object} [target] */ - remove (key, callback, target) { + public remove (key, callback, target) { const list = this._callbackTable[key]; if (list) { target = target || null; @@ -206,31 +207,15 @@ CallbacksHandler.prototype = { } } } - }, -}; + } +} /** * !#en The callbacks invoker to handle and invoke callbacks by key. * !#zh CallbacksInvoker 用来根据 Key 管理并调用回调方法。 - * @class CallbacksInvoker - * - * @extends _CallbacksHandler */ -function CallbacksInvoker () { - CallbacksHandler.call(this); -} -js.extend(CallbacksInvoker, CallbacksHandler); -js.mixin(CallbacksInvoker.prototype, { - /** - * @method emit - * @param {String} key - * @param {any} [p1] - * @param {any} [p2] - * @param {any} [p3] - * @param {any} [p4] - * @param {any} [p5] - */ - emit (key, p1, p2, p3, p4, p5) { +export class CallbacksInvoker extends CallbacksHandler { + public emit (key: string, p1?: any, p2?: any, p3?: any, p4?: any, p5?: any) { const list = this._callbackTable[key]; if (list) { const rootInvoker = !list.isInvoking; @@ -257,14 +242,9 @@ js.mixin(CallbacksInvoker.prototype, { } } } - }, -}); + } +} if (CC_TEST) { cc._Test.CallbacksInvoker = CallbacksInvoker; } - -export { - CallbacksHandler, - CallbacksInvoker, -}; diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index 4f36dba9c1..070f294821 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -25,7 +25,8 @@ ****************************************************************************/ import * as js from '../utils/js'; -import {CallbacksInvoker} from './callbacks-invoker'; +import { CallbacksInvoker } from './callbacks-invoker'; +import Event from './event'; const fastRemove = js.array.fastRemove; @@ -53,21 +54,17 @@ const fastRemove = js.array.fastRemove; * 事件目标是事件触发时,分派的事件对象,Node 是最常见的事件目标, * 但是其他对象也可以是事件目标。
* - * @class EventTarget - * @extends CallbacksInvoker */ -function EventTarget () { - CallbacksInvoker.call(this); -} -js.extend(EventTarget, CallbacksInvoker); -js.mixin(EventTarget.prototype, { +export default class EventTarget extends CallbacksInvoker { /** * !#en Checks whether the EventTarget object has any callback registered for a specific type of event. * !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。 - * @method hasEventListener - * @param {String} type - The type of event. - * @return {Boolean} True if a callback of the specified type is registered; false otherwise. + * @param type - The type of event. + * @return True if a callback of the specified type is registered; false otherwise. */ + public hasEventListener (key: string) { + return super.hasEventListener(key); + } /** * !#en @@ -76,39 +73,28 @@ js.mixin(EventTarget.prototype, { * !#zh * 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。 * - * @method on - * @param {String} type - A string representing the event type to listen for. - * @param {Function} callback - The callback that will be invoked when the event is dispatched. - * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {any} [callback.arg1] arg1 - * @param {any} [callback.arg2] arg2 - * @param {any} [callback.arg3] arg3 - * @param {any} [callback.arg4] arg4 - * @param {any} [callback.arg5] arg5 - * @param {Object} [target] - The target (this object) to invoke the callback, can be null - * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. - * @typescript - * on(type: string, callback: T, target?: any, useCapture?: boolean): T + * @param type - A string representing the event type to listen for. + * @param callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param target - The target (this object) to invoke the callback, can be null + * @return Just returns the incoming callback so you can save the anonymous function easier. * @example * eventTarget.on('fire', function () { * cc.log("fire in the hole"); * }, node); */ - on (type, callback, target) { - if (!callback) { - cc.errorID(6800); - return; - } - - if ( !this.hasEventListener(type, callback, target) ) { + public on (type: string, callback: T, target: Object | null = null) { + if (!super.hasEventListener(type, callback, target)) { this.add(type, callback, target); + // @ts-ignore if (target && target.__eventTargets) { + // @ts-ignore target.__eventTargets.push(this); } } return callback; - }, + } /** * !#en @@ -118,9 +104,10 @@ js.mixin(EventTarget.prototype, { * 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 * * @method off - * @param {String} type - A string representing the event type being removed. - * @param {Function} [callback] - The callback to remove. - * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @param type - A string representing the event type being removed. + * @param [callback] - The callback to remove. + * @param [target] - The target (this object) to invoke the callback, + * if it's not given, only callback without target will be removed * @example * // register fire eventListener * var callback = eventTarget.on('fire', function () { @@ -131,32 +118,35 @@ js.mixin(EventTarget.prototype, { * // remove all fire event listeners * eventTarget.off('fire'); */ - off (type, callback, target) { + public off (type: string, callback?: Function, target: Object | null = null) { if (!callback) { this.removeAll(type); } else { this.remove(type, callback, target); + // @ts-ignore if (target && target.__eventTargets) { + // @ts-ignore fastRemove(target.__eventTargets, this); } } - }, + } /** * !#en Removes all callbacks previously registered with the same target (passed as parameter). * This is not for removing all listeners in the current event target, * and this is not for removing all listeners the target parameter have registered. - * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. + * It's only for removing all listeners (callback and target couple) registered + * on the current event target by the target parameter. * !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 * @method targetOff * @param {Object} target - The target to be searched for all related listeners */ - targetOff () { + public targetOff () { this.removeAll(); - }, + } /** * !#en @@ -180,20 +170,21 @@ js.mixin(EventTarget.prototype, { * cc.log("this is the callback and will be invoked only once"); * }, node); */ - once (type, callback, target) { + public once (type, callback, target) { const eventType_hasOnceListener = '__ONCE_FLAG:' + type; - const hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); + const hasOnceListener = super.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { const self = this; const onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { self.off(type, onceWrapper, target); self.remove(eventType_hasOnceListener, callback, target); + // @ts-ignore callback.call(this, arg1, arg2, arg3, arg4, arg5); }; this.on(type, onceWrapper, target); this.add(eventType_hasOnceListener, callback, target); } - }, + } /** * !#en @@ -201,18 +192,20 @@ js.mixin(EventTarget.prototype, { * !#zh * 通过事件名发送自定义事件 * - * @method emit - * @param {String} type - event type - * @param {*} [arg1] - First argument - * @param {*} [arg2] - Second argument - * @param {*} [arg3] - Third argument - * @param {*} [arg4] - Fourth argument - * @param {*} [arg5] - Fifth argument + * @param type - event type + * @param arg1 - First argument + * @param arg2 - Second argument + * @param arg3 - Third argument + * @param arg4 - Fourth argument + * @param arg5 - Fifth argument * @example * * eventTarget.emit('fire', event); * eventTarget.emit('fire', message, emitter); */ + public emit (key: string, p1?: any, p2?: any, p3?: any, p4?: any, p5?: any) { + return super.emit(key, p1, p2, p3, p4, p5); + } /** * !#en @@ -220,13 +213,13 @@ js.mixin(EventTarget.prototype, { * !#zh * 通过事件对象派发事件 * - * @method dispatchEvent - * @param {Event} event + * @param event */ - dispatchEvent (event) { + public dispatchEvent (event: Event) { + // @ts-ignore this.invoke(event.type, event); - }, -}); + } +} -cc.EventTarget = EventTarget; -export default EventTarget; +/* tslint:disable:no-string-literal */ +cc['EventTarget'] = EventTarget; diff --git a/cocos/core/event/event.ts b/cocos/core/event/event.ts index ac80e2e6d9..01af21145a 100644 --- a/cocos/core/event/event.ts +++ b/cocos/core/event/event.ts @@ -29,89 +29,134 @@ * !#zh 包含事件相关信息的对象。 * @class Event */ -class Event { +export default class Event { + // Event types + /** - * @method constructor - * @param {String} type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" - * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not + * !#en Code for event without type. + * !#zh 没有类型的事件 */ - constructor (type, bubbles) { - /** - * !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". - * !#zh 事件类型。 - * @property type - * @type {String} - */ + public static NO_TYPE = 'no_type'; + + /** + * !#en The type code of Touch event. + * !#zh 触摸事件类型 + */ + public static TOUCH = 'touch'; + /** + * !#en The type code of Mouse event. + * !#zh 鼠标事件类型 + */ + public static MOUSE = 'mouse'; + /** + * !#en The type code of Keyboard event. + * !#zh 键盘事件类型 + */ + public static KEYBOARD = 'keyboard'; + /** + * !#en The type code of Acceleration event. + * !#zh 加速器事件类型 + */ + public static ACCELERATION = 'acceleration'; + + // Event phases + + /** + * !#en Events not currently dispatched are in this phase + * !#zh 尚未派发事件阶段 + */ + public static NONE = 0; + + /** + * !#en + * The capturing phase comprises the journey from the root to the last node before the event target's node + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 + */ + public static CAPTURING_PHASE = 1; + + /** + * !#en + * The target phase comprises only the event target node + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 目标阶段仅包括事件目标节点。 + */ + public static AT_TARGET = 2; + + /** + * !#en + * The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 + */ + public static BUBBLING_PHASE = 3; + + /** + * !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". + * !#zh 事件类型。 + */ + public type: string; + + /** + * !#en Indicate whether the event bubbles up through the tree or not. + * !#zh 表示该事件是否进行冒泡。 + */ + public bubbles: boolean; + + /** + * !#en A reference to the target to which the event was originally dispatched. + * !#zh 最初事件触发的目标 + */ + public target: Object | null = null; + + /** + * !#en A reference to the currently registered target for the event. + * !#zh 当前目标 + */ + public currentTarget: Object | null = null; + + /** + * !#en + * Indicates which phase of the event flow is currently being evaluated. + * Returns an integer value represented by 4 constants: + * - Event.NONE = 0 + * - Event.CAPTURING_PHASE = 1 + * - Event.AT_TARGET = 2 + * - Event.BUBBLING_PHASE = 3 + * The phases are explained in the [section 3.1, Event dispatch and DOM event flow] + * (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. + * !#zh 事件阶段 + */ + public eventPhase = 0; + + /* + * Indicates whether or not event.stopPropagation() has been called on the event. + */ + private _propagationStopped = false; + + /* + * Indicates whether or not event.stopPropagationImmediate() has been called on the event. + */ + private _propagationImmediateStopped = false; + + /** + * @param type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" + * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (type: string, bubbles?: boolean) { this.type = type; - - /** - * !#en Indicate whether the event bubbles up through the tree or not. - * !#zh 表示该事件是否进行冒泡。 - * @property bubbles - * @type {Boolean} - */ this.bubbles = !!bubbles; - - /** - * !#en A reference to the target to which the event was originally dispatched. - * !#zh 最初事件触发的目标 - * @property target - * @type {Object} - */ - this.target = null; - - /** - * !#en A reference to the currently registered target for the event. - * !#zh 当前目标 - * @property currentTarget - * @type {Object} - */ - this.currentTarget = null; - - /** - * !#en - * Indicates which phase of the event flow is currently being evaluated. - * Returns an integer value represented by 4 constants: - * - Event.NONE = 0 - * - Event.CAPTURING_PHASE = 1 - * - Event.AT_TARGET = 2 - * - Event.BUBBLING_PHASE = 3 - * The phases are explained in the [section 3.1, Event dispatch and DOM event flow] - * (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. - * !#zh 事件阶段 - * @property eventPhase - * @type {Number} - */ - this.eventPhase = 0; - - /* - * Indicates whether or not event.stopPropagation() has been called on the event. - * @property _propagationStopped - * @type {Boolean} - * @private - */ - this._propagationStopped = false; - - /* - * Indicates whether or not event.stopPropagationImmediate() has been called on the event. - * @property _propagationImmediateStopped - * @type {Boolean} - * @private - */ - this._propagationImmediateStopped = false; } /** * !#en Reset the event for being stored in the object pool. * !#zh 重置对象池中存储的事件。 - * @method unuse - * @returns {String} */ public unuse () { - this.type = cc.Event.NO_TYPE; + this.type = Event.NO_TYPE; this.target = null; this.currentTarget = null; - this.eventPhase = cc.Event.NONE; + this.eventPhase = Event.NONE; this._propagationStopped = false; this._propagationImmediateStopped = false; } @@ -119,10 +164,8 @@ class Event { /** * !#en Reuse the event for being used again by the object pool. * !#zh 用于对象池再次使用的事件。 - * @method reuse - * @returns {String} */ - public reuse (type, bubbles) { + public reuse (type: string, bubbles?: boolean) { this.type = type; this.bubbles = bubbles || false; } @@ -130,7 +173,6 @@ class Event { /** * !#en Stops propagation for current event. * !#zh 停止传递当前事件。 - * @method stopPropagation */ public stopPropagation () { this._propagationStopped = true; @@ -140,7 +182,6 @@ class Event { * !#en Stops propagation for current event immediately, * the event won't even be dispatched to the listeners attached in the current target. * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 - * @method stopPropagationImmediate */ public stopPropagationImmediate () { this._propagationImmediateStopped = true; @@ -149,8 +190,6 @@ class Event { /** * !#en Checks whether the event has been stopped. * !#zh 检查该事件是否已经停止传递. - * @method isStopped - * @returns {Boolean} */ public isStopped () { return this._propagationStopped || this._propagationImmediateStopped; @@ -164,8 +203,7 @@ class Event { * It returns 0 when the listener is associated with fixed priority. *

* !#zh 获取当前目标节点 - * @method getCurrentTarget - * @returns {Node} The target with which the event associates. + * @returns The target with which the event associates. */ public getCurrentTarget () { return this.currentTarget; @@ -174,96 +212,11 @@ class Event { /** * !#en Gets the event type. * !#zh 获取事件类型 - * @method getType - * @returns {String} */ public getType () { return this.type; } } -// event type -/** - * !#en Code for event without type. - * !#zh 没有类型的事件 - * @property NO_TYPE - * @static - * @type {string} - */ -Event.NO_TYPE = 'no_type'; - -/** - * !#en The type code of Touch event. - * !#zh 触摸事件类型 - * @property TOUCH - * @static - * @type {String} - */ -Event.TOUCH = 'touch'; -/** - * !#en The type code of Mouse event. - * !#zh 鼠标事件类型 - * @property MOUSE - * @static - * @type {String} - */ -Event.MOUSE = 'mouse'; -/** - * !#en The type code of Keyboard event. - * !#zh 键盘事件类型 - * @property KEYBOARD - * @static - * @type {String} - */ -Event.KEYBOARD = 'keyboard'; -/** - * !#en The type code of Acceleration event. - * !#zh 加速器事件类型 - * @property ACCELERATION - * @static - * @type {String} - */ -Event.ACCELERATION = 'acceleration'; - -// event phase -/** - * !#en Events not currently dispatched are in this phase - * !#zh 尚未派发事件阶段 - * @property NONE - * @type {Number} - * @static - */ -Event.NONE = 0; -/** - * !#en - * The capturing phase comprises the journey from the root to the last node before the event target's node - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 - * @property CAPTURING_PHASE - * @type {Number} - * @static - */ -Event.CAPTURING_PHASE = 1; -/** - * !#en - * The target phase comprises only the event target node - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 目标阶段仅包括事件目标节点。 - * @property AT_TARGET - * @type {Number} - * @static - */ -Event.AT_TARGET = 2; -/** - * !#en - * The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 - * @property BUBBLING_PHASE - * @type {Number} - * @static - */ -Event.BUBBLING_PHASE = 3; - -cc.Event = Event; -export default Event; +/* tslint:disable:no-string-literal */ +cc['Event'] = Event; From c8eb77a7bdb984f7eae682739b4dafe2f3954533 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 7 Jan 2019 11:28:02 +0800 Subject: [PATCH 060/267] rename to ts & tslint-autofix --- .../{texture-cube.js => texture-cube.ts} | 276 +++++++++--------- .../assets/{image-asset.js => image-asset.ts} | 66 ++--- .../{render-texture.js => render-texture.ts} | 48 ++- cocos/assets/{texture-2d.js => texture-2d.ts} | 76 ++--- .../{texture-base.js => texture-base.ts} | 152 +++++----- 5 files changed, 308 insertions(+), 310 deletions(-) rename cocos/3d/assets/{texture-cube.js => texture-cube.ts} (87%) rename cocos/assets/{image-asset.js => image-asset.ts} (83%) rename cocos/assets/{render-texture.js => render-texture.ts} (75%) rename cocos/assets/{texture-2d.js => texture-2d.ts} (87%) rename cocos/assets/{texture-base.js => texture-base.ts} (87%) diff --git a/cocos/3d/assets/texture-cube.js b/cocos/3d/assets/texture-cube.ts similarity index 87% rename from cocos/3d/assets/texture-cube.js rename to cocos/3d/assets/texture-cube.ts index 8b22687e16..9854377f82 100644 --- a/cocos/3d/assets/texture-cube.js +++ b/cocos/3d/assets/texture-cube.ts @@ -23,10 +23,10 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import GFXTextureCube from '../../renderer/gfx/texture-cube'; +import ImageAsset from '../../assets/image-asset'; import TextureBase from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; -import ImageAsset from '../../assets/image-asset'; +import GFXTextureCube from '../../renderer/gfx/texture-cube'; /** * @typedef {import("../../assets/texture-2d")} Texture2D @@ -46,32 +46,18 @@ const FaceIndex = cc.Enum({ top: 2, bottom: 3, front: 4, - back: 5 + back: 5, }); @ccclass('cc.TextureCube') export default class TextureCube extends TextureBase { - /** - * @type {Mipmap[]} - */ - @property - _mipmaps = []; - - constructor() { - super(); - - /** - * @type {GFXTextureCube} - */ - this._texture = null; - } /** * Gets the mipmap images. * Note that the result do not contains the auto generated mipmaps. * @type {Mipmap[]} */ - get mipmaps() { + get mipmaps () { return this._mipmaps; } @@ -79,7 +65,7 @@ export default class TextureCube extends TextureBase { * Sets the mipmaps images. * @type {Mipmap[]} */ - set mipmaps(value) { + set mipmaps (value) { this._setMipmaps(value); } @@ -87,7 +73,7 @@ export default class TextureCube extends TextureBase { * Gets the mipmap image at level 0. * @type {Mipmap} */ - get image() { + get image () { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; } @@ -95,121 +81,15 @@ export default class TextureCube extends TextureBase { * Sets the mipmap images as a single mipmap image. * @type {Mipmap} */ - set image(value) { + set image (value) { this.mipmaps = [value]; } - /** - * Gets the underlying texture object. - */ - getImpl () { - return this._texture; - } - - /** - * !#en - * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
- * After destroy, this object is not usable any more. - * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. - * !#zh - * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
- * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} inherit from the CCObject - */ - destroy () { - this.releaseTexture(); - // TODO cc.textureUtil ? - // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url - return super.destroy(); - } - - /** - * !#en - * Release texture, please use destroy instead. - * !#zh 释放纹理,请使用 destroy 替代。 - * @method releaseTexture - * @deprecated since v2.0 - */ - releaseTexture () { - this._setMipmaps([]); - this._texture && this._texture.destroy(); - } - - /** - * Sets the _mipmaps to specified value, and updates the width and height accordingly. - * If available, synchronize the mipmap data to underlying texture. - * @param {Mipmap[]} mipmaps - */ - _setMipmaps(mipmaps) { - this._mipmaps = mipmaps; - if (mipmaps.length === 0) { - super.update({ - width: 0, - height: 0 - }); - } else { - super.update({ - width: this._mipmaps[0].front.width, - height: this._mipmaps[0].front.height, - format: this._mipmaps[0].front._format - }); - } - - let counter = 0; - const inc = () => { - ++counter; - if (counter === this._mipmaps.length * 6) { - this._updateMipmaps(this._mipmaps.map(mipmap => TextureCube._toMipmapArray(mipmap))); - } - }; - mipmaps.forEach(mipmap => { - TextureCube._forEachFace(mipmap, face => { - if (face.loaded) { - inc(); - } else { - face.addEventListener("load", () => inc()); - } - }); - }); - } - - /** - * Updates mipmaps of the underlying texture. - * @param {ImageSource[][]} mipmapSources - */ - _updateMipmaps(mipmapSources) { - const opts = this._getOpts(); - opts.images = mipmapSources; - if (!this._texture) { - this._texture = new GFXTextureCube(cc.game._renderContext, opts); - } else { - this._texture.update(opts); - } - } - - /** - * Update texture options, not available in Canvas render mode. - * image, format, premultiplyAlpha can not be updated in native. - * @method update - */ - update (options) { - if (!options) return; - - super.update(options); - - // TODO: options.image - - if (this._texture) { - this._texture.update(options); - } - } - /** * @param {Mipmap} mipmap * @return {ImageSource[]} */ - static _toMipmapArray(mipmap) { + public static _toMipmapArray (mipmap) { /** @type {ImageSource[]} */ const result = new Array(); result[FaceIndex.front] = mipmap.front.data; @@ -225,8 +105,8 @@ export default class TextureCube extends TextureBase { * @param {Mipmap} mipmap * @param {(face: ImageAsset) => void} callback */ - static _forEachFace(mipmap, callback) { - for (let face in mipmap) { + public static _forEachFace (mipmap, callback) { + for (const face in mipmap) { callback(mipmap[face]); } } @@ -234,34 +114,154 @@ export default class TextureCube extends TextureBase { /** * @param {Texture2D[]} textures */ - static fromTexture2DArray(textures, out) { - let res = [], mips = textures.length / 6; + public static fromTexture2DArray (textures, out) { + const res = [], mips = textures.length / 6; for (let i = 0; i < mips; i++) { res.push(textures.splice(0, 6).reduce((acc, img, i) => { acc[FaceIndex[i]] = img.image; return acc; }, {})); } - if (!out) out = new TextureCube(); + if (!out) { out = new TextureCube(); } out.mipmaps = res; return out; } + /** + * @type {Mipmap[]} + */ + @property + public _mipmaps = []; - _serialize() { + constructor () { + super(); + + /** + * @type {GFXTextureCube} + */ + this._texture = null; + } + + /** + * Gets the underlying texture object. + */ + public getImpl () { + return this._texture; + } + + /** + * !#en + * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more. + * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. + * !#zh + * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + * @method destroy + * @return {Boolean} inherit from the CCObject + */ + public destroy () { + this.releaseTexture(); + // TODO cc.textureUtil ? + // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url + return super.destroy(); + } + + /** + * !#en + * Release texture, please use destroy instead. + * !#zh 释放纹理,请使用 destroy 替代。 + * @method releaseTexture + * @deprecated since v2.0 + */ + public releaseTexture () { + this._setMipmaps([]); + this._texture && this._texture.destroy(); + } + + /** + * Sets the _mipmaps to specified value, and updates the width and height accordingly. + * If available, synchronize the mipmap data to underlying texture. + * @param {Mipmap[]} mipmaps + */ + public _setMipmaps (mipmaps) { + this._mipmaps = mipmaps; + if (mipmaps.length === 0) { + super.update({ + width: 0, + height: 0, + }); + } else { + super.update({ + width: this._mipmaps[0].front.width, + height: this._mipmaps[0].front.height, + format: this._mipmaps[0].front._format, + }); + } + + let counter = 0; + const inc = () => { + ++counter; + if (counter === this._mipmaps.length * 6) { + this._updateMipmaps(this._mipmaps.map((mipmap) => TextureCube._toMipmapArray(mipmap))); + } + }; + mipmaps.forEach((mipmap) => { + TextureCube._forEachFace(mipmap, (face) => { + if (face.loaded) { + inc(); + } else { + face.addEventListener('load', () => inc()); + } + }); + }); + } + + /** + * Updates mipmaps of the underlying texture. + * @param {ImageSource[][]} mipmapSources + */ + public _updateMipmaps (mipmapSources) { + const opts = this._getOpts(); + opts.images = mipmapSources; + if (!this._texture) { + this._texture = new GFXTextureCube(cc.game._renderContext, opts); + } else { + this._texture.update(opts); + } + } + + /** + * Update texture options, not available in Canvas render mode. + * image, format, premultiplyAlpha can not be updated in native. + * @method update + */ + public update (options) { + if (!options) { return; } + + super.update(options); + + // TODO: options.image + + if (this._texture) { + this._texture.update(options); + } + } + + public _serialize () { return { base: super._serialize(), - mipmaps: this._mipmaps.map(mipmap => {return { + mipmaps: this._mipmaps.map((mipmap) => {return { front: mipmap.front._uuid, back: mipmap.back._uuid, left: mipmap.left._uuid, right: mipmap.right._uuid, top: mipmap.top._uuid, bottom: mipmap.bottom._uuid, - };}) + }; }), }; } - _deserialize (data, handle) { + public _deserialize (data, handle) { super._deserialize(data.base); this._mipmaps = new Array(data.mipmaps.length); @@ -277,7 +277,7 @@ export default class TextureCube extends TextureBase { } } - onLoaded() { + public onLoaded () { this.mipmaps = this._mipmaps; } } diff --git a/cocos/assets/image-asset.js b/cocos/assets/image-asset.ts similarity index 83% rename from cocos/assets/image-asset.js rename to cocos/assets/image-asset.ts index 9644ebed06..89bdf0e92b 100644 --- a/cocos/assets/image-asset.js +++ b/cocos/assets/image-asset.ts @@ -22,8 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -//@ts-check -import {ccclass, property} from "../core/data/class-decorator"; +// @ts-check +import {ccclass, property} from '../core/data/class-decorator'; import EventTarget from '../core/event/event-target'; import {addon} from '../core/utils/js'; @@ -39,12 +39,12 @@ const CHAR_CODE_0 = 48; // '0' @ccclass('cc.ImageAsset') export default class ImageAsset extends cc.Asset { - static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; + public static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; /** * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} nativeAsset */ - constructor(nativeAsset = undefined) { + constructor (nativeAsset = undefined) { super(); EventTarget.call(this); @@ -58,7 +58,7 @@ export default class ImageAsset extends cc.Asset { * @readonly */ // TODO - use nativeUrl directly - this.url = ""; + this.url = ''; /** * @type {HTMLCanvasElement | HTMLImageElement | RawImageData} @@ -68,7 +68,7 @@ export default class ImageAsset extends cc.Asset { width: 0, height: 0, format: 0, - _compressed: false + _compressed: false, }; if (CC_EDITOR) { @@ -79,12 +79,12 @@ export default class ImageAsset extends cc.Asset { this._nativeAsset = nativeAsset; } } - + /** * @type {HTMLCanvasElement | HTMLImageElement | RawImageData} */ @property({ - override: true + override: true, }) get _nativeAsset () { // maybe returned to pool in webgl @@ -101,14 +101,14 @@ export default class ImageAsset extends cc.Asset { /** * @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView} */ - get data() { + get data () { return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data; } /** * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data */ - reset(data) { + public reset (data) { if (!(data instanceof HTMLElement)) { this._nativeData = Object.create(data); this._onDataComplete(); @@ -128,15 +128,15 @@ export default class ImageAsset extends cc.Asset { } } - get width() { + get width () { return this._nativeData.width; } - get height() { + get height () { return this._nativeData.height; } - get format() { + get format () { if (this._nativeData instanceof HTMLElement) { return undefined; } @@ -154,20 +154,20 @@ export default class ImageAsset extends cc.Asset { // SERIALIZATION - _serialize () { - let extId = ""; + public _serialize () { + let extId = ''; let exportedExts = this._exportedExts; if (!exportedExts && this._native) { exportedExts = [this._native]; } if (exportedExts) { - let exts = []; + const exts = []; for (let i = 0; i < exportedExts.length; i++) { - let extId = ""; - let ext = exportedExts[i]; + let extId = ''; + const ext = exportedExts[i]; if (ext) { // ext@format - let extFormat = ext.split('@'); + const extFormat = ext.split('@'); extId = ImageAsset.extnames.indexOf(extFormat[0]); if (extId < 0) { extId = ext; @@ -180,27 +180,27 @@ export default class ImageAsset extends cc.Asset { } extId = exts.join('_'); } - return "" + extId; + return '' + extId; } - _deserialize (data, handle) { - let fields = data.split(','); + public _deserialize (data, handle) { + const fields = data.split(','); // decode extname - var extIdStr = fields[0]; + const extIdStr = fields[0]; if (extIdStr) { - let extIds = extIdStr.split('_'); + const extIds = extIdStr.split('_'); let extId = 999; let ext = ''; let format = this._format; - let SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS; + const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS; for (let i = 0; i < extIds.length; i++) { - let extFormat = extIds[i].split('@'); + const extFormat = extIds[i].split('@'); let tmpExt = extFormat[0]; tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0; tmpExt = ImageAsset.extnames[tmpExt] || extFormat; - let index = SupportTextureFormats.indexOf(tmpExt); + const index = SupportTextureFormats.indexOf(tmpExt); if (index !== -1 && index < extId) { extId = index; ext = tmpExt; @@ -214,19 +214,19 @@ export default class ImageAsset extends cc.Asset { } // preset uuid to get correct nativeUrl - let loadingItem = handle.customEnv; - let uuid = loadingItem && loadingItem.uuid; + const loadingItem = handle.customEnv; + const uuid = loadingItem && loadingItem.uuid; if (uuid) { this._uuid = uuid; - var url = this.nativeUrl; + const url = this.nativeUrl; this.url = url; } } } - _onDataComplete() { + public _onDataComplete () { this.loaded = true; - this.emit("load"); + this.emit('load'); } } @@ -240,4 +240,4 @@ export default class ImageAsset extends cc.Asset { */ addon(ImageAsset.prototype, EventTarget.prototype); -cc.ImageAsset = ImageAsset; \ No newline at end of file +cc.ImageAsset = ImageAsset; diff --git a/cocos/assets/render-texture.js b/cocos/assets/render-texture.ts similarity index 75% rename from cocos/assets/render-texture.js rename to cocos/assets/render-texture.ts index 5b3302620f..e63fdc39ec 100644 --- a/cocos/assets/render-texture.js +++ b/cocos/assets/render-texture.ts @@ -1,6 +1,6 @@ +import { ccclass } from '../core/data/class-decorator'; import gfx from '../renderer/gfx'; import Texture2D from './texture-2d'; -import { ccclass } from '../core/data/class-decorator'; /** * Render textures are textures that can be rendered to. @@ -25,44 +25,42 @@ export default class RenderTexture extends Texture2D { * @param {Number} [depthStencilFormat] * @method initWithSize */ - initWithSize (width, height, depthStencilFormat) { + public initWithSize (width, height, depthStencilFormat) { this.width = Math.floor(width || cc.visibleRect.width); this.height = Math.floor(height || cc.visibleRect.height); this._resetUnderlyingMipmaps(); - let opts = { + const opts = { colors: [ this._texture ], }; if (depthStencilFormat) { - if (this.depthStencilBuffer) this.depthStencilBuffer.destroy(); - let depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height); + if (this.depthStencilBuffer) { this.depthStencilBuffer.destroy(); } + const depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height); if (depthStencilFormat === gfx.RB_FMT_D24S8) { opts.depthStencil = depthStencilBuffer; - } - else if (depthStencilFormat === gfx.RB_FMT_S8) { + } else if (depthStencilFormat === gfx.RB_FMT_S8) { opts.stencil = depthStencilBuffer; - } - else if (depthStencilFormat === gfx.RB_FMT_D16) { + } else if (depthStencilFormat === gfx.RB_FMT_D16) { opts.depth = depthStencilBuffer; } this.depthStencilBuffer = depthStencilBuffer; this.depthStencilFormat = depthStencilFormat; } - if (this._framebuffer) this._framebuffer.destroy(); + if (this._framebuffer) { this._framebuffer.destroy(); } this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts); this.loaded = true; - this.emit("load"); + this.emit('load'); } - updateSize(width, height) { + public updateSize (width, height) { this.width = Math.floor(width || cc.visibleRect.width); this.height = Math.floor(height || cc.visibleRect.height); this._resetUnderlyingMipmaps(); - let rbo = this.depthStencilBuffer; - if (rbo) rbo.update(this.width, this.height); + const rbo = this.depthStencilBuffer; + if (rbo) { rbo.update(this.width, this.height); } this._framebuffer._width = width; this._framebuffer._height = height; } @@ -74,8 +72,8 @@ export default class RenderTexture extends Texture2D { * @param {Number} x * @param {Number} y */ - drawTextureAt (texture, x, y) { - if (!texture._image) return; + public drawTextureAt (texture, x, y) { + if (!texture._image) { return; } this._texture.updateSubImage({ x, y, @@ -84,8 +82,8 @@ export default class RenderTexture extends Texture2D { height: texture.height, level: 0, flipY: false, - premultiplyAlpha: texture._premultiplyAlpha - }) + premultiplyAlpha: texture._premultiplyAlpha, + }); } /** @@ -106,17 +104,17 @@ export default class RenderTexture extends Texture2D { * @param {Number} [h] * @return {Uint8Array} */ - readPixels (data, x, y, w, h) { - if (!this._framebuffer || !this._texture) return data; + public readPixels (data, x, y, w, h) { + if (!this._framebuffer || !this._texture) { return data; } x = x || 0; y = y || 0; - let width = w || this.width; - let height = h || this.height; + const width = w || this.width; + const height = h || this.height; data = data || new Uint8Array(width * height * 4); - let gl = cc.game._renderContext._gl; - let oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); + const gl = cc.game._renderContext._gl; + const oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID); gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO); @@ -124,7 +122,7 @@ export default class RenderTexture extends Texture2D { return data; } - destroy () { + public destroy () { super.destroy(); if (this._framebuffer) { this._framebuffer.destroy(); diff --git a/cocos/assets/texture-2d.js b/cocos/assets/texture-2d.ts similarity index 87% rename from cocos/assets/texture-2d.js rename to cocos/assets/texture-2d.ts index 544984835b..d9468ba218 100644 --- a/cocos/assets/texture-2d.js +++ b/cocos/assets/texture-2d.ts @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import GFXTexture2D from '../renderer/gfx/texture-2d'; import {ccclass, property} from '../core/data/class-decorator'; -import TextureBase from './texture-base'; +import GFXTexture2D from '../renderer/gfx/texture-2d'; import ImageAsset from './image-asset'; +import TextureBase from './texture-base'; /** * @typedef {import("./texture-base").ImageSource} ImageSource @@ -48,15 +48,15 @@ import ImageAsset from './image-asset'; @ccclass('cc.Texture2D') export default class Texture2D extends TextureBase { @property({ - override: true + override: true, }) - _flipY = true; - + public _flipY = true; + /** * @type {ImageAsset[]} */ @property([ImageAsset]) - _mipmaps = []; + public _mipmaps = []; constructor () { super(); @@ -72,7 +72,7 @@ export default class Texture2D extends TextureBase { * Note that the result do not contains the auto generated mipmaps. * @return {ImageAsset[]} */ - get mipmaps() { + get mipmaps () { return this._mipmaps; } @@ -80,7 +80,7 @@ export default class Texture2D extends TextureBase { * Sets the mipmaps images. * @param {ImageAsset[]} value */ - set mipmaps(value) { + set mipmaps (value) { this._setMipmaps(value); } @@ -88,7 +88,7 @@ export default class Texture2D extends TextureBase { * Gets the mipmap image at level 0. * @return {ImageAsset} */ - get image() { + get image () { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; } @@ -96,22 +96,22 @@ export default class Texture2D extends TextureBase { * Sets the mipmap images as a single mipmap image. * @param {ImageAsset} value */ - set image(value) { + set image (value) { this.mipmaps = [value]; } /** * Gets the underlying texture object. */ - getImpl () { + public getImpl () { return this._texture; } /** * Returns the string representation of this texture. */ - toString () { - return this._mipmaps.length !== 0 ? this._mipmaps[0].url : ""; + public toString () { + return this._mipmaps.length !== 0 ? this._mipmaps[0].url : ''; } /** @@ -120,7 +120,7 @@ export default class Texture2D extends TextureBase { * @method update * @param {TextureUpdateOpts} options */ - update (options) { + public update (options) { if (!options) { return; } @@ -132,14 +132,14 @@ export default class Texture2D extends TextureBase { } if (options.images !== undefined && options.images.length !== 0) { - this._setMipmaps(options.images.map(image => { + this._setMipmaps(options.images.map((image) => { const mipmap = new ImageAsset(); mipmap.reset(image instanceof HTMLElement ? image : { _data: image, width: this.width, height: this.height, format: this._format, - _compressed: false + _compressed: false, }); return mipmap; })); @@ -154,7 +154,7 @@ export default class Texture2D extends TextureBase { * * @param {ImageSource} source */ - updateImage(source) { + public updateImage (source) { this.updateMipmaps([source]); } @@ -166,7 +166,7 @@ export default class Texture2D extends TextureBase { * If the range specified by [firstLevel, firstLevel + sources.length) exceeds * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated. */ - updateMipmaps(sources, firstLevel = 0) { + public updateMipmaps (sources, firstLevel = 0) { if (firstLevel >= sources.length) { return; } @@ -181,15 +181,15 @@ export default class Texture2D extends TextureBase { width: mipmap.width, height: mipmap.height, format: mipmap._format, - _compressed: false + _compressed: false, }); this._texture.updateImage({ width: this.width, height: this.height, - level: level, + level, image: sources[i], flipY: false, - premultiplyAlpha: false + premultiplyAlpha: false, }); } } @@ -202,8 +202,8 @@ export default class Texture2D extends TextureBase { * @return {HTMLImageElement|HTMLCanvasElement} * @deprecated Use this.image.data instead. */ - getHtmlElementObj () { - return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data: null; + public getHtmlElementObj () { + return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data : null; } /** @@ -217,7 +217,7 @@ export default class Texture2D extends TextureBase { * @method destroy * @return {Boolean} inherit from the CCObject */ - destroy () { + public destroy () { this.releaseTexture(); // TODO cc.textureUtil ? // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url @@ -231,8 +231,8 @@ export default class Texture2D extends TextureBase { * @method description * @returns {String} */ - description () { - return ""; + public description () { + return ''; } /** @@ -242,7 +242,7 @@ export default class Texture2D extends TextureBase { * @method releaseTexture * @deprecated since v2.0, use destroy instead. */ - releaseTexture () { + public releaseTexture () { this._setMipmaps([]); this._texture && this._texture.destroy(); } @@ -252,19 +252,19 @@ export default class Texture2D extends TextureBase { * If available, synchronize the mipmap data to underlying texture. * @param {ImageAsset[]} mipmaps */ - _setMipmaps(mipmaps) { + public _setMipmaps (mipmaps) { this._mipmaps = mipmaps; if (mipmaps.length === 0) { super.update({ width: 0, - height: 0 + height: 0, }); } else { const level0 = this._mipmaps[0]; super.update({ width: level0.width, height: level0.height, - format: level0._format + format: level0._format, }); } @@ -272,14 +272,14 @@ export default class Texture2D extends TextureBase { const inc = () => { ++counter; if (counter === mipmaps.length) { - this._resetUnderlyingMipmaps(mipmaps.map(mipmap => mipmap.data)); + this._resetUnderlyingMipmaps(mipmaps.map((mipmap) => mipmap.data)); } }; - mipmaps.forEach(mipmap => { + mipmaps.forEach((mipmap) => { if (mipmap.loaded) { inc(); } else { - mipmap.addEventListener("load", () => { + mipmap.addEventListener('load', () => { inc(); }); } @@ -290,7 +290,7 @@ export default class Texture2D extends TextureBase { * Resets sources and amount of the underlying texture's the mipmaps. * @param {ImageSource[]} mipmapSources */ - _resetUnderlyingMipmaps(mipmapSources = [null]) { + public _resetUnderlyingMipmaps (mipmapSources = [null]) { const opts = this._getOpts(); opts.images = mipmapSources; if (!this._texture) { @@ -300,14 +300,14 @@ export default class Texture2D extends TextureBase { } } - _serialize() { + public _serialize () { return { base: super._serialize(), - mipmaps: this._mipmaps.map(mipmap => mipmap._uuid) + mipmaps: this._mipmaps.map((mipmap) => mipmap._uuid), }; } - _deserialize (data, handle) { + public _deserialize (data, handle) { super._deserialize(data.base); this._mipmaps = new Array(data.mipmaps.length); @@ -319,7 +319,7 @@ export default class Texture2D extends TextureBase { } } - onLoaded() { + public onLoaded () { this.mipmaps = this._mipmaps; } } diff --git a/cocos/assets/texture-base.js b/cocos/assets/texture-base.ts similarity index 87% rename from cocos/assets/texture-base.js rename to cocos/assets/texture-base.ts index 3a9a578b40..1c726fefa7 100644 --- a/cocos/assets/texture-base.js +++ b/cocos/assets/texture-base.ts @@ -24,13 +24,13 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check +import {ccclass, property} from '../core/data/class-decorator'; import EventTarget from '../core/event/event-target'; import IDGenerator from '../core/utils/id-generator'; -import Enum from '../core/value-types/enum'; import {addon} from '../core/utils/js'; +import Enum from '../core/value-types/enum'; import {enums} from '../renderer/gfx/enums'; -import { Asset } from './asset'; -import {ccclass, property} from '../core/data/class-decorator'; +import Asset from './CCAsset'; /** * @typedef {import("../renderer/gfx/texture-2d").HTMLImageSource} HTMLImageSource @@ -42,7 +42,7 @@ import {ccclass, property} from '../core/data/class-decorator'; * @exports TextureUpdateOpts */ -let _images = []; +const _images = []; const CHAR_CODE_1 = 49; // '1' @@ -52,7 +52,7 @@ const GL_REPEAT = 10497; // gl.REPEAT const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT -var idGenerator = new IDGenerator('Tex'); +const idGenerator = new IDGenerator('Tex'); /** * The texture pixel format, default value is RGBA8888, @@ -180,7 +180,7 @@ export const WrapMode = Enum({ * @type {Number} * @readonly */ - MIRRORED_REPEAT: GL_MIRRORED_REPEAT + MIRRORED_REPEAT: GL_MIRRORED_REPEAT, }); /** @@ -201,7 +201,7 @@ export const Filter = Enum({ * @type {Number} * @readonly */ - NEAREST: GL_NEAREST + NEAREST: GL_NEAREST, }); const FilterIndex = { @@ -212,7 +212,7 @@ const FilterIndex = { /** * @type TextureUpdateOpts */ -let _sharedOpts = { +const _sharedOpts = { width: undefined, height: undefined, minFilter: undefined, @@ -226,10 +226,10 @@ let _sharedOpts = { image: undefined, flipY: undefined, premultiplyAlpha: undefined, - anisotropy: undefined + anisotropy: undefined, }; function _getSharedOptions () { - for (var key in _sharedOpts) { + for (const key in _sharedOpts) { _sharedOpts[key] = undefined; } _images.length = 0; @@ -240,49 +240,49 @@ function _getSharedOptions () { @ccclass('cc.TextureBase') export default class TextureBase extends Asset { - @property - _genMipmap = false; - @property - _format = PixelFormat.RGBA8888; + public static PixelFormat = PixelFormat; - @property - _premultiplyAlpha = false; + public static WrapMode = WrapMode; - @property - _flipY = false; - - @property - _minFilter = Filter.LINEAR; - - @property - _magFilter = Filter.LINEAR; - - @property - _mipFilter = Filter.LINEAR; - - @property - _wrapS = WrapMode.CLAMP_TO_EDGE; - - @property - _wrapT = WrapMode.CLAMP_TO_EDGE; - - @property - _anisotropy = 1; - - static PixelFormat = PixelFormat; - - static WrapMode = WrapMode; - - static Filter = Filter; + public static Filter = Filter; /** * * @param {TextureBase} texture */ - static _isCompressed (texture) { + public static _isCompressed (texture) { return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; } + @property + public _genMipmap = false; + + @property + public _format = PixelFormat.RGBA8888; + + @property + public _premultiplyAlpha = false; + + @property + public _flipY = false; + + @property + public _minFilter = Filter.LINEAR; + + @property + public _magFilter = Filter.LINEAR; + + @property + public _mipFilter = Filter.LINEAR; + + @property + public _wrapS = WrapMode.CLAMP_TO_EDGE; + + @property + public _wrapT = WrapMode.CLAMP_TO_EDGE; + + @property + public _anisotropy = 1; constructor () { super(); @@ -324,7 +324,7 @@ export default class TextureBase extends Asset { this.height = 0; } - getId () { + public getId () { return this._id; } @@ -333,7 +333,7 @@ export default class TextureBase extends Asset { * @method update * @param {TextureUpdateOpts} options */ - update (options) { + public update (options) { if (!options) { return; } @@ -379,8 +379,8 @@ export default class TextureBase extends Asset { } } - _getOpts() { - let opts = _getSharedOptions(); + public _getOpts () { + const opts = _getSharedOptions(); opts.width = this.width; opts.height = this.height; opts.mipmap = this._genMipmap; @@ -403,8 +403,8 @@ export default class TextureBase extends Asset { * @method getPixelFormat * @return {Number} */ - getPixelFormat () { - //support only in WebGl rendering mode + public getPixelFormat () { + // support only in WebGl rendering mode return this._format; } @@ -415,7 +415,7 @@ export default class TextureBase extends Asset { * @method hasPremultipliedAlpha * @return {Boolean} */ - hasPremultipliedAlpha () { + public hasPremultipliedAlpha () { return this._premultiplyAlpha || false; } @@ -425,7 +425,7 @@ export default class TextureBase extends Asset { * @method getAnisotropy * @return {Number} */ - getAnisotropy() { + public getAnisotropy () { return this._anisotropy; } @@ -436,7 +436,7 @@ export default class TextureBase extends Asset { * @method hasMipmap * @return {Boolean} */ - genMipmap () { + public genMipmap () { return this._genMipmap || false; } @@ -449,9 +449,9 @@ export default class TextureBase extends Asset { * @param {WrapMode} wrapS * @param {WrapMode} wrapT */ - setWrapMode (wrapS, wrapT) { + public setWrapMode (wrapS, wrapT) { if (this._wrapS !== wrapS || this._wrapT !== wrapT) { - var opts = _getSharedOptions(); + const opts = _getSharedOptions(); opts.wrapS = wrapS; opts.wrapT = wrapT; this.update(opts); @@ -465,9 +465,9 @@ export default class TextureBase extends Asset { * @param {Filter} minFilter * @param {Filter} magFilter */ - setFilters (minFilter, magFilter) { + public setFilters (minFilter, magFilter) { if (this._minFilter !== minFilter || this._magFilter !== magFilter) { - var opts = _getSharedOptions(); + const opts = _getSharedOptions(); opts.minFilter = minFilter; opts.magFilter = magFilter; this.update(opts); @@ -480,9 +480,9 @@ export default class TextureBase extends Asset { * @method setMipFilter * @param {Filter} mipFilter */ - setMipFilter (mipFilter) { + public setMipFilter (mipFilter) { if (this._mipFilter !== mipFilter) { - var opts = _getSharedOptions(); + const opts = _getSharedOptions(); opts.mipFilter = mipFilter; this.update(opts); } @@ -495,9 +495,9 @@ export default class TextureBase extends Asset { * @method setFlipY * @param {Boolean} flipY */ - setFlipY (flipY) { + public setFlipY (flipY) { if (this._flipY !== flipY) { - var opts = _getSharedOptions(); + const opts = _getSharedOptions(); opts.flipY = flipY; this.update(opts); } @@ -510,9 +510,9 @@ export default class TextureBase extends Asset { * @method setPremultiplyAlpha * @param {Boolean} premultiply */ - setPremultiplyAlpha (premultiply) { + public setPremultiplyAlpha (premultiply) { if (this._premultiplyAlpha !== premultiply) { - var opts = _getSharedOptions(); + const opts = _getSharedOptions(); opts.premultiplyAlpha = premultiply; this.update(opts); } @@ -524,9 +524,9 @@ export default class TextureBase extends Asset { * @method setAnisotropy * @param {number} anisotropy */ - setAnisotropy(anisotropy) { - if (this._anisotropy != anisotropy) { - var opts = _getSharedOptions(); + public setAnisotropy (anisotropy) { + if (this._anisotropy !== anisotropy) { + const opts = _getSharedOptions(); opts.anisotropy = anisotropy; this.update(opts); } @@ -539,9 +539,9 @@ export default class TextureBase extends Asset { * @method setGenerateMipmap * @param {Boolean} mipmap */ - setGenMipmap (mipmap) { + public setGenMipmap (mipmap) { if (this._genMipmap !== mipmap) { - var opts = _getSharedOptions(); + const opts = _getSharedOptions(); opts.mipmap = mipmap; this.update(opts); } @@ -552,12 +552,12 @@ export default class TextureBase extends Asset { /** * @return {any} */ - _serialize () { - return this._minFilter + "," + this._magFilter + "," + - this._wrapS + "," + this._wrapT + "," + - (this._premultiplyAlpha ? 1 : 0) + "," + - this._mipFilter + "," + this._anisotropy + "," + - (this._flipY ? 1 : 0) + "," + + public _serialize () { + return this._minFilter + ',' + this._magFilter + ',' + + this._wrapS + ',' + this._wrapT + ',' + + (this._premultiplyAlpha ? 1 : 0) + ',' + + this._mipFilter + ',' + this._anisotropy + ',' + + (this._flipY ? 1 : 0) + ',' + (this._genMipmap ? 1 : 0); } @@ -565,9 +565,9 @@ export default class TextureBase extends Asset { * * @param {string} data */ - _deserialize (data) { - let fields = data.split(','); - fields.unshift(""); + public _deserialize (data) { + const fields = data.split(','); + fields.unshift(''); if (fields.length >= 6) { // decode filters this._minFilter = parseInt(fields[1]); From 69f38e6da66464f3e4e16f606b7ecbc2808bfc03 Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 8 Jan 2019 19:07:27 +0800 Subject: [PATCH 061/267] add rect.ts --- cocos/core/vmath/rect.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 cocos/core/vmath/rect.ts diff --git a/cocos/core/vmath/rect.ts b/cocos/core/vmath/rect.ts new file mode 100644 index 0000000000..1c230111e3 --- /dev/null +++ b/cocos/core/vmath/rect.ts @@ -0,0 +1,22 @@ + +export interface IRect2D { + x?: number; + y?: number; + width?: number; + height?: number; +} + +export interface INormalizedRect2D { + x: number; + y: number; + width: number; + height: number; +} + +export function normalizeRect2D (rect: IRect2D, fullWidth: number, fullHeight: number): INormalizedRect2D { + rect.x = rect.x || 0; + rect.y = rect.y || 0; + rect.width = rect.width || fullWidth; + rect.height = rect.height || fullHeight; + return rect as INormalizedRect2D; +} From aacd60fa92f5cd188b79bd0f22cc898270715cb4 Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 8 Jan 2019 19:28:00 +0800 Subject: [PATCH 062/267] impl texture-assets using gfx --- cocos/3d/assets/texture-cube.ts | 279 +++++++-------- cocos/assets/image-asset.ts | 266 +++++++------- cocos/assets/render-texture.ts | 229 ++++++++---- cocos/assets/texture-2d.ts | 249 ++++--------- cocos/assets/texture-base.ts | 606 ++++++++++++++++---------------- cocos/core/data/object.d.ts | 4 +- cocos/core/value-types/enum.js | 11 + 7 files changed, 783 insertions(+), 861 deletions(-) diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 9854377f82..1ad72c8e7e 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -23,39 +23,26 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check +import { Texture2D } from '../../assets'; import ImageAsset from '../../assets/image-asset'; import TextureBase from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; -import GFXTextureCube from '../../renderer/gfx/texture-cube'; +import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; -/** - * @typedef {import("../../assets/texture-2d")} Texture2D - * @typedef {import("../../assets/texture-base").ImageSource} ImageSource - * @typedef {import("../../assets/texture-base").TextureUpdateOpts} TextureUpdateOpts - * @typedef {import("../../assets/texture-base").HTMLImageSource} HTMLImageSource - * @typedef {{front: HTMLImageSource, back: HTMLImageSource, left: HTMLImageSource, right: HTMLImageSource, top: HTMLImageSource, bottom: HTMLImageSource}} MipmapHTMLImageSource - * @typedef {{front: ImageAsset, back: ImageAsset, left: ImageAsset, right: ImageAsset, top: ImageAsset, bottom: ImageAsset}} Mipmap - */ - -/** - * @enum {number} - */ -const FaceIndex = cc.Enum({ - right: 0, - left: 1, - top: 2, - bottom: 3, - front: 4, - back: 5, -}); +interface ITextureCubeMipmap { + front: ImageAsset; + back: ImageAsset; + left: ImageAsset; + right: ImageAsset; + top: ImageAsset; + bottom: ImageAsset; +} @ccclass('cc.TextureCube') export default class TextureCube extends TextureBase { - /** * Gets the mipmap images. * Note that the result do not contains the auto generated mipmaps. - * @type {Mipmap[]} */ get mipmaps () { return this._mipmaps; @@ -63,15 +50,14 @@ export default class TextureCube extends TextureBase { /** * Sets the mipmaps images. - * @type {Mipmap[]} */ set mipmaps (value) { - this._setMipmaps(value); + this._mipmaps = value; + this._recreateTexture(); } /** * Gets the mipmap image at level 0. - * @type {Mipmap} */ get image () { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; @@ -79,73 +65,39 @@ export default class TextureCube extends TextureBase { /** * Sets the mipmap images as a single mipmap image. - * @type {Mipmap} */ set image (value) { - this.mipmaps = [value]; + this.mipmaps = value ? [value] : []; } /** - * @param {Mipmap} mipmap - * @return {ImageSource[]} + * @param textures + * @deprecated Manually assign to mipmaps property instead. */ - public static _toMipmapArray (mipmap) { - /** @type {ImageSource[]} */ - const result = new Array(); - result[FaceIndex.front] = mipmap.front.data; - result[FaceIndex.back] = mipmap.back.data; - result[FaceIndex.left] = mipmap.left.data; - result[FaceIndex.right] = mipmap.right.data; - result[FaceIndex.top] = mipmap.top.data; - result[FaceIndex.bottom] = mipmap.bottom.data; - return result; - } - - /** - * @param {Mipmap} mipmap - * @param {(face: ImageAsset) => void} callback - */ - public static _forEachFace (mipmap, callback) { - for (const face in mipmap) { - callback(mipmap[face]); - } - } - - /** - * @param {Texture2D[]} textures - */ - public static fromTexture2DArray (textures, out) { - const res = [], mips = textures.length / 6; - for (let i = 0; i < mips; i++) { - res.push(textures.splice(0, 6).reduce((acc, img, i) => { - acc[FaceIndex[i]] = img.image; - return acc; - }, {})); + public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) { + const mipmaps: ITextureCubeMipmap[] = []; + const nMipmaps = textures.length / 6; + for (let i = 0; i < nMipmaps; i++) { + const x = i * 6; + mipmaps.push({ + front: textures[x + FaceIndex.front].image!, + back: textures[x + FaceIndex.back].image!, + left: textures[x + FaceIndex.left].image!, + right: textures[x + FaceIndex.right].image!, + top: textures[x + FaceIndex.top].image!, + bottom: textures[x + FaceIndex.bottom].image!, + }); } if (!out) { out = new TextureCube(); } - out.mipmaps = res; + out.mipmaps = mipmaps; return out; } - /** - * @type {Mipmap[]} - */ + @property - public _mipmaps = []; + public _mipmaps: ITextureCubeMipmap[] = []; constructor () { super(); - - /** - * @type {GFXTextureCube} - */ - this._texture = null; - } - - /** - * Gets the underlying texture object. - */ - public getImpl () { - return this._texture; } /** @@ -156,13 +108,9 @@ export default class TextureCube extends TextureBase { * !#zh * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} inherit from the CCObject */ public destroy () { - this.releaseTexture(); - // TODO cc.textureUtil ? - // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url + this._mipmaps = []; return super.destroy(); } @@ -170,81 +118,10 @@ export default class TextureCube extends TextureBase { * !#en * Release texture, please use destroy instead. * !#zh 释放纹理,请使用 destroy 替代。 - * @method releaseTexture - * @deprecated since v2.0 + * @deprecated Since v2.0. */ public releaseTexture () { - this._setMipmaps([]); - this._texture && this._texture.destroy(); - } - - /** - * Sets the _mipmaps to specified value, and updates the width and height accordingly. - * If available, synchronize the mipmap data to underlying texture. - * @param {Mipmap[]} mipmaps - */ - public _setMipmaps (mipmaps) { - this._mipmaps = mipmaps; - if (mipmaps.length === 0) { - super.update({ - width: 0, - height: 0, - }); - } else { - super.update({ - width: this._mipmaps[0].front.width, - height: this._mipmaps[0].front.height, - format: this._mipmaps[0].front._format, - }); - } - - let counter = 0; - const inc = () => { - ++counter; - if (counter === this._mipmaps.length * 6) { - this._updateMipmaps(this._mipmaps.map((mipmap) => TextureCube._toMipmapArray(mipmap))); - } - }; - mipmaps.forEach((mipmap) => { - TextureCube._forEachFace(mipmap, (face) => { - if (face.loaded) { - inc(); - } else { - face.addEventListener('load', () => inc()); - } - }); - }); - } - - /** - * Updates mipmaps of the underlying texture. - * @param {ImageSource[][]} mipmapSources - */ - public _updateMipmaps (mipmapSources) { - const opts = this._getOpts(); - opts.images = mipmapSources; - if (!this._texture) { - this._texture = new GFXTextureCube(cc.game._renderContext, opts); - } else { - this._texture.update(opts); - } - } - - /** - * Update texture options, not available in Canvas render mode. - * image, format, premultiplyAlpha can not be updated in native. - * @method update - */ - public update (options) { - if (!options) { return; } - - super.update(options); - - // TODO: options.image - - if (this._texture) { - this._texture.update(options); - } + this.mipmaps = []; } public _serialize () { @@ -261,12 +138,21 @@ export default class TextureCube extends TextureBase { }; } - public _deserialize (data, handle) { - super._deserialize(data.base); + public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) { + const data = serializedData as ITextureCubeSerializeData; + super._deserialize(data.base, handle); this._mipmaps = new Array(data.mipmaps.length); - this._mipmaps.fill({}); for (let i = 0; i < data.mipmaps.length; ++i) { + // Prevent resource load failed + this._mipmaps[i] = { + front: new ImageAsset(), + back: new ImageAsset(), + left: new ImageAsset(), + right: new ImageAsset(), + top: new ImageAsset(), + bottom: new ImageAsset(), + }; const mipmap = data.mipmaps[i]; handle.result.push(this._mipmaps[i], `front`, mipmap.front); handle.result.push(this._mipmaps[i], `back`, mipmap.back); @@ -280,6 +166,77 @@ export default class TextureCube extends TextureBase { public onLoaded () { this.mipmaps = this._mipmaps; } + + protected _createTexture () { + if (this._mipmaps.length === 0) { + return; + } + + this._texture = this._getGlobalDevice().createTexture({ + type: GFXTextureType.TEX2D, + /* tslint:disable:no-bitwise */ + usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, + /* tslint:enable:no-bitwise */ + format: this._getGfxFormat(), + width: this.width, + height: this.height, + mipLevel: this._mipmaps.length, + arrayLayer: 6, + }); + + this._mipmaps.forEach((mipmap, level) => { + _forEachFace(mipmap, (face, faceIndex) => { + this._assignImage(face, level, faceIndex); + }); + }); + } + + protected _createTextureView () { + if (!this._texture) { + return; + } + + this._textureView = this._getGlobalDevice().createTextureView({ + texture: this._texture, + type: GFXTextureViewType.TV2D_ARRAY, + format: this._getGfxFormat(), + }); + } } -cc.TextureCube = TextureCube; +/* tslint:disable:no-string-literal */ +cc['TextureCube'] = TextureCube; + +interface ITextureCubeSerializeData { + base: string; + mipmaps: Array<{ + front: string; + back: string; + left: string; + right: string; + top: string; + bottom: string; + }>; +} + +enum FaceIndex { + right = 0, + left = 1, + top = 2, + bottom = 3, + front = 4, + back = 5, +} + +/** + * @param {Mipmap} mipmap + * @param {(face: ImageAsset) => void} callback + */ +function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) { + callback(mipmap.front, FaceIndex.front); + callback(mipmap.back, FaceIndex.back); + callback(mipmap.left, FaceIndex.left); + callback(mipmap.right, FaceIndex.right); + callback(mipmap.top, FaceIndex.top); + callback(mipmap.bottom, FaceIndex.bottom); +} diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts index 89bdf0e92b..b43319850c 100644 --- a/cocos/assets/image-asset.ts +++ b/cocos/assets/image-asset.ts @@ -26,108 +26,38 @@ import {ccclass, property} from '../core/data/class-decorator'; import EventTarget from '../core/event/event-target'; import {addon} from '../core/utils/js'; +import { Asset } from './asset'; -/** - * @typedef {{ _data: ArrayBufferView, _compressed: boolean, width: number, height: number, format: number}} RawImageData - */ +export interface IMemoryImageSource { + _data: ArrayBufferView | null; + _compressed: boolean; + width: number; + height: number; + format: number; +} -const CHAR_CODE_0 = 48; // '0' +type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource; /** * Class ImageAsset. */ @ccclass('cc.ImageAsset') -export default class ImageAsset extends cc.Asset { +export default class ImageAsset extends Asset { - public static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; - - /** - * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} nativeAsset - */ - constructor (nativeAsset = undefined) { - super(); - EventTarget.call(this); - - /** - * !#en - * The url of the texture, this could be empty if the texture wasn't created via a file. - * !#zh - * 图像文件的 url,当图像不是由文件创建时值可能为空 - * @property url - * @type {String} - * @readonly - */ - // TODO - use nativeUrl directly - this.url = ''; - - /** - * @type {HTMLCanvasElement | HTMLImageElement | RawImageData} - */ - this._nativeData = { - _data: null, - width: 0, - height: 0, - format: 0, - _compressed: false, - }; - - if (CC_EDITOR) { - this._exportedExts = null; - } - - if (nativeAsset !== undefined) { - this._nativeAsset = nativeAsset; - } - } - - /** - * @type {HTMLCanvasElement | HTMLImageElement | RawImageData} - */ - @property({ - override: true, - }) + @property({override: true}) get _nativeAsset () { - // maybe returned to pool in webgl + // Maybe returned to pool in webgl. return this._nativeData; } - /** - * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} value - */ - set _nativeAsset (value) { + set _nativeAsset (value: ImageSource) { this.reset(value); } - /** - * @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView} - */ get data () { return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data; } - /** - * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data - */ - public reset (data) { - if (!(data instanceof HTMLElement)) { - this._nativeData = Object.create(data); - this._onDataComplete(); - } else { - this._nativeData = data; - if (CC_WECHATGAME || CC_QQPLAY || data.complete || data instanceof HTMLCanvasElement) { - this._onDataComplete(); - } else { - this.loaded = false; - data.addEventListener('load', () => { - this._onDataComplete(); - }); - data.addEventListener('error', (err) => { - cc.warnID(3119, err.message); - }); - } - } - } - get width () { return this._nativeData.width; } @@ -143,6 +73,74 @@ export default class ImageAsset extends cc.Asset { return this._nativeData.format; } + /** + * !#en + * The url of the texture, this could be empty if the texture wasn't created via a file. + * !#zh + * 图像文件的 url,当图像不是由文件创建时值可能为空 + */ + // TODO - use nativeUrl directly + get url () { + return this._url; + } + + private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc']; + + private _nativeData: ImageSource; + + private _url: string; + + private _exportedExts: string[] | null | undefined = undefined; + + private _format: string = ''; + + /** + * @param nativeAsset + */ + constructor (nativeAsset?: ImageSource) { + super(); + // @ts-ignore + EventTarget.call(this); + + this._url = ''; + + this._nativeData = { + _data: null, + width: 0, + height: 0, + format: 0, + _compressed: false, + }; + + if (CC_EDITOR) { + this._exportedExts = null; + } + + if (nativeAsset !== undefined) { + this._nativeAsset = nativeAsset; + } + } + + public reset (data: ImageSource) { + if (!(data instanceof HTMLElement)) { + this._nativeData = Object.create(data); + this._onDataComplete(); + } else { + this._nativeData = data; + if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) { + this._onDataComplete(); + } else { + this.loaded = false; + data.addEventListener('load', () => { + this._onDataComplete(); + }); + data.addEventListener('error', (err) => { + cc.warnID(3119, err.message); + }); + } + } + } + // destroy() { // if (cc.macro.CLEANUP_IMAGE_CACHE) { // if (this._data instanceof HTMLImageElement) { @@ -155,77 +153,67 @@ export default class ImageAsset extends cc.Asset { // SERIALIZATION public _serialize () { - let extId = ''; - let exportedExts = this._exportedExts; - if (!exportedExts && this._native) { - exportedExts = [this._native]; + let targetExtensions = this._exportedExts; + if (!targetExtensions && this._native) { + targetExtensions = [this._native]; } - if (exportedExts) { - const exts = []; - for (let i = 0; i < exportedExts.length; i++) { - let extId = ''; - const ext = exportedExts[i]; - if (ext) { - // ext@format - const extFormat = ext.split('@'); - extId = ImageAsset.extnames.indexOf(extFormat[0]); - if (extId < 0) { - extId = ext; - } - if (extFormat[1]) { - extId += '@' + extFormat[1]; - } - } - exts.push(extId); + + if (!targetExtensions) { + return ''; + } + + const extensionIndices: string[] = []; + for (const targetExtension of targetExtensions) { + const extensionFormat = targetExtension.split('@'); + const i = ImageAsset.extnames.indexOf(extensionFormat[0]); + let exportedExtensionID = i < 0 ? targetExtension : `${i}`; + if (extensionFormat[1]) { + exportedExtensionID += '@' + extensionFormat[1]; } - extId = exts.join('_'); + extensionIndices.push(exportedExtensionID); } - return '' + extId; + return extensionIndices.join('_'); } - public _deserialize (data, handle) { - const fields = data.split(','); - // decode extname - const extIdStr = fields[0]; - if (extIdStr) { - const extIds = extIdStr.split('_'); + public _deserialize (data: string, handle: any) { + const extensionIDs = data.split('_'); - let extId = 999; - let ext = ''; - let format = this._format; - const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS; - for (let i = 0; i < extIds.length; i++) { - const extFormat = extIds[i].split('@'); - let tmpExt = extFormat[0]; - tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0; - tmpExt = ImageAsset.extnames[tmpExt] || extFormat; + let preferedExtensionIndex = Number.MAX_VALUE; + let format = this._format; + let ext = ''; + const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[]; + for (const extensionID of extensionIDs) { + const extFormat = extensionID.split('@'); - const index = SupportTextureFormats.indexOf(tmpExt); - if (index !== -1 && index < extId) { - extId = index; - ext = tmpExt; - format = extFormat[1] ? parseInt(extFormat[1]) : this._format; - } + const i = parseInt(extFormat[0], undefined); + const tmpExt = ImageAsset.extnames[i] || extFormat.join(); + + const index = SupportTextureFormats.indexOf(tmpExt); + if (index !== -1 && index < preferedExtensionIndex) { + preferedExtensionIndex = index; + ext = tmpExt; + format = extFormat[1] ? extFormat[1] : this._format; } + } - if (ext) { - this._setRawAsset(ext); - this._format = format; - } + if (ext) { + // @ts-ignore + this._setRawAsset(ext); + this._format = format; + } - // preset uuid to get correct nativeUrl - const loadingItem = handle.customEnv; - const uuid = loadingItem && loadingItem.uuid; - if (uuid) { - this._uuid = uuid; - const url = this.nativeUrl; - this.url = url; - } + // preset uuid to get correct nativeUrl + const loadingItem = handle.customEnv; + const uuid = loadingItem && loadingItem.uuid; + if (uuid) { + this._uuid = uuid; + this._url = this.nativeUrl; } } public _onDataComplete () { this.loaded = true; + // @ts-ignore this.emit('load'); } } diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts index e63fdc39ec..b83176fe74 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/assets/render-texture.ts @@ -1,7 +1,25 @@ import { ccclass } from '../core/data/class-decorator'; -import gfx from '../renderer/gfx'; +import { IRect2D, normalizeRect2D } from '../core/vmath/rect'; +import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; +import { GFXFramebuffer } from '../gfx/framebuffer'; +import { GFXTexture } from '../gfx/texture'; +import { GFXTextureView } from '../gfx/texture-view'; +import { RenderPassStage } from '../pipeline/render-pipeline'; +import ImageAsset from './image-asset'; import Texture2D from './texture-2d'; +enum DepthStencilFormat { + D24S8 = GFXFormat.D24S8, + + S8 = GFXFormat.R8UI, + + D16 = GFXFormat.D16, +} + +function toGfxDepthStencilFormat (depthStencilFormat: DepthStencilFormat): GFXFormat { + return depthStencilFormat as unknown as GFXFormat; +} + /** * Render textures are textures that can be rendered to. * @class RenderTexture @@ -9,10 +27,14 @@ import Texture2D from './texture-2d'; */ @ccclass('cc.RenderTexture') export default class RenderTexture extends Texture2D { + private _framebuffer: GFXFramebuffer | null = null; + + private _depthStencilTexture: GFXTexture | null = null; + + private _depthStencilTextureView: GFXTextureView | null = null; constructor () { super(); - this._framebuffer = null; } /** @@ -20,70 +42,123 @@ export default class RenderTexture extends Texture2D { * Init the render texture with size. * !#zh * 初始化 render texture - * @param {Number} [width] - * @param {Number} [height] - * @param {Number} [depthStencilFormat] + * @param [width] + * @param [height] + * @param [depthStencilFormat] * @method initWithSize */ - public initWithSize (width, height, depthStencilFormat) { - this.width = Math.floor(width || cc.visibleRect.width); - this.height = Math.floor(height || cc.visibleRect.height); - this._resetUnderlyingMipmaps(); + public initWithSize (width?: number, height?: number, depthStencilFormat?: DepthStencilFormat) { + this.destroy(); - const opts = { - colors: [ this._texture ], - }; - if (depthStencilFormat) { - if (this.depthStencilBuffer) { this.depthStencilBuffer.destroy(); } - const depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height); - if (depthStencilFormat === gfx.RB_FMT_D24S8) { - opts.depthStencil = depthStencilBuffer; - } else if (depthStencilFormat === gfx.RB_FMT_S8) { - opts.stencil = depthStencilBuffer; - } else if (depthStencilFormat === gfx.RB_FMT_D16) { - opts.depth = depthStencilBuffer; - } - this.depthStencilBuffer = depthStencilBuffer; - this.depthStencilFormat = depthStencilFormat; + const gfxDevice = this._getGlobalDevice(); + + const w = Math.floor(width || cc.visibleRect.width); + const h = Math.floor(height || cc.visibleRect.height); + const image = new ImageAsset({ + width: w, + height: h, + format: GFXFormat.RGBA8UI, + _data: new Uint8Array(w * h * 4), + _compressed: false, + }); + + this.image = image; + + if (!this._texture) { + return; } - if (this._framebuffer) { this._framebuffer.destroy(); } - this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts); + const colorView = gfxDevice.createTextureView({ + texture: this._texture, + type: GFXTextureViewType.TV2D, + format: this._getGfxFormat(), + }); + + if (!colorView) { + return; + } + + if (depthStencilFormat !== undefined) { + this._depthStencilTexture = gfxDevice.createTexture({ + type: GFXTextureType.TEX2D, + usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT, + format: toGfxDepthStencilFormat(depthStencilFormat), + width: w, + height: h, + }); + if (!this._depthStencilTexture) { + return; + } + this._depthStencilTextureView = gfxDevice.createTextureView({ + texture: this._depthStencilTexture, + type: GFXTextureViewType.TV2D, + format: toGfxDepthStencilFormat(depthStencilFormat), + }); + } + + 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, + isOffscreen: true, + }); this.loaded = true; + // @ts-ignore this.emit('load'); } - public updateSize (width, height) { - this.width = Math.floor(width || cc.visibleRect.width); - this.height = Math.floor(height || cc.visibleRect.height); - this._resetUnderlyingMipmaps(); - - const rbo = this.depthStencilBuffer; - if (rbo) { rbo.update(this.width, this.height); } - this._framebuffer._width = width; - this._framebuffer._height = height; + public destroy () { + if (this._framebuffer) { + this._framebuffer.destroy(); + this._framebuffer = null; + } + if (this._depthStencilTextureView) { + this._depthStencilTextureView.destroy(); + this._depthStencilTextureView = null; + } + if (this._depthStencilTexture) { + this._depthStencilTexture.destroy(); + this._depthStencilTexture = null; + } + return super.destroy(); } + // TODO: + // public updateSize (width, height) { + // this.width = Math.floor(width || cc.visibleRect.width); + // this.height = Math.floor(height || cc.visibleRect.height); + // this._resetUnderlyingMipmaps(); + + // const rbo = this.depthStencilBuffer; + // if (rbo) { rbo.update(this.width, this.height); } + // this._framebuffer._width = width; + // this._framebuffer._height = height; + // } + /** * !#en Draw a texture to the specified position * !#zh 将指定的图片渲染到指定的位置上 - * @param {Texture2D} texture - * @param {Number} x - * @param {Number} y + * @param texture + * @param x + * @param y */ - public drawTextureAt (texture, x, y) { - if (!texture._image) { return; } + public drawTextureAt (texture: Texture2D, x: number, y: number) { + if (!this._texture) { + return; + } - this._texture.updateSubImage({ - x, y, - image: texture._image, - width: texture.width, - height: texture.height, - level: 0, - flipY: false, - premultiplyAlpha: texture._premultiplyAlpha, - }); + const image = texture.image; + + if (!image) { + return; + } + + this._assignImage(image, 0); } /** @@ -96,38 +171,42 @@ export default class RenderTexture extends Texture2D { * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。 * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。 * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。 - * @method readPixels - * @param {Uint8Array} [data] - * @param {Number} [x] - * @param {Number} [y] - * @param {Number} [w] - * @param {Number} [h] - * @return {Uint8Array} + * @param [data] + * @param [rect] */ - public readPixels (data, x, y, w, h) { - if (!this._framebuffer || !this._texture) { return data; } + public readPixels (data?: Uint8Array, rect: IRect2D = {}) { + if (!this._framebuffer || !this._texture) { + return undefined; + } - x = x || 0; - y = y || 0; - const width = w || this.width; - const height = h || this.height; - data = data || new Uint8Array(width * height * 4); + const normalizedRect = normalizeRect2D(rect, this.width, this.height); - const gl = cc.game._renderContext._gl; - const oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); - gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID); - gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data); - gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO); + data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4); + + this._getGlobalDevice().copyFramebufferToBuffer(this._framebuffer, data.buffer, [{ + buffOffset: 0, + buffStride: 0, + buffTexHeight: 0, + texOffset: { + x: normalizedRect.x, + y: normalizedRect.y, + z: 0, + }, + texExtent: { + width: normalizedRect.width, + height: normalizedRect.height, + depth: 1, + }, + texSubres: { + baseMipLevel: 0, + levelCount: 1, + baseArrayLayer: 0, + layerCount: 1, + }, + }]); return data; } - - public destroy () { - super.destroy(); - if (this._framebuffer) { - this._framebuffer.destroy(); - } - } } cc.RenderTexture = RenderTexture; diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index d9468ba218..f52c059f3c 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -24,53 +24,19 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import {ccclass, property} from '../core/data/class-decorator'; -import GFXTexture2D from '../renderer/gfx/texture-2d'; +import { ccclass, property } from '../core/data/class-decorator'; +import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; import ImageAsset from './image-asset'; import TextureBase from './texture-base'; /** - * @typedef {import("./texture-base").ImageSource} ImageSource - * @typedef {import("./texture-base").TextureUpdateOpts} TextureUpdateOpts - */ - -/** - *

- * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
- * The created cc.Texture2D object will always have power-of-two dimensions.
- * Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
- * Be aware that the content of the generated textures will be upside-down!

- - * @class Texture2D - * @extends TextureBase + * Represents a 2-dimension texture. */ @ccclass('cc.Texture2D') export default class Texture2D extends TextureBase { - @property({ - override: true, - }) - public _flipY = true; - - /** - * @type {ImageAsset[]} - */ - @property([ImageAsset]) - public _mipmaps = []; - - constructor () { - super(); - - /** - * @type {GFXTexture2D} - */ - this._texture = null; - } - /** * Gets the mipmap images. * Note that the result do not contains the auto generated mipmaps. - * @return {ImageAsset[]} */ get mipmaps () { return this._mipmaps; @@ -78,15 +44,14 @@ export default class Texture2D extends TextureBase { /** * Sets the mipmaps images. - * @param {ImageAsset[]} value */ set mipmaps (value) { - this._setMipmaps(value); + this._mipmaps = value; + this._recreateTexture(); } /** * Gets the mipmap image at level 0. - * @return {ImageAsset} */ get image () { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; @@ -94,17 +59,16 @@ export default class Texture2D extends TextureBase { /** * Sets the mipmap images as a single mipmap image. - * @param {ImageAsset} value */ set image (value) { - this.mipmaps = [value]; + this.mipmaps = value ? [value] : []; } - /** - * Gets the underlying texture object. - */ - public getImpl () { - return this._texture; + @property([ImageAsset]) + public _mipmaps: ImageAsset[] = []; + + constructor () { + super(true); } /** @@ -115,82 +79,33 @@ export default class Texture2D extends TextureBase { } /** - * Update texture options, not available in Canvas render mode. - * image, format, premultiplyAlpha can not be updated in native. - * @method update - * @param {TextureUpdateOpts} options + * Updates mipmaps at level 0. */ - public update (options) { - if (!options) { - return; - } - - super.update(options); - - if (options.image) { - options.images = [options.image]; - } - - if (options.images !== undefined && options.images.length !== 0) { - this._setMipmaps(options.images.map((image) => { - const mipmap = new ImageAsset(); - mipmap.reset(image instanceof HTMLElement ? image : { - _data: image, - width: this.width, - height: this.height, - format: this._format, - _compressed: false, - }); - return mipmap; - })); - } - - if (this._texture) { - this._texture.update(options); - } - } - - /** - * - * @param {ImageSource} source - */ - public updateImage (source) { - this.updateMipmaps([source]); + public updateImage () { + this.updateMipmaps(0); } /** * Updates mipmaps at specified range of levels. - * @param {ImageSource[]} sources The image sources. - * @param {number} firstLevel The first level from which the sources update. + * @param sources The image sources. + * @param firstLevel The first level from which the sources update. * @description * If the range specified by [firstLevel, firstLevel + sources.length) exceeds * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated. + * Use this method if your mipmap data are modified. */ - public updateMipmaps (sources, firstLevel = 0) { - if (firstLevel >= sources.length) { + public updateMipmaps (firstLevel: number, count?: number) { + if (firstLevel >= this._mipmaps.length) { return; } - const nUpdate = Math.min(sources.length, this._mipmaps.length - firstLevel); + const nUpdate = Math.min( + count === undefined ? this._mipmaps.length : count, + this._mipmaps.length - firstLevel); + for (let i = 0; i < nUpdate; ++i) { const level = firstLevel + i; - const mipmap = this._mipmaps[level]; - const source = sources[i]; - mipmap.reset(source instanceof HTMLElement ? source : { - _data: source, - width: mipmap.width, - height: mipmap.height, - format: mipmap._format, - _compressed: false, - }); - this._texture.updateImage({ - width: this.width, - height: this.height, - level, - image: sources[i], - flipY: false, - premultiplyAlpha: false, - }); + this._uploadImage(this._mipmaps[level], level); } } @@ -214,13 +129,9 @@ export default class Texture2D extends TextureBase { * !#zh * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
* 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} inherit from the CCObject */ public destroy () { - this.releaseTexture(); - // TODO cc.textureUtil ? - // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url + this._mipmaps = []; return super.destroy(); } @@ -228,76 +139,20 @@ export default class Texture2D extends TextureBase { * !#en * Description of cc.Texture2D. * !#zh cc.Texture2D 描述。 - * @method description - * @returns {String} */ public description () { - return ''; + const url = this._mipmaps[0] ? this._mipmaps[0].url : ''; + return ``; } /** * !#en * Release texture, please use destroy instead. * !#zh 释放纹理,请使用 destroy 替代。 - * @method releaseTexture - * @deprecated since v2.0, use destroy instead. + * @deprecated Since v2.0, use destroy instead. */ public releaseTexture () { - this._setMipmaps([]); - this._texture && this._texture.destroy(); - } - - /** - * Sets the _mipmaps to specified value, and updates the width and height accordingly. - * If available, synchronize the mipmap data to underlying texture. - * @param {ImageAsset[]} mipmaps - */ - public _setMipmaps (mipmaps) { - this._mipmaps = mipmaps; - if (mipmaps.length === 0) { - super.update({ - width: 0, - height: 0, - }); - } else { - const level0 = this._mipmaps[0]; - super.update({ - width: level0.width, - height: level0.height, - format: level0._format, - }); - } - - let counter = 0; - const inc = () => { - ++counter; - if (counter === mipmaps.length) { - this._resetUnderlyingMipmaps(mipmaps.map((mipmap) => mipmap.data)); - } - }; - mipmaps.forEach((mipmap) => { - if (mipmap.loaded) { - inc(); - } else { - mipmap.addEventListener('load', () => { - inc(); - }); - } - }); - } - - /** - * Resets sources and amount of the underlying texture's the mipmaps. - * @param {ImageSource[]} mipmapSources - */ - public _resetUnderlyingMipmaps (mipmapSources = [null]) { - const opts = this._getOpts(); - opts.images = mipmapSources; - if (!this._texture) { - this._texture = new GFXTexture2D(cc.game._renderContext, opts); - } else { - this._texture.update(opts); - } + this.mipmaps = []; } public _serialize () { @@ -307,8 +162,9 @@ export default class Texture2D extends TextureBase { }; } - public _deserialize (data, handle) { - super._deserialize(data.base); + public _deserialize (serializedData: any, handle: any) { + const data = serializedData as ITexture2DSerializeData; + super._deserialize(data.base, handle); this._mipmaps = new Array(data.mipmaps.length); for (let i = 0; i < data.mipmaps.length; ++i) { @@ -322,6 +178,45 @@ export default class Texture2D extends TextureBase { public onLoaded () { this.mipmaps = this._mipmaps; } + + protected _createTexture () { + if (this._mipmaps.length === 0) { + return; + } + + this._texture = this._getGlobalDevice().createTexture({ + type: GFXTextureType.TEX2D, + /* tslint:disable:no-bitwise */ + usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, + /* tslint:enable:no-bitwise */ + format: this._getGfxFormat(), + width: this.width, + height: this.height, + mipLevel: this._mipmaps.length, + }); + + this._mipmaps.forEach((mipmap, level) => { + this._assignImage(mipmap, level); + }); + } + + protected _createTextureView () { + if (!this._texture) { + return; + } + + this._textureView = this._getGlobalDevice().createTextureView({ + texture: this._texture, + type: GFXTextureViewType.TV2D, + format: this._getGfxFormat(), + }); + } } -cc.Texture2D = Texture2D; +/* tslint:disable:no-string-literal */ +cc['Texture2D'] = Texture2D; + +interface ITexture2DSerializeData { + base: string; + mipmaps: string[]; +} diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 1c726fefa7..499e304b19 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -28,30 +28,17 @@ import {ccclass, property} from '../core/data/class-decorator'; import EventTarget from '../core/event/event-target'; import IDGenerator from '../core/utils/id-generator'; import {addon} from '../core/utils/js'; -import Enum from '../core/value-types/enum'; -import {enums} from '../renderer/gfx/enums'; -import Asset from './CCAsset'; - -/** - * @typedef {import("../renderer/gfx/texture-2d").HTMLImageSource} HTMLImageSource - * @typedef {import("../renderer/gfx/texture-2d").ImageSource} ImageSource - * @typedef {import("../renderer/gfx/texture-2d").TextureUpdateOpts} TextureUpdateOpts - * - * @exports HTMLImageSource - * @exports ImageSource - * @exports TextureUpdateOpts - */ - -const _images = []; +import { ccenum } from '../core/value-types/enum'; +import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; +import { GFXSampler } from '../gfx/sampler'; +import { GFXTexture } from '../gfx/texture'; +import { GFXTextureView } from '../gfx/texture-view'; +import { Asset } from './asset'; +import ImageAsset from './image-asset'; const CHAR_CODE_1 = 49; // '1' -const GL_NEAREST = 9728; // gl.NEAREST -const GL_LINEAR = 9729; // gl.LINEAR -const GL_REPEAT = 10497; // gl.REPEAT -const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE -const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT - const idGenerator = new IDGenerator('Tex'); /** @@ -60,187 +47,145 @@ const idGenerator = new IDGenerator('Tex'); * other formats are supported by compressed file types or raw data. * @enum {number} */ -const PixelFormat = Enum({ +export enum PixelFormat { /** * 16-bit texture without Alpha channel - * @property RGB565 - * @readonly - * @type {Number} */ - RGB565: enums.TEXTURE_FMT_R5_G6_B5, + RGB565 = GFXFormat.R5G6B5, /** * 16-bit textures: RGB5A1 - * @property RGB5A1 - * @readonly - * @type {Number} */ - RGB5A1: enums.TEXTURE_FMT_R5_G5_B5_A1, + RGB5A1 = GFXFormat.RGB5A1, /** * 16-bit textures: RGBA4444 - * @property RGBA4444 - * @readonly - * @type {Number} */ - RGBA4444: enums.TEXTURE_FMT_R4_G4_B4_A4, + RGBA4444 = GFXFormat.RGBA4, /** * 24-bit texture: RGB888 - * @property RGB888 - * @readonly - * @type {Number} */ - RGB888: enums.TEXTURE_FMT_RGB8, + RGB888 = GFXFormat.RGB8UI, /** * 32-bit texture: RGBA8888 - * @property RGBA8888 - * @readonly - * @type {Number} */ - RGBA8888: enums.TEXTURE_FMT_RGBA8, + RGBA8888 = GFXFormat.RGBA8UI, /** * 32-bit float texture: RGBA32F - * @property RGBA32F - * @readonly - * @type {Number} */ - RGBA32F: enums.TEXTURE_FMT_RGBA32F, + RGBA32F = GFXFormat.RGBA32F, /** * 8-bit textures used as masks - * @property A8 - * @readonly - * @type {Number} */ - A8: enums.TEXTURE_FMT_A8, + A8 = GFXFormat.R8UI, /** * 8-bit intensity texture - * @property I8 - * @readonly - * @type {Number} */ - I8: enums.TEXTURE_FMT_L8, + I8 = GFXFormat.R8UI, /** * 16-bit textures used as masks - * @property AI88 - * @readonly - * @type {Number} */ - AI8: enums.TEXTURE_FMT_L8_A8, - + AI8 = GFXFormat.RG8UI, /** * rgb 2 bpp pvrtc - * @property RGB_PVRTC_2BPPV1 - * @readonly - * @type {Number} */ - RGB_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_2BPPV1, + RGB_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGB2, /** * rgba 2 bpp pvrtc - * @property RGBA_PVRTC_2BPPV1 - * @readonly - * @type {Number} */ - RGBA_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_2BPPV1, + RGBA_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGBA2, /** * rgb 4 bpp pvrtc - * @property RGB_PVRTC_4BPPV1 - * @readonly - * @type {Number} */ - RGB_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_4BPPV1, + RGB_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGB4, /** * rgba 4 bpp pvrtc - * @property RGBA_PVRTC_4BPPV1 - * @readonly - * @type {Number} */ - RGBA_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1, -}); + RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4, +} +ccenum(PixelFormat); + +function toGfxFormat (pixelFormat: PixelFormat) { + return pixelFormat as unknown as GFXFormat; +} /** - * The texture wrap mode + * The texture wrap mode. * @enum {number} */ -export const WrapMode = Enum({ +export enum WrapMode { /** - * The constant variable equals gl.REPEAT for texture - * @property REPEAT - * @type {Number} - * @readonly + * Specifies that the repeat warp mode will be used. */ - REPEAT: GL_REPEAT, + REPEAT = GFXAddress.WRAP, /** - * The constant variable equals gl.CLAMP_TO_EDGE for texture - * @property CLAMP_TO_EDGE - * @type {Number} - * @readonly + * Specifies that the clamp to edge warp mode will be used. */ - CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE, + CLAMP_TO_EDGE = GFXAddress.CLAMP, /** - * The constant variable equals gl.MIRRORED_REPEAT for texture - * @property MIRRORED_REPEAT - * @type {Number} - * @readonly + * Specifies that the mirrored repeat warp mode will be used. */ - MIRRORED_REPEAT: GL_MIRRORED_REPEAT, -}); + MIRRORED_REPEAT = GFXAddress.MIRROR, + /** + * Specifies that the clamp to border wrap mode will be used. + */ + CLAMP_TO_BORDER = GFXAddress.BORDER, +} +ccenum(WrapMode); + +function toGfxAddressMode (wrapMode: WrapMode) { + return wrapMode as unknown as GFXAddress; +} /** * The texture filter mode * @enum {number} */ -export const Filter = Enum({ +export enum Filter { /** - * The constant variable equals gl.LINEAR for texture - * @property LINEAR - * @type {Number} - * @readonly + * Specifies linear filtering. */ - LINEAR: GL_LINEAR, + LINEAR = GFXFilter.LINEAR, /** - * The constant variable equals gl.NEAREST for texture - * @property NEAREST - * @type {Number} - * @readonly + * Specifies nearest filtering. */ - NEAREST: GL_NEAREST, -}); + NEAREST = GFXFilter.POINT, +} +ccenum(Filter); -const FilterIndex = { - 9728: 0, // GL_NEAREST - 9729: 1, // GL_LINEAR -}; - -/** - * @type TextureUpdateOpts - */ -const _sharedOpts = { - width: undefined, - height: undefined, - minFilter: undefined, - magFilter: undefined, - mipFilter: undefined, - wrapS: undefined, - wrapT: undefined, - format: undefined, - mipmap: undefined, - images: undefined, - image: undefined, - flipY: undefined, - premultiplyAlpha: undefined, - anisotropy: undefined, -}; -function _getSharedOptions () { - for (const key in _sharedOpts) { - _sharedOpts[key] = undefined; - } - _images.length = 0; - _sharedOpts.images = _images; - _sharedOpts.flipY = false; - return _sharedOpts; +function toGfxFilterMode (filter: Filter) { + return filter as unknown as GFXFilter; } @ccclass('cc.TextureBase') export default class TextureBase extends Asset { + /** + * !#en + * Texture width, in pixels. + * For 2D texture, the width of texture is equal to its very first mipmap's width; + * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width. + * !#zh + * 贴图像素宽度 + * @property width + * @type {Number} + */ + public get width (): number { + return this._width; + } + + /** + * !#en + * Texture height, in pixels. + * For 2D texture, the height of texture is equal to its very first mipmap's height; + * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height. + * !#zh + * 贴图像素高度 + * @property height + * @type {Number} + */ + public get height (): number { + return this._height; + } + public static PixelFormat = PixelFormat; public static WrapMode = WrapMode; @@ -249,45 +194,61 @@ export default class TextureBase extends Asset { /** * - * @param {TextureBase} texture + * @param texture */ - public static _isCompressed (texture) { + public static _isCompressed (texture: TextureBase) { return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1; } - @property - public _genMipmap = false; + + protected _texture: GFXTexture | null = null; + + protected _textureView: GFXTextureView | null = null; @property - public _format = PixelFormat.RGBA8888; + private _genMipmap = false; @property - public _premultiplyAlpha = false; + private _format: PixelFormat = PixelFormat.RGBA8888; @property - public _flipY = false; + private _premultiplyAlpha = false; @property - public _minFilter = Filter.LINEAR; + private _flipY = false; @property - public _magFilter = Filter.LINEAR; + private _minFilter = Filter.LINEAR; @property - public _mipFilter = Filter.LINEAR; + private _magFilter = Filter.LINEAR; @property - public _wrapS = WrapMode.CLAMP_TO_EDGE; + private _mipFilter = Filter.LINEAR; @property - public _wrapT = WrapMode.CLAMP_TO_EDGE; + private _wrapS: WrapMode = WrapMode.CLAMP_TO_EDGE; @property - public _anisotropy = 1; + private _wrapT: WrapMode = WrapMode.CLAMP_TO_EDGE; - constructor () { + @property + private _anisotropy = 1; + + private _width: number = 0; + + private _height: number = 0; + + private _sampler: GFXSampler | null = null; + + private _id: string; + + protected constructor (flipY: boolean = false) { super(); + // @ts-ignore EventTarget.call(this); + this._flipY = flipY; + // Id for generate hash in material this._id = idGenerator.getNewId(); @@ -299,109 +260,27 @@ export default class TextureBase extends Asset { * @property loaded * @type {Boolean} */ + // @ts-ignore this.loaded = false; - /** - * !#en - * Texture width, in pixels. - * For 2D texture, the width of texture is equal to its very first mipmap's width; - * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width. - * !#zh - * 贴图像素宽度 - * @property width - * @type {Number} - */ - this.width = 0; - /** - * !#en - * Texture height, in pixels. - * For 2D texture, the height of texture is equal to its very first mipmap's height; - * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height. - * !#zh - * 贴图像素高度 - * @property height - * @type {Number} - */ - this.height = 0; + } + + /** + * Gets the underlying texture object. + * @deprecated Use getGfxTexture() instead. + */ + public getImpl () { + return this._texture; } public getId () { return this._id; } - /** - * Update texture sampler options. - * @method update - * @param {TextureUpdateOpts} options - */ - public update (options) { - if (!options) { - return; - } - - if (options.width !== undefined) { - this.width = options.width; - } - if (options.height !== undefined) { - this.height = options.height; - } - if (options.minFilter !== undefined) { - this._minFilter = options.minFilter; - options.minFilter = FilterIndex[options.minFilter]; - } - if (options.magFilter !== undefined) { - this._magFilter = options.magFilter; - options.magFilter = FilterIndex[options.magFilter]; - } - if (options.mipFilter !== undefined) { - this._mipFilter = options.mipFilter; - options.mipFilter = FilterIndex[options.mipFilter]; - } - if (options.wrapS !== undefined) { - this._wrapS = options.wrapS; - } - if (options.wrapT !== undefined) { - this._wrapT = options.wrapT; - } - if (options.format !== undefined) { - this._format = options.format; - } - if (options.flipY !== undefined) { - this._flipY = options.flipY; - } - if (options.premultiplyAlpha !== undefined) { - this._premultiplyAlpha = options.premultiplyAlpha; - } - if (options.anisotropy !== undefined) { - this._anisotropy = options.anisotropy; - } - if (options.mipmap !== undefined) { - this._genMipmap = options.mipmap; - } - } - - public _getOpts () { - const opts = _getSharedOptions(); - opts.width = this.width; - opts.height = this.height; - opts.mipmap = this._genMipmap; - opts.format = this._format; - opts.premultiplyAlpha = this._premultiplyAlpha; - opts.anisotropy = this._anisotropy; - opts.flipY = this._flipY; - opts.minFilter = FilterIndex[this._minFilter]; - opts.magFilter = FilterIndex[this._magFilter]; - opts.mipFilter = FilterIndex[this._mipFilter]; - opts.wrapS = this._wrapS; - opts.wrapT = this._wrapT; - return opts; - } - /** * !#en * Pixel format of the texture. * !#zh 获取纹理的像素格式。 - * @method getPixelFormat - * @return {Number} + * @return */ public getPixelFormat () { // support only in WebGl rendering mode @@ -412,8 +291,7 @@ export default class TextureBase extends Asset { * !#en * Whether or not the texture has their Alpha premultiplied. * !#zh 检查纹理在上传 GPU 时预乘选项是否开启。 - * @method hasPremultipliedAlpha - * @return {Boolean} + * @return */ public hasPremultipliedAlpha () { return this._premultiplyAlpha || false; @@ -422,8 +300,7 @@ export default class TextureBase extends Asset { /** * !#en Anisotropy of the texture. * !#zh 获取纹理的各向异性。 - * @method getAnisotropy - * @return {Number} + * @return */ public getAnisotropy () { return this._anisotropy; @@ -433,8 +310,7 @@ export default class TextureBase extends Asset { * !#en * Whether or not to generate mipmap. * !#zh 检查纹理在上传 GPU 时是否生成 mipmap。 - * @method hasMipmap - * @return {Boolean} + * @return */ public genMipmap () { return this._genMipmap || false; @@ -445,46 +321,40 @@ export default class TextureBase extends Asset { * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. * !#zh 设置纹理包装模式。 * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。 - * @method setTexParameters - * @param {WrapMode} wrapS - * @param {WrapMode} wrapT + * @param wrapS + * @param wrapT */ - public setWrapMode (wrapS, wrapT) { + public setWrapMode (wrapS: WrapMode, wrapT: WrapMode) { if (this._wrapS !== wrapS || this._wrapT !== wrapT) { - const opts = _getSharedOptions(); - opts.wrapS = wrapS; - opts.wrapT = wrapT; - this.update(opts); + this._wrapS = wrapS; + this._wrapT = wrapT; + this._updateSampler(); } } /** * !#en Sets the minFilter and magFilter options * !#zh 设置纹理贴图缩小和放大过滤器算法选项。 - * @method setFilters - * @param {Filter} minFilter - * @param {Filter} magFilter + * @param minFilter + * @param magFilter */ - public setFilters (minFilter, magFilter) { + public setFilters (minFilter: Filter, magFilter: Filter) { if (this._minFilter !== minFilter || this._magFilter !== magFilter) { - const opts = _getSharedOptions(); - opts.minFilter = minFilter; - opts.magFilter = magFilter; - this.update(opts); + this._minFilter = minFilter; + this._magFilter = magFilter; + this._updateSampler(); } } /** * !#en Sets the mipFilter options * !#zh 设置纹理Mipmap过滤算法选项。 - * @method setMipFilter - * @param {Filter} mipFilter + * @param mipFilter */ - public setMipFilter (mipFilter) { + public setMipFilter (mipFilter: Filter) { if (this._mipFilter !== mipFilter) { - const opts = _getSharedOptions(); - opts.mipFilter = mipFilter; - this.update(opts); + this._mipFilter = mipFilter; + this._updateSampler(); } } @@ -492,14 +362,12 @@ export default class TextureBase extends Asset { * !#en * Sets the flipY options * !#zh 设置贴图的纵向翻转选项。 - * @method setFlipY - * @param {Boolean} flipY + * @param flipY */ - public setFlipY (flipY) { + public setFlipY (flipY: boolean) { if (this._flipY !== flipY) { - const opts = _getSharedOptions(); - opts.flipY = flipY; - this.update(opts); + this._flipY = flipY; + this._updateSampler(); } } @@ -507,28 +375,24 @@ export default class TextureBase extends Asset { * !#en * Sets the premultiply alpha options * !#zh 设置贴图的预乘选项。 - * @method setPremultiplyAlpha - * @param {Boolean} premultiply + * @param premultiply */ - public setPremultiplyAlpha (premultiply) { + public setPremultiplyAlpha (premultiply: boolean) { if (this._premultiplyAlpha !== premultiply) { - const opts = _getSharedOptions(); - opts.premultiplyAlpha = premultiply; - this.update(opts); + this._premultiplyAlpha = premultiply; + this._updateSampler(); } } /** * !#en Sets the anisotropy of the texture * !#zh 设置贴图的各向异性。 - * @method setAnisotropy - * @param {number} anisotropy + * @param anisotropy */ - public setAnisotropy (anisotropy) { + public setAnisotropy (anisotropy: number) { if (this._anisotropy !== anisotropy) { - const opts = _getSharedOptions(); - opts.anisotropy = anisotropy; - this.update(opts); + this._anisotropy = anisotropy; + this._updateSampler(); } } @@ -536,23 +400,43 @@ export default class TextureBase extends Asset { * !#en * Sets whether generate mipmaps for the texture * !#zh 是否为纹理设置生成 mipmaps。 - * @method setGenerateMipmap - * @param {Boolean} mipmap + * @param mipmap */ - public setGenMipmap (mipmap) { + public setGenMipmap (mipmap: boolean) { if (this._genMipmap !== mipmap) { - const opts = _getSharedOptions(); - opts.mipmap = mipmap; - this.update(opts); + this._genMipmap = mipmap; + this._updateSampler(); } } + public destroy () { + this._destroyTexture(); + + if (this._sampler) { + this._sampler.destroy(); + } + + return true; + } + + public getGFXTexture () { + return this._texture; + } + + public getGFXTextureView () { + return this._textureView; + } + + public getGFXSampler () { + return this._sampler; + } + // SERIALIZATION /** - * @return {any} + * @return */ - public _serialize () { + public _serialize (): any { return this._minFilter + ',' + this._magFilter + ',' + this._wrapS + ',' + this._wrapT + ',' + (this._premultiplyAlpha ? 1 : 0) + ',' + @@ -563,32 +447,141 @@ export default class TextureBase extends Asset { /** * - * @param {string} data + * @param data */ - public _deserialize (data) { + public _deserialize (serializedData: any, handle: any) { + const data = serializedData as string; const fields = data.split(','); fields.unshift(''); if (fields.length >= 6) { // decode filters - this._minFilter = parseInt(fields[1]); - this._magFilter = parseInt(fields[2]); + this._minFilter = parseInt(fields[1], undefined); + this._magFilter = parseInt(fields[2], undefined); // decode wraps - this._wrapS = parseInt(fields[3]); - this._wrapT = parseInt(fields[4]); + this._wrapS = parseInt(fields[3], undefined); + this._wrapT = parseInt(fields[4], undefined); // decode premultiply alpha this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1; } if (fields.length >= 8) { - this._mipFilter = parseInt(fields[6]); - this._anisotropy = parseInt(fields[7]); + this._mipFilter = parseInt(fields[6], undefined); + this._anisotropy = parseInt(fields[7], undefined); } if (fields.length >= 10) { this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1; this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1; } } + + protected _getGlobalDevice (): GFXDevice { + return cc.director.root.device; + } + + protected _getGfxFormat () { + return toGfxFormat(this._format); + } + + protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) { + const upload = () => { this._uploadImage(image, level, arrayIndex); }; + // @ts-ignore + if (image.loaded) { + upload(); + } else { + // @ts-ignore + image.addEventListener('load', () => { + upload(); + }); + } + } + + protected _uploadImage (image: ImageAsset, level: number, arrayIndex?: number) { + if (!this._texture) { + return; + } + + if (level >= this._texture.mipLevel) { + return; + } + + const data = image.data; + if (!data) { + return; + } + + const region: GFXBufferTextureCopy = { + buffOffset: 0, + buffStride: 0, + buffTexHeight: 0, + texOffset: { + x: 0, + y: 0, + z: 0, + }, + texExtent: { + width: this._texture.width, + height: this._texture.height, + depth: 1, + }, + texSubres: { + baseMipLevel: level, + levelCount: 1, + baseArrayLayer: arrayIndex || 0, + layerCount: 1, + }, + }; + + if (data instanceof HTMLElement) { + this._getGlobalDevice().copyImageSourceToTexture(data, this._texture, [region]); + } else { + this._getGlobalDevice().copyBufferToTexture(data.buffer, this._texture, [region]); + } + } + + protected _recreateTexture () { + this._destroyTexture(); + this._createTexture(); + if (this._texture) { + this._width = this._texture.width; + this._height = this._texture.height; + } + this._createTextureView(); + } + + protected _createTexture () { + return; + } + + protected _createTextureView () { + return; + } + + private _destroyTexture () { + if (this._textureView) { + this._textureView.destroy(); + this._textureView = null; + } + + if (this._texture) { + this._texture.destroy(); + this._texture = null; + } + } + + private _updateSampler () { + this._sampler = this._getGlobalDevice().createSampler({ + name: `Sampler of ${this.name}`, + minFilter: toGfxFilterMode(this._minFilter), + magFilter: toGfxFilterMode(this._magFilter), + addressU: toGfxAddressMode(this._wrapS), + addressV: toGfxAddressMode(this._wrapT), + maxAnisotropy: this._anisotropy, + }); + } } +/* tslint:disable:no-string-literal */ +cc['TextureBase'] = TextureBase; + /** * !#zh * 当该资源加载成功后触发该事件 @@ -599,4 +592,3 @@ export default class TextureBase extends Asset { */ addon(TextureBase.prototype, EventTarget.prototype); -cc.TextureBase = TextureBase; diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts index a14ac9e6f0..5d70237897 100644 --- a/cocos/core/data/object.d.ts +++ b/cocos/core/data/object.d.ts @@ -40,8 +40,8 @@ export class CCObject { protected _destruct(): void; protected _destroyImmediate(): void; - protected _serialize: (exporting: boolean) => object | null; - protected _deserialize: (data: object, ctx: object) => object | null; + protected _serialize?(): any; + protected _deserialize?(data: any, ctx: any): any; protected _onPreDestroy: () => void | null; protected Flags: object; } diff --git a/cocos/core/value-types/enum.js b/cocos/core/value-types/enum.js index 755f04cea7..7847d41342 100644 --- a/cocos/core/value-types/enum.js +++ b/cocos/core/value-types/enum.js @@ -118,4 +118,15 @@ if (CC_DEV) { } } +/** + * + * @param {Object} enumx + */ +export function ccenum(enumx) { + if ('__enums__' in enumx) { + return; + } + js.value(enumx, '__enums__', null, true); +} + cc.Enum = Enum; From 3ccb123b9996f1677d916da16fd2833e2a24828f Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 8 Jan 2019 19:48:37 +0800 Subject: [PATCH 063/267] robust --- cocos/3d/assets/texture-cube.ts | 18 ++++++++++++------ cocos/assets/render-texture.ts | 10 +++++++++- cocos/assets/texture-2d.ts | 18 ++++++++++++------ cocos/assets/texture-base.ts | 27 +++++++++++++++++++++++---- 4 files changed, 56 insertions(+), 17 deletions(-) diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 1ad72c8e7e..9a9ce7ccb3 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -163,16 +163,17 @@ export default class TextureCube extends TextureBase { } } - public onLoaded () { - this.mipmaps = this._mipmaps; - } - protected _createTexture () { if (this._mipmaps.length === 0) { return; } - this._texture = this._getGlobalDevice().createTexture({ + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._texture = gfxDevice.createTexture({ type: GFXTextureType.TEX2D, /* tslint:disable:no-bitwise */ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, @@ -196,7 +197,12 @@ export default class TextureCube extends TextureBase { return; } - this._textureView = this._getGlobalDevice().createTextureView({ + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._textureView = gfxDevice.createTextureView({ texture: this._texture, type: GFXTextureViewType.TV2D_ARRAY, format: this._getGfxFormat(), diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts index b83176fe74..72d001bcc6 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/assets/render-texture.ts @@ -51,6 +51,9 @@ export default class RenderTexture extends Texture2D { this.destroy(); const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } const w = Math.floor(width || cc.visibleRect.width); const h = Math.floor(height || cc.visibleRect.height); @@ -179,11 +182,16 @@ export default class RenderTexture extends Texture2D { return undefined; } + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + const normalizedRect = normalizeRect2D(rect, this.width, this.height); data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4); - this._getGlobalDevice().copyFramebufferToBuffer(this._framebuffer, data.buffer, [{ + gfxDevice.copyFramebufferToBuffer(this._framebuffer, data.buffer, [{ buffOffset: 0, buffStride: 0, buffTexHeight: 0, diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index f52c059f3c..faf0eff38d 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -175,16 +175,17 @@ export default class Texture2D extends TextureBase { } } - public onLoaded () { - this.mipmaps = this._mipmaps; - } - protected _createTexture () { if (this._mipmaps.length === 0) { return; } - this._texture = this._getGlobalDevice().createTexture({ + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._texture = gfxDevice.createTexture({ type: GFXTextureType.TEX2D, /* tslint:disable:no-bitwise */ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, @@ -205,7 +206,12 @@ export default class Texture2D extends TextureBase { return; } - this._textureView = this._getGlobalDevice().createTextureView({ + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._textureView = gfxDevice.createTextureView({ texture: this._texture, type: GFXTextureViewType.TV2D, format: this._getGfxFormat(), diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 499e304b19..fb0a4cdf93 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -473,7 +473,12 @@ export default class TextureBase extends Asset { } } - protected _getGlobalDevice (): GFXDevice { + public onLoaded () { + this._updateSampler(); + this._recreateTexture(); + } + + protected _getGlobalDevice (): GFXDevice | null { return cc.director.root.device; } @@ -508,6 +513,11 @@ export default class TextureBase extends Asset { return; } + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + const region: GFXBufferTextureCopy = { buffOffset: 0, buffStride: 0, @@ -531,9 +541,9 @@ export default class TextureBase extends Asset { }; if (data instanceof HTMLElement) { - this._getGlobalDevice().copyImageSourceToTexture(data, this._texture, [region]); + gfxDevice.copyImageSourceToTexture(data, this._texture, [region]); } else { - this._getGlobalDevice().copyBufferToTexture(data.buffer, this._texture, [region]); + gfxDevice.copyBufferToTexture(data.buffer, this._texture, [region]); } } @@ -568,7 +578,16 @@ export default class TextureBase extends Asset { } private _updateSampler () { - this._sampler = this._getGlobalDevice().createSampler({ + if (this._sampler) { + this._sampler.destroy(); + } + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; + } + + this._sampler = gfxDevice.createSampler({ name: `Sampler of ${this.name}`, minFilter: toGfxFilterMode(this._minFilter), magFilter: toGfxFilterMode(this._magFilter), From b89c77129023e308ada346c99bff528bc804ef52 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 8 Jan 2019 19:56:51 +0800 Subject: [PATCH 064/267] add rotate function to node --- cocos/core/vmath/quat.ts | 123 ++++++++++++++++++++--------- cocos/gfx/define.ts | 30 +++---- cocos/gfx/device.ts | 140 ++++++++++++++++----------------- cocos/renderer/scene/camera.ts | 42 +++++++--- cocos/renderer/scene/model.ts | 2 +- cocos/scene-graph/node.js | 68 ++++++++++++++-- 6 files changed, 265 insertions(+), 140 deletions(-) diff --git a/cocos/core/vmath/quat.ts b/cocos/core/vmath/quat.ts index 348b037cb9..cdc51b966b 100644 --- a/cocos/core/vmath/quat.ts +++ b/cocos/core/vmath/quat.ts @@ -24,7 +24,7 @@ export default class quat { * @param w - Value assigned to w component. * @return The newly created quaternion. */ - public static create (x = 0, y = 0, z = 0, w = 1) { + public static create(x = 0, y = 0, z = 0, w = 1) { return new quat(x, y, z, w); } @@ -34,7 +34,7 @@ export default class quat { * @param a - Quaternion to clone. * @return The newly created quaternion. */ - public static clone (a: quat) { + public static clone(a: quat) { return new quat(a.x, a.y, a.z, a.w); } @@ -45,7 +45,7 @@ export default class quat { * @param a - The specified quaternion. * @return out. */ - public static copy (out: Out, a: quat) { + public static copy(out: Out, a: quat) { return vec4.copy(out, a); } @@ -59,7 +59,7 @@ export default class quat { * @param w - Value set to w component. * @return out. */ - public static set (out: Out, x: number, y: number, z: number, w: number) { + public static set(out: Out, x: number, y: number, z: number, w: number) { out.x = x; out.y = y; out.z = z; @@ -73,7 +73,7 @@ export default class quat { * @param out - Quaternion to set. * @return out. */ - public static identity (out: Out) { + public static identity(out: Out) { out.x = 0; out.y = 0; out.z = 0; @@ -92,7 +92,7 @@ export default class quat { * @param b - The destination vector. * @return out. */ - public static rotationTo (out: Out, a: vec3, b: vec3) { + public static rotationTo(out: Out, a: vec3, b: vec3) { const dot = vec3.dot(a, b); if (dot < -0.999999) { vec3.cross(tmpVec3, tmpXUnitVec3, a); @@ -131,7 +131,7 @@ export default class quat { * @param {quat} q - Quaternion to be decomposed. * @return - Angle, in radians, of the rotation. */ - public static getAxisAngle (outAxis: Out, q: quat) { + public static getAxisAngle(outAxis: Out, q: quat) { const rad = Math.acos(q.w) * 2.0; const s = Math.sin(rad / 2.0); if (s !== 0.0) { @@ -155,7 +155,7 @@ export default class quat { * @param b - The second operand. * @return out. */ - public static multiply (out: Out, a: quat, b: quat) { + public static multiply(out: Out, a: quat, b: quat) { const { x: ax, y: ay, z: az, w: aw } = a; const { x: bx, y: by, z: bz, w: bw } = b; @@ -169,7 +169,7 @@ export default class quat { /** * Alias of {@link quat.multiply}. */ - public static mul (out: Out, a: quat, b: quat) { + public static mul(out: Out, a: quat, b: quat) { return quat.multiply(out, a, b); } @@ -181,7 +181,7 @@ export default class quat { * @param b - The scale number. * @return out. */ - public static scale (out: Out, a: quat, b: number) { + public static scale(out: Out, a: quat, b: number) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -197,7 +197,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateX (out: Out, a: quat, rad: number) { + public static rotateX(out: Out, a: quat, rad: number) { rad *= 0.5; const { x: ax, y: ay, z: az, w: aw } = a; @@ -219,7 +219,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateY (out: Out, a: quat, rad: number) { + public static rotateY(out: Out, a: quat, rad: number) { rad *= 0.5; const { x: ax, y: ay, z: az, w: aw } = a; @@ -241,7 +241,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateZ (out: Out, a: quat, rad: number) { + public static rotateZ(out: Out, a: quat, rad: number) { rad *= 0.5; const { x: ax, y: ay, z: az, w: aw } = a; @@ -264,7 +264,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateAround (out: Out, rot: quat, axis: IVec3Like, rad: number) { + public static rotateAround(out: Out, rot: quat, axis: IVec3Like, rad: number) { // get inv-axis (local to rot) quat.invert(tmpQuat1, rot); vec3.transformQuat(tmpVec3, axis, tmpQuat1); @@ -283,7 +283,7 @@ export default class quat { * @param rad - Angle (in radians) to rotate. * @return out. */ - public static rotateAroundLocal (out: Out, rot: quat, axis: IVec3Like, rad: number) { + public static rotateAroundLocal(out: Out, rot: quat, axis: IVec3Like, rad: number) { quat.fromAxisAngle(tmpQuat1, axis, rad); quat.mul(out, rot, tmpQuat1); return out; @@ -298,7 +298,7 @@ export default class quat { * @param a - Quaternion to calculate W. * @return out. */ - public static calculateW (out: Out, a: quat) { + public static calculateW(out: Out, a: quat) { const { x, y, z } = a; out.x = x; @@ -315,7 +315,7 @@ export default class quat { * @param b - The second operand. * @return - The dot product of a and b. */ - public static dot (a: quat, b: quat) { + public static dot(a: quat, b: quat) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } @@ -328,7 +328,7 @@ export default class quat { * @param t - The interpolation coefficient. * @return out. */ - public static lerp (out: Out, a: quat, b: quat, t: number) { + public static lerp(out: Out, a: quat, b: quat, t: number) { const { x: ax, y: ay, z: az, w: aw } = a; out.x = ax + t * (b.x - ax); out.y = ay + t * (b.y - ay); @@ -346,7 +346,7 @@ export default class quat { * @param t - The interpolation coefficient. * @return out. */ - public static slerp (out: Out, a: quat, b: quat, t: number) { + public static slerp(out: Out, a: quat, b: quat, t: number) { // benchmarks: // http://jsperf.com/quaternion-slerp-implementations @@ -399,7 +399,7 @@ export default class quat { * @param t - The interpolation coefficient. * @return out */ - public static sqlerp (out: Out, a: quat, b: quat, c: quat, d: quat, t: number) { + public static sqlerp(out: Out, a: quat, b: quat, c: quat, d: quat, t: number) { quat.slerp(tmpQuat1, a, d, t); quat.slerp(tmpQuat2, b, c, t); quat.slerp(out, tmpQuat1, tmpQuat2, 2 * t * (1 - t)); @@ -413,7 +413,7 @@ export default class quat { * @param a - Quaternion to calculate inverse of. * @return out. */ - public static invert (out: Out, a: quat) { + public static invert(out: Out, a: quat) { const { x: a0, y: a1, z: a2, w: a3 } = a; const dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; const invDot = dot ? 1.0 / dot : 0; @@ -435,7 +435,7 @@ export default class quat { * @param a - Quaternion to calculate conjugate of. * @return out. */ - public static conjugate (out: Out, a: quat) { + public static conjugate(out: Out, a: quat) { out.x = -a.x; out.y = -a.y; out.z = -a.z; @@ -449,7 +449,7 @@ export default class quat { * @param a - The quaternion. * @return Length of the quaternion. */ - public static magnitude (a: quat) { + public static magnitude(a: quat) { const { x, y, z, w } = a; return Math.sqrt(x * x + y * y + z * z + w * w); } @@ -457,7 +457,7 @@ export default class quat { /** * Alias of {@link quat.magnitude}. */ - public static mag (a: quat) { + public static mag(a: quat) { return quat.magnitude(a); } @@ -467,7 +467,7 @@ export default class quat { * @param a - The quaternion. * @return Squared length of the quaternion. */ - public static squaredMagnitude (a: quat) { + public static squaredMagnitude(a: quat) { const { x, y, z, w } = a; return x * x + y * y + z * z + w * w; } @@ -475,7 +475,7 @@ export default class quat { /** * Alias of {@link quat.squaredMagnitude} */ - public static sqrMag (a: quat) { + public static sqrMag(a: quat) { return quat.squaredMagnitude(a); } @@ -487,7 +487,7 @@ export default class quat { * @return out. * @function */ - public static normalize (out: Out, a: quat) { + public static normalize(out: Out, a: quat) { const { x, y, z, w } = a; let len = x * x + y * y + z * z + w * w; if (len > 0) { @@ -511,7 +511,7 @@ export default class quat { * @param zAxis - Vector representing the viewing direction. * @return out. */ - public static fromAxes (out: Out, xAxis: IVec3Like, yAxis: IVec3Like, zAxis: IVec3Like) { + public static fromAxes(out: Out, xAxis: IVec3Like, yAxis: IVec3Like, zAxis: IVec3Like) { mat3.set(tmpMat3, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, @@ -529,7 +529,7 @@ export default class quat { * * @return out. */ - public static fromViewUp (out: Out, view: IVec3Like, up: IVec3Like) { + public static fromViewUp(out: Out, view: IVec3Like, up: IVec3Like) { mat3.fromViewUp(tmpMat3, view, up); return quat.normalize(out, quat.fromMat3(out, tmpMat3)); } @@ -543,7 +543,7 @@ export default class quat { * @param rad - The angle in radians. * @return out. */ - public static fromAxisAngle (out: Out, axis: IVec3Like, rad: number) { + public static fromAxisAngle(out: Out, axis: IVec3Like, rad: number) { rad = rad * 0.5; const s = Math.sin(rad); out.x = s * axis.x; @@ -564,7 +564,7 @@ export default class quat { * @return out. * @function */ - public static fromMat3 (out: Out, m: IMat3Like) { + public static fromMat3(out: Out, m: IMat3Like) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm const { @@ -621,7 +621,7 @@ export default class quat { * @return out. * @function */ - public static fromEuler (out: Out, x: number, y: number, z: number) { + public static fromEuler(out: Out, x: number, y: number, z: number) { x *= halfToRad; y *= halfToRad; z *= halfToRad; @@ -641,6 +641,53 @@ export default class quat { return out; } + /** + * Returns the X orthonormal axis defining the quaternion. + * + * @param out - X axis. + * @param q - The quaternion. + * @function + */ + public static toAxisX(out: vec3, q: quat) { + let fy = 2.0 * q.y; + let fz = 2.0 * q.z; + out.x = 1.0 - fy * q.y - fz * q.z; + out.y = fy * q.x + fz * q.w; + out.z = fz * q.x + fy * q.w; + } + + /** + * Returns the Y orthonormal axis defining the quaternion. + * + * @param out - Y axis. + * @param q - The quaternion. + * @function + */ + public static toAxisY(out: vec3, q: quat) { + let fx = 2.0 * q.x; + let fy = 2.0 * q.y; + let fz = 2.0 * q.z; + out.x = fy * q.x - fz * q.w; + out.y = 1.0 - fx * q.x - fz * q.z; + out.z = fz * q.y + fx * q.w; + } + + /** + * Returns the Z orthonormal axis defining the quaternion. + * + * @param out - Z axis. + * @param q - The quaternion. + * @function + */ + public static toAxisZ(out: vec3, q: quat) { + let fx = 2.0 * q.x; + let fy = 2.0 * q.y; + let fz = 2.0 * q.z; + out.x = fz * q.x - fy * q.w; + out.y = fz * q.y - fx * q.w; + out.z = 1.0 - fx * q.x - fy * q.y; + } + /** * Convert a quaternion back to euler angle (in degrees). * @@ -648,7 +695,7 @@ export default class quat { * @param q - the quaternion to be converted * @return out. */ - public static toEuler (out: Out, q: quat) { + public static toEuler(out: Out, q: quat) { const { x, y, z, w } = q; let heading: number = 0; let attitude: number = 0; @@ -687,7 +734,7 @@ export default class quat { * @param a - The quaternion. * @return - String representation of this quaternion. */ - public static str (a: quat) { + public static str(a: quat) { return `quat(${a.x}, ${a.y}, ${a.z}, ${a.w})`; } @@ -698,7 +745,7 @@ export default class quat { * @param q - The quaternion. * @return out. */ - public static array> (out: Out, q: quat) { + public static array>(out: Out, q: quat) { out[0] = q.x; out[1] = q.y; out[2] = q.z; @@ -714,7 +761,7 @@ export default class quat { * @param b - The second quaternion. * @return True if the quaternions are equal, false otherwise. */ - public static exactEquals (a: quat, b: quat) { + public static exactEquals(a: quat, b: quat) { return vec4.exactEquals(a, b); } @@ -725,7 +772,7 @@ export default class quat { * @param b The second quaternion. * @return True if the quaternions are approximately equal, false otherwise. */ - public static equals (a: quat, b: quat) { + public static equals(a: quat, b: quat) { return vec4.equals(a, b); } @@ -757,7 +804,7 @@ export default class quat { * @param z - Value assigned to z component. * @param w - Value assigned to w component. */ - constructor (x = 0, y = 0, z = 0, w = 1) { + constructor(x = 0, y = 0, z = 0, w = 1) { this.x = x; this.y = y; this.z = z; diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 7d21a511d3..eb4da23120 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -450,27 +450,27 @@ export interface GFXExtent { } export class GFXTextureSubres { - baseMipLevel: number = 0; - levelCount: number = 1; - baseArrayLayer: number = 0; - layerCount: number = 1; + public baseMipLevel: number = 0; + public levelCount: number = 1; + public baseArrayLayer: number = 0; + public layerCount: number = 1; } export class GFXTextureCopy { - srcSubres: GFXTextureSubres = new GFXTextureSubres; - srcOffset: GFXOffset = { x: 0, y: 0, z: 0 }; - dstSubres: GFXTextureSubres = new GFXTextureSubres; - dstOffset: GFXOffset = { x: 0, y: 0, z: 0 }; - extent: GFXExtent = { width: 0, height: 0, depth: 0 }; + public srcSubres: GFXTextureSubres = new GFXTextureSubres; + public srcOffset: GFXOffset = { x: 0, y: 0, z: 0 }; + public dstSubres: GFXTextureSubres = new GFXTextureSubres; + public dstOffset: GFXOffset = { x: 0, y: 0, z: 0 }; + public extent: GFXExtent = { width: 0, height: 0, depth: 0 }; } export class GFXBufferTextureCopy { - buffOffset: number = 0; - buffStride: number = 0; - buffTexHeight: number = 0; - texOffset: GFXOffset = { x: 0, y: 0, z: 0 }; - texExtent: GFXExtent = { width: 0, height: 0, depth: 0 }; - texSubres: GFXTextureSubres = new GFXTextureSubres; + public buffOffset: number = 0; + public buffStride: number = 0; + public buffTexHeight: number = 0; + public texOffset: GFXOffset = { x: 0, y: 0, z: 0 }; + public texExtent: GFXExtent = { width: 0, height: 0, depth: 0 }; + public texSubres: GFXTextureSubres = new GFXTextureSubres; } export interface GFXFormatInfo { diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index e37c42ef07..0a9e3b6a21 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -1,136 +1,109 @@ +import { GFXBindingLayout, GFXBindingLayoutInfo } from './binding-layout'; import { GFXBuffer, GFXBufferInfo } from './buffer'; +import { GFXCommandAllocator, GFXCommandAllocatorInfo } from './command-allocator'; +import { GFXCommandBuffer, GFXCommandBufferInfo } from './command-buffer'; +import { GFXBufferTextureCopy, GFXFormat } from './define'; +import { GFXFramebuffer, GFXFramebufferInfo } from './framebuffer'; +import { GFXInputAssembler, GFXInputAssemblerInfo } from './input-assembler'; +import { GFXPipelineLayout, GFXPipelineLayoutInfo } from './pipeline-layout'; +import { GFXPipelineState, GFXPipelineStateInfo } from './pipeline-state'; import { GFXQueue, GFXQueueInfo } from './queue'; +import { GFXRenderPass, GFXRenderPassInfo } from './render-pass'; +import { GFXSampler, GFXSamplerInfo } from './sampler'; +import { GFXShader, GFXShaderInfo } from './shader'; import { GFXTexture, GFXTextureInfo } from './texture'; -import { GFXTextureViewInfo, GFXTextureView } from './texture-view'; -import { GFXFramebufferInfo, GFXFramebuffer } from './framebuffer'; -import { GFXRenderPassInfo, GFXRenderPass } from './render-pass'; -import { GFXPipelineStateInfo, GFXPipelineState } from './pipeline-state'; -import { GFXPipelineLayoutInfo, GFXPipelineLayout } from './pipeline-layout'; -import { GFXSamplerInfo, GFXSampler } from './sampler'; -import { GFXShaderInfo, GFXShader } from './shader'; -import { GFXInputAssemblerInfo, GFXInputAssembler } from './input-assembler'; -import { GFXCommandBufferInfo, GFXCommandBuffer } from './command-buffer'; -import { GFXCommandAllocatorInfo, GFXCommandAllocator } from './command-allocator'; -import { GFXWindowInfo, GFXWindow } from './window'; -import { GFXBindingLayoutInfo, GFXBindingLayout } from './binding-layout'; -import { GFXRect, GFXBufferTextureCopy, GFXFormat } from './define'; +import { GFXTextureView, GFXTextureViewInfo } from './texture-view'; +import { GFXWindow, GFXWindowInfo } from './window'; export enum GFXFeature { -}; +} export interface GFXDeviceInfo { canvasElm: HTMLElement; isAntialias?: boolean; isPremultipliedAlpha?: boolean; -}; +} export abstract class GFXDevice { - public abstract initialize(info: GFXDeviceInfo): boolean; - public abstract destroy(): void; - public abstract createBuffer(info: GFXBufferInfo): GFXBuffer | null; - public abstract createTexture(info: GFXTextureInfo): GFXTexture | null; - public abstract createTextureView(info: GFXTextureViewInfo): GFXTextureView | null; - public abstract createSampler(info: GFXSamplerInfo): GFXSampler | null; - public abstract createBindingLayout(info: GFXBindingLayoutInfo): GFXBindingLayout | null; - public abstract createShader(info: GFXShaderInfo): GFXShader | null; - public abstract createInputAssembler(info: GFXInputAssemblerInfo): GFXInputAssembler | null; - public abstract createRenderPass(info: GFXRenderPassInfo): GFXRenderPass | null; - public abstract createFramebuffer(info: GFXFramebufferInfo): GFXFramebuffer | null; - public abstract createPipelineLayout(info: GFXPipelineLayoutInfo): GFXPipelineLayout | null; - public abstract createPipelineState(info: GFXPipelineStateInfo): GFXPipelineState | null; - public abstract createCommandAllocator(info: GFXCommandAllocatorInfo): GFXCommandAllocator | null; - public abstract createCommandBuffer(info: GFXCommandBufferInfo): GFXCommandBuffer | null; - public abstract createQueue(info: GFXQueueInfo): GFXQueue | null; - public abstract createWindow(info: GFXWindowInfo): GFXWindow | null; - public abstract present(); - - public abstract copyBufferToTexture(buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); - public abstract copyImageSourceToTexture(source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]); - public abstract copyFramebufferToBuffer(srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]); - - public get canvas(): HTMLCanvasElement { - return this._canvas; + public get canvas (): HTMLCanvasElement { + return this._canvas as HTMLCanvasElement; } - public get canvas2D(): HTMLCanvasElement { - return this._canvas2D; + public get canvas2D (): HTMLCanvasElement { + return this._canvas2D as HTMLCanvasElement; } - public get queue(): GFXQueue { - return this._queue; + public get queue (): GFXQueue { + return this._queue as GFXQueue; } - public get width(): number { + public get width (): number { return this._width; } - public get height(): number { + public get height (): number { return this._height; } - public get mainWindow(): GFXWindow { - return this._mainWindow; + public get mainWindow (): GFXWindow { + return this._mainWindow as GFXWindow; } - public get commandAllocator(): GFXCommandAllocator { - return this._cmdAllocator; + public get commandAllocator (): GFXCommandAllocator { + return this._cmdAllocator as GFXCommandAllocator; } - public get renderer(): string { + public get renderer (): string { return this._renderer; } - public get vendor(): string { + public get vendor (): string { return this._vendor; } - public get maxVertexAttributes(): number { + public get maxVertexAttributes (): number { return this._maxVertexAttributes; } - public get maxVertexUniformVectors(): number { + public get maxVertexUniformVectors (): number { return this._maxVertexUniformVectors; } - public get maxFragmentUniformVectors(): number { + public get maxFragmentUniformVectors (): number { return this._maxFragmentUniformVectors; } - public get maxTextureUnits(): number { + public get maxTextureUnits (): number { return this._maxTextureUnits; } - public get maxVertexTextureUnits(): number { + public get maxVertexTextureUnits (): number { return this._maxVertexTextureUnits; } - public get depthBits(): number { + public get depthBits (): number { return this._depthBits; } - public get stencilBits(): number { + public get stencilBits (): number { return this._stencilBits; } - public get colorFormat(): GFXFormat { + public get colorFormat (): GFXFormat { return this._colorFmt; } - public get depthStencilFormat(): GFXFormat { + public get depthStencilFormat (): GFXFormat { return this._depthStencilFmt; } - public genShaderId(): number { - return this._shaderIdGen++; - } - protected _canvas: HTMLCanvasElement | null = null; protected _canvas2D: HTMLCanvasElement | null = null; - protected _deviceName: string = ""; - protected _renderer: string = ""; - protected _vendor: string = ""; - protected _version: string = ""; + protected _deviceName: string = ''; + protected _renderer: string = ''; + protected _vendor: string = ''; + protected _version: string = ''; protected _queue: GFXQueue | null = null; protected _width: number = 0; protected _height: number = 0; @@ -146,4 +119,31 @@ export abstract class GFXDevice { protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; protected _shaderIdGen: number = 0; -}; + + public abstract initialize (info: GFXDeviceInfo): boolean; + public abstract destroy (): void; + public abstract createBuffer (info: GFXBufferInfo): GFXBuffer | null; + public abstract createTexture (info: GFXTextureInfo): GFXTexture | null; + public abstract createTextureView (info: GFXTextureViewInfo): GFXTextureView | null; + public abstract createSampler (info: GFXSamplerInfo): GFXSampler | null; + public abstract createBindingLayout (info: GFXBindingLayoutInfo): GFXBindingLayout | null; + public abstract createShader (info: GFXShaderInfo): GFXShader | null; + public abstract createInputAssembler (info: GFXInputAssemblerInfo): GFXInputAssembler | null; + public abstract createRenderPass (info: GFXRenderPassInfo): GFXRenderPass | null; + public abstract createFramebuffer (info: GFXFramebufferInfo): GFXFramebuffer | null; + public abstract createPipelineLayout (info: GFXPipelineLayoutInfo): GFXPipelineLayout | null; + public abstract createPipelineState (info: GFXPipelineStateInfo): GFXPipelineState | null; + public abstract createCommandAllocator (info: GFXCommandAllocatorInfo): GFXCommandAllocator | null; + public abstract createCommandBuffer (info: GFXCommandBufferInfo): GFXCommandBuffer | null; + public abstract createQueue (info: GFXQueueInfo): GFXQueue | null; + public abstract createWindow (info: GFXWindowInfo): GFXWindow | null; + public abstract present (); + + public abstract copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyImageSourceToTexture (source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]); + public abstract copyFramebufferToBuffer (srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]); + + public genShaderId (): number { + return this._shaderIdGen++; + } +} diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index cc2435d8fc..6b59e7c0de 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -126,13 +126,31 @@ export class Camera { return this._position; } - public rotate(axis: vec3, rad: number, ns?: NodeSpace) { + public rotate(rot: quat, ns?: NodeSpace) { + let space = (ns !== undefined? ns : NodeSpace.LOCAL); + if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + this._node.rotate(rot); + } else if (space === NodeSpace.WORLD) { + this._node.rotateWorld(rot); + } + } + + public rotateFromAxisAngle(axis: vec3, rad: number, ns?: NodeSpace) { quat.fromAxisAngle(this._rotation, axis, rad); let space = (ns !== undefined? ns : NodeSpace.LOCAL); if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.setRotation(this._rotation); + this._node.rotate(this._rotation); } else if (space === NodeSpace.WORLD) { - this._node.setWorldRotation(this._rotation); + this._node.rotateWorld(this._rotation); + } + } + + public setRotation(rot: quat, ns?: NodeSpace) { + let space = (ns !== undefined? ns : NodeSpace.LOCAL); + if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + this._node.setRotation(rot); + } else if (space === NodeSpace.WORLD) { + this._node.setWorldRotation(rot); } } @@ -140,10 +158,12 @@ export class Camera { let space = (ns !== undefined? ns : NodeSpace.LOCAL); if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.getRotation(this._rotation); - this.rotate(this._rotation, rad, ns); + quat.toAxisX(this._direction, this._rotation); + this.rotateFromAxisAngle(this._direction, rad, ns); } else if (space === NodeSpace.WORLD) { this._node.getWorldRotation(this._rotation); - this.rotate(this._rotation, rad, ns); + quat.toAxisX(this._direction, this._rotation); + this.rotateFromAxisAngle(this._direction, rad, ns); } } @@ -151,10 +171,12 @@ export class Camera { let space = (ns !== undefined? ns : NodeSpace.LOCAL); if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.getRotation(this._rotation); - this.rotate(this._rotation, rad, ns); + quat.toAxisY(this._direction, this._rotation); + this.rotateFromAxisAngle(this._direction, rad, ns); } else if (space === NodeSpace.WORLD) { this._node.getWorldRotation(this._rotation); - this.rotate(this._rotation, rad, ns); + quat.toAxisY(this._direction, this._rotation); + this.rotateFromAxisAngle(this._direction, rad, ns); } } @@ -162,10 +184,12 @@ export class Camera { let space = (ns !== undefined? ns : NodeSpace.LOCAL); if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.getRotation(this._rotation); - this.rotate(this._rotation, rad, ns); + quat.toAxisZ(this._direction, this._rotation); + this.rotateFromAxisAngle(this._direction, rad, ns); } else if (space === NodeSpace.WORLD) { this._node.getWorldRotation(this._rotation); - this.rotate(this._rotation, rad, ns); + quat.toAxisZ(this._direction, this._rotation); + this.rotateFromAxisAngle(this._direction, rad, ns); } } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index f882b0b7b3..ac9f6105ce 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -151,7 +151,7 @@ export default class Model { } recordCommandBuffer(index: number) { - let pass = this._material.passes[index]; + let pass = (this._material).passes[index]; let cmdBufferInfo = { allocator: cc.director.root.device.commandAllocator, type: GFXCommandBufferType.SECONDARY, diff --git a/cocos/scene-graph/node.js b/cocos/scene-graph/node.js index d44462ec46..429af2c35b 100644 --- a/cocos/scene-graph/node.js +++ b/cocos/scene-graph/node.js @@ -7,6 +7,7 @@ import { ccclass, property, mixins } from '../core/data/class-decorator'; let v3_a = cc.v3(); let q_a = cc.quat(); +let q_b = cc.quat(); let array_a = new Array(10); let EventType = cc.Enum({ @@ -67,13 +68,13 @@ class Node extends BaseNode { _eulerDirty = false; // is node but not scene - static isNode (obj) { + static isNode(obj) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); } static EventType = EventType; - constructor (name) { + constructor(name) { super(name); EventTarget.call(this); } @@ -158,11 +159,11 @@ class Node extends BaseNode { while (i) { child = array_a[--i]; if (cur) { - vec3.mul(child._pos, child._lpos, cur._scale); - vec3.transformQuat(child._pos, child._pos, cur._rot); - vec3.add(child._pos, child._pos, cur._pos); - quat.mul(child._rot, cur._rot, child._lrot); - vec3.mul(child._scale, cur._scale, child._lscale); + vec3.mul(child._pos, child._lpos, cur._scale); + vec3.transformQuat(child._pos, child._pos, cur._rot); + vec3.add(child._pos, child._pos, cur._pos); + quat.mul(child._rot, cur._rot, child._lrot); + vec3.mul(child._scale, cur._scale, child._lscale); } child._matDirty = true; // further deferred eval child._dirty = false; @@ -211,6 +212,59 @@ class Node extends BaseNode { } } + /** + * rotate in local space + * + * @param {quat|number} val the new local rotation, or the x component of it + * @param {number} [y] the y component of the new local rotation + * @param {number} [z] the z component of the new local rotation + * @param {number} [w] the w component of the new local rotation + */ + rotate(val, y, z, w) { + + if (arguments.length === 1) { + quat.normalize(q_a, val); + } else if (arguments.length === 4) { + quat.set(q_a, val, y, z, w); + quat.normalize(q_a, q_a); + } + + quat.multiply(this._lrot, this._lrot, q_a); + + this._eulerDirty = true; + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * rotate in world space + * + * @param {quat|number} val the new local rotation, or the x component of it + * @param {number} [y] the y component of the new local rotation + * @param {number} [z] the z component of the new local rotation + * @param {number} [w] the w component of the new local rotation + */ + rotateWorld(val, y, z, w) { + + if (arguments.length === 1) { + quat.normalize(q_a, val); + } else if (arguments.length === 4) { + quat.set(q_a, val, y, z, w); + quat.normalize(q_a, q_a); + } + + getWorldRotation(q_b); + quat.invert(q_b); + quat.multiply(q_a, q_a, q_b); + quat.multiply(this._lrot, this._lrot, q_a); + + this._eulerDirty = true; + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + /** * set local rotation * @param {quat|number} val the new local rotation, or the x component of it From 6172f7d23b55fb752d1cc165817ac6f19a967764 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Tue, 8 Jan 2019 19:58:52 +0800 Subject: [PATCH 065/267] fix model --- cocos/3d/framework/model-component.js | 6 +++--- cocos/renderer/scene/model.ts | 23 +++++++++++------------ cocos/renderer/scene/render-scene.ts | 2 +- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index c8a4310491..27893eef00 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -223,8 +223,8 @@ export default class ModelComponent extends RenderableComponent { let material = this.getSharedMaterial(i); let inputAssembler = this._mesh.getSubMesh(i); - model.setInputAssembler(inputAssembler); - model.setNode(this.node); + model.inputAssembler = inputAssembler; + model.node = this.node; this._updateModelMaterial(model, material); } } @@ -247,7 +247,7 @@ export default class ModelComponent extends RenderableComponent { * @param {Material} material */ _updateModelMaterial(model, material) { - model.setMaterial(material ? material : this._getBuiltinMaterial()); + model.material = material ? material : this._getBuiltinMaterial(); } _updateCastShadow() { diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index d7d77d4c27..a1f7fe4c2f 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -61,7 +61,7 @@ export default class Model { this._cmdBuffers = new Array(); } - setScene(scene: RenderScene) { + set scene(scene: RenderScene | null) { this._scene = scene; if (this._scene) { @@ -107,7 +107,7 @@ export default class Model { * Get the hosting node of this camera * @returns {Node} the hosting node */ - getNode(): Node { + get node(): Node { return this._node; } @@ -115,7 +115,7 @@ export default class Model { * Set the hosting node of this model * @param {Node} node the hosting node */ - setNode(node: Node) { + set node(node: Node) { this._node = node; } @@ -123,7 +123,7 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - setInputAssembler(ia: GFXInputAssembler) { + set inputAssembler(ia: GFXInputAssembler) { this._inputAssembler = ia; } @@ -143,11 +143,14 @@ export default class Model { } } - setMaterial(material: Material) { + set material(material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { this.recordCommandBuffer(i); } + for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { + this._cmdBuffers.pop().destroy(); + } } recordCommandBuffer(index: number) { @@ -158,10 +161,6 @@ export default class Model { }; if (this._cmdBuffers[index] == null) this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); - else { - this._cmdBuffers[index].destroy(); - this._cmdBuffers[index].initialize(cmdBufferInfo); - } this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); @@ -174,15 +173,15 @@ export default class Model { * Set the user key * @param {number} key */ - setUserKey(key: number) { + set userKey(key: number) { this._userKey = key; } - getPassList(): Pass[] { + get passList(): Pass[] { return (this._material).passes; } - getCmdBufferList(): GFXCommandBuffer[] { + get cmdBufferList(): GFXCommandBuffer[] { return this._cmdBuffers; } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index d8ef313727..044286e592 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -119,7 +119,7 @@ export class RenderScene { public createModel(clazz: new () => T): Model { let model = new clazz; - model.setScene(this); + model.scene = this; this._models.push(model); return model; } From d9af01cdc5a2ce95b5f98d4f2edf52b893fe9ff5 Mon Sep 17 00:00:00 2001 From: Weiliang Wang Date: Tue, 8 Jan 2019 20:09:31 +0800 Subject: [PATCH 066/267] Revert "Event fix" --- ...lbacks-invoker.ts => callbacks-invoker.js} | 180 +++++++----- .../{event-target.ts => event-target.js} | 117 ++++---- cocos/core/event/event.js | 269 ++++++++++++++++++ cocos/core/event/event.ts | 222 --------------- cocos/core/event/{index.ts => index.js} | 2 +- 5 files changed, 435 insertions(+), 355 deletions(-) rename cocos/core/event/{callbacks-invoker.ts => callbacks-invoker.js} (62%) rename cocos/core/event/{event-target.ts => event-target.js} (73%) create mode 100644 cocos/core/event/event.js delete mode 100644 cocos/core/event/event.ts rename cocos/core/event/{index.ts => index.js} (96%) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.js similarity index 62% rename from cocos/core/event/callbacks-invoker.ts rename to cocos/core/event/callbacks-invoker.js index 56ded45fa0..5f05aec478 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.js @@ -28,18 +28,17 @@ import * as js from '../utils/js'; const fastRemoveAt = js.array.fastRemoveAt; class CallbackList { - public callbacks: Array = []; + constructor () { + this.callbacks = []; + this.targets = []; // same length with callbacks, nullable + this.isInvoking = false; + this.containCanceled = false; + } - public targets: Array = []; // same length with callbacks, nullable - - public isInvoking = false; - - public containCanceled = false; - - public removeBy (array, value) { - const callbacks = this.callbacks; - const targets = this.targets; - for (let i = 0; i < array.length; ++i) { + removeBy (array, value) { + var callbacks = this.callbacks; + var targets = this.targets; + for (var i = 0; i < array.length; ++i) { if (array[i] === value) { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); @@ -48,14 +47,14 @@ class CallbackList { } } - public cancel (index: number) { + cancel (index) { this.callbacks[index] = this.targets[index] = null; this.containCanceled = true; } - public cancelAll () { - const callbacks = this.callbacks; - const targets = this.targets; + cancelAll () { + let callbacks = this.callbacks; + let targets = this.targets; for (let i = 0; i < callbacks.length; i++) { callbacks[i] = targets[i] = null; } @@ -63,14 +62,14 @@ class CallbackList { } // filter all removed callbacks and compact array - public purgeCanceled () { + purgeCanceled () { this.removeBy(this.callbacks, null); this.containCanceled = false; } } const MAX_SIZE = 16; -const callbackListPool = new js.Pool((list: CallbackList) => { +let callbackListPool = new js.Pool(function (list) { list.callbacks.length = 0; list.targets.length = 0; list.isInvoking = false; @@ -80,10 +79,6 @@ callbackListPool.get = function () { return this._get() || new CallbackList(); }; -interface ICallbackTable { - [x: string]: CallbackList | undefined; -} - /** * The CallbacksHandler is an abstract class that can register and unregister callbacks by key. * Subclasses should implement their own methods about how to invoke the callbacks. @@ -91,97 +86,105 @@ interface ICallbackTable { * * @private */ -export class CallbacksHandler { - protected _callbackTable: ICallbackTable = js.createMap(true); - +function CallbacksHandler () { + this._callbackTable = js.createMap(true); +} +CallbacksHandler.prototype = { + constructor: CallbacksHandler, /** - * @param key - * @param callback - * @param [target] - can be null + * @method add + * @param {String} key + * @param {Function} callback + * @param {Object} [target] - can be null */ - public add (key: string, callback: Function, target: object | null = null) { - let list = this._callbackTable[key]; + add (key, callback, target) { + var list = this._callbackTable[key]; if (!list) { - list = this._callbackTable[key] = callbackListPool.get() as CallbackList; + list = this._callbackTable[key] = callbackListPool.get(); } list.callbacks.push(callback); list.targets.push(target || null); - } + }, /** * Check if the specified key has any registered callback. If a callback is also specified, * it will only return true if the callback is registered. - * @param key - * @param [callback] - * @param [target] + * @method hasEventListener + * @param {String} key + * @param {Function} [callback] + * @param {Object} [target] + * @return {Boolean} */ - public hasEventListener (key: string, callback?: Function, target: Object | null = null) { - const list = this._callbackTable[key]; + hasEventListener (key, callback, target) { + var list = this._callbackTable[key]; if (!list) { return false; } // check any valid callback - const callbacks = list.callbacks; + var callbacks = list.callbacks; if (!callback) { // Make sure no cancelled callbacks if (list.isInvoking) { - for (const cb of callbacks) { - if (cb) { + for (let i = 0; i < callbacks.length; i++) { + if (callbacks[i]) { return true; } } return false; - } else { + } + else { return callbacks.length > 0; } } target = target || null; - const targets = list.targets; + var targets = list.targets; for (let i = 0; i < callbacks.length; ++i) { if (callbacks[i] === callback && targets[i] === target) { return true; } } return false; - } + }, /** * Removes all callbacks registered in a certain event type or all callbacks registered with a certain target - * @param keyOrTarget - The event key to be removed or the target to be removed + * @method removeAll + * @param {String|Object} keyOrTarget - The event key to be removed or the target to be removed */ - public removeAll (keyOrTarget?: string | object) { + removeAll (keyOrTarget) { if (typeof keyOrTarget === 'string') { // remove by key - const list = this._callbackTable[keyOrTarget]; + let list = this._callbackTable[keyOrTarget]; if (list) { if (list.isInvoking) { list.cancelAll(); - } else { + } + else { callbackListPool.put(list); delete this._callbackTable[keyOrTarget]; } } - } else if (keyOrTarget) { + } + else if (keyOrTarget) { // remove by target - for (const key in this._callbackTable) { - if (this._callbackTable.hasOwnProperty(key)) { - const list = this._callbackTable[key]!; - if (list.isInvoking) { - const targets = list.targets; - for (let i = 0; i < targets.length; ++i) { - if (targets[i] === keyOrTarget) { - list.cancel(i); - } + for (let key in this._callbackTable) { + let list = this._callbackTable[key]; + if (list.isInvoking) { + let targets = list.targets; + for (let i = 0; i < targets.length; ++i) { + if (targets[i] === keyOrTarget) { + list.cancel(i); } - } else { - list.removeBy(list.targets, keyOrTarget); } } + else { + list.removeBy(list.targets, keyOrTarget); + } } } - } + }, /** * @method remove @@ -189,17 +192,18 @@ export class CallbacksHandler { * @param {Function} callback * @param {Object} [target] */ - public remove (key, callback, target) { - const list = this._callbackTable[key]; + remove (key, callback, target) { + var list = this._callbackTable[key]; if (list) { target = target || null; - const callbacks = list.callbacks; - const targets = list.targets; - for (let i = 0; i < callbacks.length; ++i) { + var callbacks = list.callbacks; + var targets = list.targets; + for (var i = 0; i < callbacks.length; ++i) { if (callbacks[i] === callback && targets[i] === target) { if (list.isInvoking) { list.cancel(i); - } else { + } + else { fastRemoveAt(callbacks, i); fastRemoveAt(targets, i); } @@ -208,28 +212,45 @@ export class CallbacksHandler { } } } -} +}; /** * !#en The callbacks invoker to handle and invoke callbacks by key. * !#zh CallbacksInvoker 用来根据 Key 管理并调用回调方法。 + * @class CallbacksInvoker + * + * @extends _CallbacksHandler */ -export class CallbacksInvoker extends CallbacksHandler { - public emit (key: string, p1?: any, p2?: any, p3?: any, p4?: any, p5?: any) { - const list = this._callbackTable[key]; +function CallbacksInvoker () { + CallbacksHandler.call(this); +} +js.extend(CallbacksInvoker, CallbacksHandler); +js.mixin(CallbacksInvoker.prototype, { + /** + * @method emit + * @param {String} key + * @param {any} [p1] + * @param {any} [p2] + * @param {any} [p3] + * @param {any} [p4] + * @param {any} [p5] + */ + emit (key, p1, p2, p3, p4, p5) { + var list = this._callbackTable[key]; if (list) { - const rootInvoker = !list.isInvoking; + var rootInvoker = !list.isInvoking; list.isInvoking = true; - const callbacks = list.callbacks; - const targets = list.targets; - for (let i = 0, len = callbacks.length; i < len; ++i) { - const callback = callbacks[i]; + var callbacks = list.callbacks; + var targets = list.targets; + for (var i = 0, len = callbacks.length; i < len; ++i) { + var callback = callbacks[i]; if (callback) { - const target = targets[i]; + var target = targets[i]; if (target) { callback.call(target, p1, p2, p3, p4, p5); - } else { + } + else { callback(p1, p2, p3, p4, p5); } } @@ -243,8 +264,13 @@ export class CallbacksInvoker extends CallbacksHandler { } } } -} +}); if (CC_TEST) { cc._Test.CallbacksInvoker = CallbacksInvoker; } + +export { + CallbacksHandler, + CallbacksInvoker +}; diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.js similarity index 73% rename from cocos/core/event/event-target.ts rename to cocos/core/event/event-target.js index 070f294821..9013108e6a 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.js @@ -25,8 +25,7 @@ ****************************************************************************/ import * as js from '../utils/js'; -import { CallbacksInvoker } from './callbacks-invoker'; -import Event from './event'; +import {CallbacksInvoker} from './callbacks-invoker'; const fastRemove = js.array.fastRemove; @@ -54,17 +53,21 @@ const fastRemove = js.array.fastRemove; * 事件目标是事件触发时,分派的事件对象,Node 是最常见的事件目标, * 但是其他对象也可以是事件目标。
* + * @class EventTarget + * @extends CallbacksInvoker */ -export default class EventTarget extends CallbacksInvoker { +function EventTarget () { + CallbacksInvoker.call(this); +} +js.extend(EventTarget, CallbacksInvoker); +js.mixin(EventTarget.prototype, { /** * !#en Checks whether the EventTarget object has any callback registered for a specific type of event. * !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。 - * @param type - The type of event. - * @return True if a callback of the specified type is registered; false otherwise. + * @method hasEventListener + * @param {String} type - The type of event. + * @return {Boolean} True if a callback of the specified type is registered; false otherwise. */ - public hasEventListener (key: string) { - return super.hasEventListener(key); - } /** * !#en @@ -73,28 +76,38 @@ export default class EventTarget extends CallbacksInvoker { * !#zh * 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。 * - * @param type - A string representing the event type to listen for. - * @param callback - The callback that will be invoked when the event is dispatched. - * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param target - The target (this object) to invoke the callback, can be null - * @return Just returns the incoming callback so you can save the anonymous function easier. + * @method on + * @param {String} type - A string representing the event type to listen for. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {any} [callback.arg1] arg1 + * @param {any} [callback.arg2] arg2 + * @param {any} [callback.arg3] arg3 + * @param {any} [callback.arg4] arg4 + * @param {any} [callback.arg5] arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. + * @typescript + * on(type: string, callback: T, target?: any, useCapture?: boolean): T * @example * eventTarget.on('fire', function () { * cc.log("fire in the hole"); * }, node); */ - public on (type: string, callback: T, target: Object | null = null) { - if (!super.hasEventListener(type, callback, target)) { + on (type, callback, target) { + if (!callback) { + cc.errorID(6800); + return; + } + + if ( !this.hasEventListener(type, callback, target) ) { this.add(type, callback, target); - // @ts-ignore - if (target && target.__eventTargets) { - // @ts-ignore + if (target && target.__eventTargets) target.__eventTargets.push(this); - } } return callback; - } + }, /** * !#en @@ -104,10 +117,9 @@ export default class EventTarget extends CallbacksInvoker { * 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 * * @method off - * @param type - A string representing the event type being removed. - * @param [callback] - The callback to remove. - * @param [target] - The target (this object) to invoke the callback, - * if it's not given, only callback without target will be removed + * @param {String} type - A string representing the event type being removed. + * @param {Function} [callback] - The callback to remove. + * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed * @example * // register fire eventListener * var callback = eventTarget.on('fire', function () { @@ -118,35 +130,33 @@ export default class EventTarget extends CallbacksInvoker { * // remove all fire event listeners * eventTarget.off('fire'); */ - public off (type: string, callback?: Function, target: Object | null = null) { + off (type, callback, target) { if (!callback) { this.removeAll(type); - } else { + } + else { this.remove(type, callback, target); - // @ts-ignore if (target && target.__eventTargets) { - // @ts-ignore fastRemove(target.__eventTargets, this); } } - } + }, /** * !#en Removes all callbacks previously registered with the same target (passed as parameter). * This is not for removing all listeners in the current event target, * and this is not for removing all listeners the target parameter have registered. - * It's only for removing all listeners (callback and target couple) registered - * on the current event target by the target parameter. + * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. * !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 * @method targetOff * @param {Object} target - The target to be searched for all related listeners */ - public targetOff () { + targetOff () { this.removeAll(); - } + }, /** * !#en @@ -170,21 +180,20 @@ export default class EventTarget extends CallbacksInvoker { * cc.log("this is the callback and will be invoked only once"); * }, node); */ - public once (type, callback, target) { - const eventType_hasOnceListener = '__ONCE_FLAG:' + type; - const hasOnceListener = super.hasEventListener(eventType_hasOnceListener, callback, target); + once (type, callback, target) { + var eventType_hasOnceListener = '__ONCE_FLAG:' + type; + var hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { - const self = this; - const onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { + var self = this; + var onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { self.off(type, onceWrapper, target); self.remove(eventType_hasOnceListener, callback, target); - // @ts-ignore callback.call(this, arg1, arg2, arg3, arg4, arg5); }; this.on(type, onceWrapper, target); this.add(eventType_hasOnceListener, callback, target); } - } + }, /** * !#en @@ -192,20 +201,18 @@ export default class EventTarget extends CallbacksInvoker { * !#zh * 通过事件名发送自定义事件 * - * @param type - event type - * @param arg1 - First argument - * @param arg2 - Second argument - * @param arg3 - Third argument - * @param arg4 - Fourth argument - * @param arg5 - Fifth argument + * @method emit + * @param {String} type - event type + * @param {*} [arg1] - First argument + * @param {*} [arg2] - Second argument + * @param {*} [arg3] - Third argument + * @param {*} [arg4] - Fourth argument + * @param {*} [arg5] - Fifth argument * @example * * eventTarget.emit('fire', event); * eventTarget.emit('fire', message, emitter); */ - public emit (key: string, p1?: any, p2?: any, p3?: any, p4?: any, p5?: any) { - return super.emit(key, p1, p2, p3, p4, p5); - } /** * !#en @@ -213,13 +220,13 @@ export default class EventTarget extends CallbacksInvoker { * !#zh * 通过事件对象派发事件 * - * @param event + * @method dispatchEvent + * @param {Event} event */ - public dispatchEvent (event: Event) { - // @ts-ignore + dispatchEvent (event) { this.invoke(event.type, event); } -} +}); -/* tslint:disable:no-string-literal */ -cc['EventTarget'] = EventTarget; +cc.EventTarget = EventTarget; +export default EventTarget; diff --git a/cocos/core/event/event.js b/cocos/core/event/event.js new file mode 100644 index 0000000000..12b5a4053a --- /dev/null +++ b/cocos/core/event/event.js @@ -0,0 +1,269 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * !#en Base class of all kinds of events. + * !#zh 包含事件相关信息的对象。 + * @class Event + */ +class Event { + /** + * @method constructor + * @param {String} type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" + * @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not + */ + constructor (type, bubbles) { + /** + * !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". + * !#zh 事件类型。 + * @property type + * @type {String} + */ + this.type = type; + + /** + * !#en Indicate whether the event bubbles up through the tree or not. + * !#zh 表示该事件是否进行冒泡。 + * @property bubbles + * @type {Boolean} + */ + this.bubbles = !!bubbles; + + /** + * !#en A reference to the target to which the event was originally dispatched. + * !#zh 最初事件触发的目标 + * @property target + * @type {Object} + */ + this.target = null; + + /** + * !#en A reference to the currently registered target for the event. + * !#zh 当前目标 + * @property currentTarget + * @type {Object} + */ + this.currentTarget = null; + + /** + * !#en + * Indicates which phase of the event flow is currently being evaluated. + * Returns an integer value represented by 4 constants: + * - Event.NONE = 0 + * - Event.CAPTURING_PHASE = 1 + * - Event.AT_TARGET = 2 + * - Event.BUBBLING_PHASE = 3 + * The phases are explained in the [section 3.1, Event dispatch and DOM event flow] + * (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. + * !#zh 事件阶段 + * @property eventPhase + * @type {Number} + */ + this.eventPhase = 0; + + /* + * Indicates whether or not event.stopPropagation() has been called on the event. + * @property _propagationStopped + * @type {Boolean} + * @private + */ + this._propagationStopped = false; + + /* + * Indicates whether or not event.stopPropagationImmediate() has been called on the event. + * @property _propagationImmediateStopped + * @type {Boolean} + * @private + */ + this._propagationImmediateStopped = false; + } + + /** + * !#en Reset the event for being stored in the object pool. + * !#zh 重置对象池中存储的事件。 + * @method unuse + * @returns {String} + */ + unuse () { + this.type = cc.Event.NO_TYPE; + this.target = null; + this.currentTarget = null; + this.eventPhase = cc.Event.NONE; + this._propagationStopped = false; + this._propagationImmediateStopped = false; + } + + /** + * !#en Reuse the event for being used again by the object pool. + * !#zh 用于对象池再次使用的事件。 + * @method reuse + * @returns {String} + */ + reuse (type, bubbles) { + this.type = type; + this.bubbles = bubbles || false; + } + + /** + * !#en Stops propagation for current event. + * !#zh 停止传递当前事件。 + * @method stopPropagation + */ + stopPropagation () { + this._propagationStopped = true; + } + + /** + * !#en Stops propagation for current event immediately, + * the event won't even be dispatched to the listeners attached in the current target. + * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 + * @method stopPropagationImmediate + */ + stopPropagationImmediate () { + this._propagationImmediateStopped = true; + } + + /** + * !#en Checks whether the event has been stopped. + * !#zh 检查该事件是否已经停止传递. + * @method isStopped + * @returns {Boolean} + */ + isStopped () { + return this._propagationStopped || this._propagationImmediateStopped; + } + + /** + * !#en + *

+ * Gets current target of the event
+ * note: It only be available when the event listener is associated with node.
+ * It returns 0 when the listener is associated with fixed priority. + *

+ * !#zh 获取当前目标节点 + * @method getCurrentTarget + * @returns {Node} The target with which the event associates. + */ + getCurrentTarget () { + return this.currentTarget; + } + + /** + * !#en Gets the event type. + * !#zh 获取事件类型 + * @method getType + * @returns {String} + */ + getType () { + return this.type; + } +} + +//event type +/** + * !#en Code for event without type. + * !#zh 没有类型的事件 + * @property NO_TYPE + * @static + * @type {string} + */ +Event.NO_TYPE = 'no_type'; + +/** + * !#en The type code of Touch event. + * !#zh 触摸事件类型 + * @property TOUCH + * @static + * @type {String} + */ +Event.TOUCH = 'touch'; +/** + * !#en The type code of Mouse event. + * !#zh 鼠标事件类型 + * @property MOUSE + * @static + * @type {String} + */ +Event.MOUSE = 'mouse'; +/** + * !#en The type code of Keyboard event. + * !#zh 键盘事件类型 + * @property KEYBOARD + * @static + * @type {String} + */ +Event.KEYBOARD = 'keyboard'; +/** + * !#en The type code of Acceleration event. + * !#zh 加速器事件类型 + * @property ACCELERATION + * @static + * @type {String} + */ +Event.ACCELERATION = 'acceleration'; + +//event phase +/** + * !#en Events not currently dispatched are in this phase + * !#zh 尚未派发事件阶段 + * @property NONE + * @type {Number} + * @static + */ +Event.NONE = 0; +/** + * !#en + * The capturing phase comprises the journey from the root to the last node before the event target's node + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 + * @property CAPTURING_PHASE + * @type {Number} + * @static + */ +Event.CAPTURING_PHASE = 1; +/** + * !#en + * The target phase comprises only the event target node + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 目标阶段仅包括事件目标节点。 + * @property AT_TARGET + * @type {Number} + * @static + */ +Event.AT_TARGET = 2; +/** + * !#en + * The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy + * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow + * !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 + * @property BUBBLING_PHASE + * @type {Number} + * @static + */ +Event.BUBBLING_PHASE = 3; + +cc.Event = Event; +export default Event; \ No newline at end of file diff --git a/cocos/core/event/event.ts b/cocos/core/event/event.ts deleted file mode 100644 index 01af21145a..0000000000 --- a/cocos/core/event/event.ts +++ /dev/null @@ -1,222 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - * !#en Base class of all kinds of events. - * !#zh 包含事件相关信息的对象。 - * @class Event - */ -export default class Event { - // Event types - - /** - * !#en Code for event without type. - * !#zh 没有类型的事件 - */ - public static NO_TYPE = 'no_type'; - - /** - * !#en The type code of Touch event. - * !#zh 触摸事件类型 - */ - public static TOUCH = 'touch'; - /** - * !#en The type code of Mouse event. - * !#zh 鼠标事件类型 - */ - public static MOUSE = 'mouse'; - /** - * !#en The type code of Keyboard event. - * !#zh 键盘事件类型 - */ - public static KEYBOARD = 'keyboard'; - /** - * !#en The type code of Acceleration event. - * !#zh 加速器事件类型 - */ - public static ACCELERATION = 'acceleration'; - - // Event phases - - /** - * !#en Events not currently dispatched are in this phase - * !#zh 尚未派发事件阶段 - */ - public static NONE = 0; - - /** - * !#en - * The capturing phase comprises the journey from the root to the last node before the event target's node - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 - */ - public static CAPTURING_PHASE = 1; - - /** - * !#en - * The target phase comprises only the event target node - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 目标阶段仅包括事件目标节点。 - */ - public static AT_TARGET = 2; - - /** - * !#en - * The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy - * see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 - */ - public static BUBBLING_PHASE = 3; - - /** - * !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". - * !#zh 事件类型。 - */ - public type: string; - - /** - * !#en Indicate whether the event bubbles up through the tree or not. - * !#zh 表示该事件是否进行冒泡。 - */ - public bubbles: boolean; - - /** - * !#en A reference to the target to which the event was originally dispatched. - * !#zh 最初事件触发的目标 - */ - public target: Object | null = null; - - /** - * !#en A reference to the currently registered target for the event. - * !#zh 当前目标 - */ - public currentTarget: Object | null = null; - - /** - * !#en - * Indicates which phase of the event flow is currently being evaluated. - * Returns an integer value represented by 4 constants: - * - Event.NONE = 0 - * - Event.CAPTURING_PHASE = 1 - * - Event.AT_TARGET = 2 - * - Event.BUBBLING_PHASE = 3 - * The phases are explained in the [section 3.1, Event dispatch and DOM event flow] - * (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. - * !#zh 事件阶段 - */ - public eventPhase = 0; - - /* - * Indicates whether or not event.stopPropagation() has been called on the event. - */ - private _propagationStopped = false; - - /* - * Indicates whether or not event.stopPropagationImmediate() has been called on the event. - */ - private _propagationImmediateStopped = false; - - /** - * @param type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit" - * @param bubbles - A boolean indicating whether the event bubbles up through the tree or not - */ - constructor (type: string, bubbles?: boolean) { - this.type = type; - this.bubbles = !!bubbles; - } - - /** - * !#en Reset the event for being stored in the object pool. - * !#zh 重置对象池中存储的事件。 - */ - public unuse () { - this.type = Event.NO_TYPE; - this.target = null; - this.currentTarget = null; - this.eventPhase = Event.NONE; - this._propagationStopped = false; - this._propagationImmediateStopped = false; - } - - /** - * !#en Reuse the event for being used again by the object pool. - * !#zh 用于对象池再次使用的事件。 - */ - public reuse (type: string, bubbles?: boolean) { - this.type = type; - this.bubbles = bubbles || false; - } - - /** - * !#en Stops propagation for current event. - * !#zh 停止传递当前事件。 - */ - public stopPropagation () { - this._propagationStopped = true; - } - - /** - * !#en Stops propagation for current event immediately, - * the event won't even be dispatched to the listeners attached in the current target. - * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 - */ - public stopPropagationImmediate () { - this._propagationImmediateStopped = true; - } - - /** - * !#en Checks whether the event has been stopped. - * !#zh 检查该事件是否已经停止传递. - */ - public isStopped () { - return this._propagationStopped || this._propagationImmediateStopped; - } - - /** - * !#en - *

- * Gets current target of the event
- * note: It only be available when the event listener is associated with node.
- * It returns 0 when the listener is associated with fixed priority. - *

- * !#zh 获取当前目标节点 - * @returns The target with which the event associates. - */ - public getCurrentTarget () { - return this.currentTarget; - } - - /** - * !#en Gets the event type. - * !#zh 获取事件类型 - */ - public getType () { - return this.type; - } -} - -/* tslint:disable:no-string-literal */ -cc['Event'] = Event; diff --git a/cocos/core/event/index.ts b/cocos/core/event/index.js similarity index 96% rename from cocos/core/event/index.ts rename to cocos/core/event/index.js index 7a652d3cbb..298fb5ea72 100644 --- a/cocos/core/event/index.ts +++ b/cocos/core/event/index.js @@ -25,4 +25,4 @@ ****************************************************************************/ export { default as Event } from './event'; -export { default as EventTarget } from './event-target'; +export { default as EventTarget } from './event-target'; \ No newline at end of file From a2020308f1935f6f8e16df8aa39c736537ba24fd Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 8 Jan 2019 20:09:07 +0800 Subject: [PATCH 067/267] material interface --- cocos/3d/assets/effect-asset.ts | 42 +++---- cocos/3d/assets/material.ts | 115 ++++++++---------- cocos/3d/builtin/effects.js | 20 ++- cocos/pipeline/forward/forward-flow.ts | 35 +++--- cocos/pipeline/forward/test-material-stage.ts | 43 ++++--- cocos/renderer/core/effect.ts | 62 +++++----- cocos/renderer/core/pass.ts | 98 ++++++++------- cocos/renderer/core/program-lib.ts | 18 +-- tslint.json | 5 +- 9 files changed, 232 insertions(+), 206 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index e0993474ba..b7f50345f8 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -1,14 +1,14 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; -import { PassInfoBase } from '../../renderer/core/pass'; +import { IPassInfoBase } from '../../renderer/core/pass'; -export interface TechniqueInfo { - passes: PassInfoBase[]; +export interface ITechniqueInfo { + passes: IPassInfoBase[]; queue?: number; priority?: number; lod?: number; } -export interface PropertyInfo { +export interface IPropertyInfo { type?: number; value?: number | number[] | null; displayName?: string; @@ -16,39 +16,39 @@ export interface PropertyInfo { pass?: number; } -export interface BlockMember { +export interface IBlockMember { name: string; type: number; count: number; size: number; } -export interface BlockInfo { +export interface IBlockInfo { name: string; binding: number; defines: string[]; - members: BlockMember[]; + members: IBlockMember[]; size: number; } -export interface SamplerInfo { +export interface ISamplerInfo { name: string; binding: number; defines: string[]; type: number; count: number; } -export interface DefineInfo { +export interface IDefineInfo { name: string; type: string; range?: number[]; defines: string[]; } -export interface ShaderInfo { +export interface IShaderInfo { name: string; vert: string; frag: string; - defines: DefineInfo[]; - blocks: BlockInfo[]; - samplers: SamplerInfo[]; + defines: IDefineInfo[]; + blocks: IBlockInfo[]; + samplers: ISamplerInfo[]; dependencies: Record; } @@ -56,8 +56,8 @@ const effects: Record = {}; @ccclass('cc.EffectAsset') export class EffectAsset extends Asset { - public static register(asset: EffectAsset) { effects[asset.name] = asset; } - public static remove(name: string) { + public static register (asset: EffectAsset) { effects[asset.name] = asset; } + public static remove (name: string) { if (effects[name]) { delete effects[name]; return; } for (const n in effects) { if (effects[n]._uuid === name) { @@ -66,7 +66,7 @@ export class EffectAsset extends Asset { } } } - public static get(name: string) { + public static get (name: string) { if (effects[name]) { return effects[name]; } for (const n in effects) { if (effects[n]._uuid === name) { @@ -75,19 +75,19 @@ export class EffectAsset extends Asset { } return null; } - public static getAll() { return effects; } + public static getAll () { return effects; } protected static _effects: Record = {}; @property - public techniques: TechniqueInfo[] = []; + public techniques: ITechniqueInfo[] = []; @property - public properties: Record = {}; + public properties: Record = {}; @property - public shaders: ShaderInfo[] = []; + public shaders: IShaderInfo[] = []; - public onLoaded() { + public onLoaded () { const lib = cc.game._programLib; this.shaders.forEach((s) => lib.define(s)); EffectAsset.register(this); diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 283e6084da..af1138992f 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -23,15 +23,15 @@ THE SOFTWARE. ****************************************************************************/ import { Asset } from '../../assets/asset'; -import TextureBase from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; +import { GFXBindingType } from '../../gfx/define'; import { Effect } from '../../renderer/core/effect'; import { Pass } from '../../renderer/core/pass'; import { EffectAsset } from './effect-asset'; @ccclass('cc.Material') export class Material extends Asset { - public static getInstantiatedMaterial(mat: Material, rndCom: any) { + public static getInstantiatedMaterial (mat: Material, rndCom: any) { if (mat._owner === rndCom) { return mat; } else { @@ -51,110 +51,94 @@ export class Material extends Asset { protected _defines: Record = {}; @property protected _props: Array> = []; - @property - protected _textures: Array> = []; protected _passes: Pass[] = []; protected _owner: any = null; @property - set effectAsset(val: EffectAsset | null) { + set effectAsset (val: EffectAsset | null) { if (!val || this.effectName !== val.name) { this.update(val, false); } } - get effectAsset() { + get effectAsset () { return this._effectAsset; } // helper setter @property - set effectName(val) { + set effectName (val) { if (this.effectName !== val) { this.update(val, false); } } - get effectName() { + get effectName () { return this._effectAsset ? this._effectAsset.name : ''; } @property - set technique(val: number) { + set technique (val: number) { this._techIdx = val; } - get technique() { + get technique () { return this._techIdx; } - get passes() { + get passes () { return this._passes; } - public setDefines(defines: Record) { + public setDefines (defines: Record) { this._defines = defines; this.update(); } - public setProperty(name: string, val: any, passIdx?: number) { + /** + * Convenient setter provided for quick material setup. + * pass.setUniform should be used instead + * if you need to do per-frame property update. + */ + public setProperty (name: string, val: any, passIdx?: number) { + if (!val) { console.warn(`illegal property value: ${val}.`); return; } if (passIdx === undefined) { // set property for all applicable passes const passes = this._passes; const len = passes.length; for (let i = 0; i < len; i++) { - const handle = passes[i].getHandleFromName(name); - if (handle === undefined) { continue; } - passes[i].setUniform(handle, val); - this._props[i][name] = val; + const pass = passes[i]; + if (this._uploadProperty(pass, name, val)) { + this._props[i][name] = val; + } } } else { - if (CC_DEBUG && passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } + if (passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } const pass = this._passes[passIdx]; - const handle = pass.getHandleFromName(name); - if (CC_DEBUG && handle === undefined) { console.warn(`illegal property name: ${name}.`); return; } - pass.setUniform(handle, val); - this._props[passIdx][name] = val; + if (this._uploadProperty(pass, name, val)) { + this._props[passIdx][name] = val; + } else { + console.warn(`illegal property name: ${name}.`); return; + } } } - public setTexture(name: string, val: TextureBase, passIdx?: number) { - if (passIdx === undefined) { // set property for all applicable passes - const passes = this._passes; - const len = passes.length; - for (let i = 0; i < len; i++) { - const binding = passes[i].getBindingFromName(name); - if (binding < 0) { continue; } - passes[i].bindTextureView(binding, val._texView); - this._textures[i][name] = val; - } - } else { - if (CC_DEBUG && passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } - const pass = this._passes[passIdx]; - const binding = pass.getBindingFromName(name); - if (CC_DEBUG && binding < 0) { console.warn(`illegal texture name: ${name}.`); return; } - pass.bindTextureView(binding, val._texView); - this._textures[passIdx][name] = val; - } - } - - public copy(mat: Material) { - this._props.length = this._textures.length = mat._props.length; + public copy (mat: Material) { + this._props.length = mat._props.length; for (let i = 0; i < mat._props.length; i++) { Object.assign(this._props[i], mat._props[i]); - Object.assign(this._textures[i], mat._textures[i]); } Object.assign(this._defines, mat._defines); this.update(mat.effectAsset); this._uuid = mat._uuid; } - public onLoaded() { + public onLoaded () { this.update(); } - public update(val: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { + public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { // get effect asset - if (typeof val === 'string') { - this._effectAsset = EffectAsset.get(val); + if (typeof asset === 'string') { + this._effectAsset = EffectAsset.get(asset); if (!this._effectAsset) { - console.warn(`no effect named '${val}' found`); + console.warn(`no effect named '${asset}' found`); return; } } else { - this._effectAsset = val; + this._effectAsset = asset; } if (!this._effectAsset) { return; } // create passes @@ -163,28 +147,35 @@ export class Material extends Asset { defines: this._defines, }); // handle property values - this._props.length = this._textures.length = this._passes.length; + this._props.length = this._passes.length; if (keepProps) { this._passes.forEach((pass, i) => { let props = this._props[i]; if (!props) { props = this._props[i] = {}; } for (const p of Object.keys(props)) { - const handle = pass.getHandleFromName(p); - if (handle === undefined) { continue; } - pass.setUniform(handle, props[p]); - } - let textures = this._textures[i]; - if (!textures) { textures = this._textures[i] = {}; } - for (const t of Object.keys(textures)) { - const binding = pass.getBindingFromName(t); - if (binding === undefined) { continue; } - pass.bindTextureView(binding, textures[t]._texView); + const val = props[p]; + if (!val) { continue; } + this._uploadProperty(pass, p, props[p]); } }); } else { this._props.fill({}); } } + + protected _uploadProperty (pass: Pass, name: string, val: any) { + const handle = pass.getHandle(name); + if (handle === undefined) { return false; } + const bindingType = Pass.getBindingTypeFromHandle(handle); + if (bindingType === GFXBindingType.UNIFORM_BUFFER) { + pass.setUniform(handle, val); + } else if (bindingType === GFXBindingType.SAMPLER) { + const tv = val.getGFXTextureView(); + if (!tv) { console.warn('texture asset incomplete!'); return; } + pass.bindTextureView(Pass.getBindingFromHandle(handle), tv); + } + return true; + } } cc.Material = Material; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 0feefdfbec..1a372d2949 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -6,8 +6,24 @@ export default [ "shaders": [ { "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", - "vert": "\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n varying vec2 v_texCoord;\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n", - "frag": "\n varying vec2 v_texCoord;\n uniform vec4 u_color;\n uniform sampler2D u_sampler;\n void main() {\n \n gl_FragColor = texture2D(u_sampler, v_texCoord);\n gl_FragColor.r = u_color.r;\n }\n", + "vert": ` +attribute vec2 a_position; +attribute vec2 a_texCoord; +varying vec2 v_texCoord; +void main() { + gl_Position = vec4(a_position, 0.0, 1.0); + v_texCoord = a_texCoord; +} + `, + "frag": ` +varying vec2 v_texCoord; +uniform vec4 u_color; +uniform sampler2D u_sampler; +void main() { + gl_FragColor = texture2D(u_sampler, v_texCoord); + gl_FragColor.r = u_color.r; +} + `, "defines": [], "blocks": [ {"name": "Constants", "size": 16, "defines": [], "binding": 0, "members": [ diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index d028bc9eef..860acf41b4 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,20 +1,19 @@ -import { RenderFlow, RenderFlowInfo } from "../render-flow"; -import { RenderPipeline } from "../render-pipeline"; -// import { TestStage } from "./test-stage"; -import { TestMaterialStage } from "./test-material-stage"; -import { TestStage } from "./test-stage"; +import { RenderFlow, RenderFlowInfo } from '../render-flow'; +import { RenderPipeline } from '../render-pipeline'; +import { TestMaterialStage } from './test-material-stage'; +import { TestStage } from './test-stage'; export enum ForwardStagePriority { FORWARD = 0, -}; +} export class ForwardFlow extends RenderFlow { - constructor(pipeline: RenderPipeline) { + constructor (pipeline: RenderPipeline) { super(pipeline); } - public initialize(info: RenderFlowInfo): boolean { + public initialize (info: RenderFlowInfo): boolean { if (info.name !== undefined) { this._name = info.name; @@ -22,37 +21,39 @@ export class ForwardFlow extends RenderFlow { this._priority = info.priority; - let mainWindow = this._pipeline.root.mainWindow; + const mainWindow = this._pipeline.root.mainWindow; if (!mainWindow || !mainWindow.framebuffer) { return false; } - /* + /* * this.createStage(ForwardStage, { name: "ForwardStage", priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - */ + /* */ - /* + /* */ this.createStage(TestMaterialStage, { - name: "TestMaterialStage", + name: 'TestMaterialStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - */ + /* */ + /* * this.createStage(TestStage, { - name: "TestStage", + name: 'TestStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); + /* */ return true; } - public destroy(): void { + public destroy (): void { this.destroyStages(); } -}; +} diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index d84722e3aa..56f99511df 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -16,11 +16,11 @@ export class TestMaterialStage extends RenderStage { private _texView: GFXTextureView | null = null; private _material: Material = new Material(); - constructor(flow: RenderFlow) { + constructor (flow: RenderFlow) { super(flow); } - public initialize(info: RenderStageInfo): boolean { + public initialize (info: RenderStageInfo): boolean { if (info.name !== undefined) { this._name = info.name; @@ -40,7 +40,7 @@ export class TestMaterialStage extends RenderStage { // load texture const imgElms = this._device.canvas.getElementsByTagName('img'); if (imgElms.length) { - if (!this.loadTexture(imgElms[0])) { + if (!this.loadTexture(imgElms[0] as HTMLImageElement)) { console.error('Load texture failed.'); return false; } @@ -51,7 +51,7 @@ export class TestMaterialStage extends RenderStage { return true; } - public destroy() { + public destroy () { if (this._texView) { this._texView.destroy(); @@ -69,41 +69,50 @@ export class TestMaterialStage extends RenderStage { } } - public render(view: RenderView) { + public render (view: RenderView) { + const mtl = this._material; // @ts-ignore - if (!this._material.inited) { + if (!mtl.inited) { // material - this._material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js - const pass = this._material.passes[0]; - const texBinding = pass.getBindingFromName('u_sampler'); - pass.bindTextureView(texBinding, this._texView); - const colorHandle = pass.getHandleFromName('u_color'); + mtl.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js + const pass = mtl.passes[0]; + /* * + const texBinding = pass.getBinding('u_sampler'); + pass.bindTextureView(texBinding, this._texView as GFXTextureView); + const colorHandle = pass.getHandle('u_color'); pass.setUniform(colorHandle, cc.color('#ffffff')); + /* */ + mtl.setProperty('u_sampler', { + tv: this._texView, + getGFXTextureView () { return this.tv; }, + }); + mtl.setProperty('u_color', cc.color('#ffffff')); + /* */ pass.update(); // @ts-ignore - this._material.inited = true; + mtl.inited = true; } - const cmdBuff = this._cmdBuff; + const cmdBuff = this._cmdBuff as GFXCommandBuffer; this._renderArea.width = view.width; this._renderArea.height = view.height; cmdBuff.begin(); - cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, + 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); - cmdBuff.draw(this._pipeline.quadIA); + 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 { + private loadTexture (image: HTMLImageElement): boolean { this._texture = this._device.createTexture({ type: GFXTextureType.TEX2D, usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 30dc97bd35..724032e052 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -1,13 +1,13 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { BlockMember, EffectAsset, PropertyInfo, SamplerInfo, ShaderInfo } from '../../3d/assets/effect-asset'; +import { EffectAsset, IBlockMember, IPropertyInfo, ISamplerInfo, IShaderInfo } from '../../3d/assets/effect-asset'; import { CCObject } from '../../core/data'; import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; import { GFXType } from '../../gfx/define'; import { RenderPassStage } from '../../pipeline/render-pipeline'; import Texture2D from '../gfx/texture-2d'; import TextureCube from '../gfx/texture-cube'; -import { Pass, PassInfo } from './pass'; +import { IPassInfo, Pass } from './pass'; const _typeMap = { [GFXType.INT]: 'Number', @@ -22,23 +22,23 @@ const _typeMap = { [GFXType.MAT4]: Mat4, [GFXType.SAMPLER2D]: Texture2D, [GFXType.SAMPLER_CUBE]: TextureCube, - number: 'Number', boolean: 'Boolean', default: CCObject, + number: 'Number', }; const getInstanceType = (t: number | string) => _typeMap[t] || _typeMap.default; -export interface PropertyMap { [name: string]: { type: number, value: any }; } -export interface DefineMap { [name: string]: number | boolean; } -export interface EffectInfo { +export interface IPropertyMap { [name: string]: { type: number, value: any }; } +export interface IDefineMap { [name: string]: number | boolean; } +export interface IEffectInfo { techIdx?: number; - defines?: DefineMap; + defines?: IDefineMap; } type DefaultValue = number | boolean | number[] | null; const _ctorMap = { - Number: (v?: DefaultValue) => v || 0, Boolean: (v?: DefaultValue) => v || false, + Number: (v?: DefaultValue) => v || 0, [Vec2]: (v?: DefaultValue) => Array.isArray(v) ? new Vec2(v[0], v[1]) : new Vec2(), [Vec3]: (v?: DefaultValue) => Array.isArray(v) ? new Vec3(v[0], v[1], v[2]) : new Vec3(), [Vec4]: (v?: DefaultValue) => Array.isArray(v) ? new Vec4(v[0], v[1], v[2], v[3]) : new Vec4(), @@ -48,7 +48,7 @@ const _ctorMap = { v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], - v[12], v[13], v[14], v[15] + v[12], v[13], v[14], v[15], ) : new Mat4(), [Texture2D]: () => null, [TextureCube]: () => null, @@ -57,7 +57,7 @@ const _ctorMap = { const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; const getInvolvedPrograms = (effect: EffectAsset, techIdx?: number) => { - const programs: Record = {}; + const programs: Record = {}; const lib = cc.game._programLib; if (techIdx) { effect.techniques[techIdx].passes.forEach((pass) => { @@ -73,7 +73,7 @@ const getInvolvedPrograms = (effect: EffectAsset, techIdx?: number) => { return programs; }; -interface ExtractedPropInfo { +interface IExtractedPropInfo { type: number; instanceType: object | string; value: number | boolean | object; @@ -83,26 +83,26 @@ interface ExtractedPropInfo { pass: number; } const parseProperties = (() => { - interface UniformInfo { type: number; defines: string[]; } - function genPropInfo(propInfo: PropertyInfo, uniformInfo: UniformInfo, tech: number, pass: number) - : ExtractedPropInfo { + interface IUniformInfo { type: number; defines: string[]; } + function genPropInfo (propInfo: IPropertyInfo, uniformInfo: IUniformInfo, tech: number, pass: number) + : IExtractedPropInfo { const type = propInfo.type || uniformInfo.type; return { - type, tech, pass, - instanceType: getInstanceType(type), - value: getInstanceCtor(type)(propInfo.value), - displayName: propInfo.displayName, defines: uniformInfo.defines, + displayName: propInfo.displayName, + instanceType: getInstanceType(type), + pass, tech, type, + value: getInstanceCtor(type)(propInfo.value), }; } - function findUniformInfo(program: ShaderInfo, name: string) { + function findUniformInfo (program: IShaderInfo, name: string) { for (const b of program.blocks) { const i = b.members.find((u) => u.name === name); if (i) { return Object.assign({ defines: b.defines }, i); } } return program.samplers.find((u) => u.name === name); } - function findPassIdx(effect: EffectAsset, programName: string) { // just a heuristic + function findPassIdx (effect: EffectAsset, programName: string) { // just a heuristic effect.techniques.forEach((tech, i) => { tech.passes.forEach((pass, j) => { if (pass.program === programName) { @@ -112,11 +112,11 @@ const parseProperties = (() => { }); return [ 0, 0 ]; } - return (effect: EffectAsset, programs: Record) => { - const props: Record = {}; + return (effect: EffectAsset, programs: Record) => { + const props: Record = {}; for (const prop of Object.keys(effect.properties)) { const propInfo = effect.properties[prop]; - let uniformInfo: UniformInfo | undefined; + let uniformInfo: IUniformInfo | undefined; let techIdx = 0; let passIdx = 0; // always try getting the type from shaders first @@ -141,26 +141,26 @@ const parseProperties = (() => { }; })(); -const traverseUniforms = (shaderInfo: ShaderInfo, fn: (u: BlockMember | SamplerInfo) => any) => { +const traverseUniforms = (shaderInfo: IShaderInfo, fn: (u: IBlockMember | ISamplerInfo) => any) => { shaderInfo.blocks.forEach((b) => b.members.forEach(fn)); shaderInfo.samplers.forEach(fn); }; export class Effect { - public static parseEffect(effect: EffectAsset, info?: EffectInfo) { + public static parseEffect (effect: EffectAsset, info?: IEffectInfo) { // techniques - const { techIdx, defines } = info || {}; + const { techIdx, defines } = info || {} as IEffectInfo; const programs = getInvolvedPrograms(effect, techIdx || 0); const tech = effect.techniques[techIdx || 0]; const passNum = tech.passes.length; const passes: Pass[] = new Array(passNum); const props = parseProperties(effect, programs); for (let k = 0; k < passNum; ++k) { - const passInfo = tech.passes[k]; - const uniforms: PropertyMap = passInfo.uniforms = {}; + const passInfo = tech.passes[k] as IPassInfo; + const uniforms: IPropertyMap = passInfo.uniforms = {}; traverseUniforms(programs[passInfo.program], (u) => { const prop = props[u.name]; - uniforms[u.name] = { + uniforms[u.name] = { // property overloads are shared among passes here type: prop ? prop.type : u.type, value: prop ? prop.value : getInstanceCtor(u.type)(), }; @@ -175,16 +175,16 @@ export class Effect { } return passes; } - public static parseForInspector(effect: EffectAsset) { + public static parseForInspector (effect: EffectAsset) { const programs = getInvolvedPrograms(effect); const props = parseProperties(effect, programs); const defines: Record = {}; for (const pn of Object.keys(programs)) { programs[pn].defines.forEach((define) => { defines[define.name] = { + defines: define.defines, instanceType: getInstanceType(define.type), value: getInstanceCtor(define.type)(), - defines: define.defines, }; }); } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 7e3920337f..b0216bc470 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { BlockInfo, SamplerInfo } from '../../3d/assets/effect-asset'; +import { IBlockInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; @@ -14,9 +14,9 @@ import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; import { RenderPassStage } from '../../pipeline/render-pipeline'; -import { PropertyMap } from './effect'; +import { IPropertyMap } from './effect'; -export interface PassInfoBase { +export interface IPassInfoBase { program: string; // effect-writer part primitive?: GFXPrimitiveMode; @@ -25,13 +25,13 @@ export interface PassInfoBase { depthStencilState?: GFXDepthStencilState; blendState?: GFXBlendState; } -export interface PassInfo extends PassInfoBase { +export interface IPassInfo extends IPassInfoBase { // generated part - blocks: BlockInfo[]; - samplers: SamplerInfo[]; + blocks: IBlockInfo[]; + samplers: ISamplerInfo[]; shader: GFXShader; renderPass: GFXRenderPass; - uniforms: PropertyMap; + uniforms: IPropertyMap; } const _type2fn = { @@ -49,18 +49,28 @@ const _type2fn = { [GFXType.MAT4]: (a: Float32Array, v: any) => mat4.array(a, v), }; -const bindingMask = 0x0fff0000; -const indexMask = 0x0000ffff; -const genHandle = (binding: number, index: number = 0) => (binding << 16) | index; -const parseHandle = (handle: number) => [(handle & bindingMask) >> 16, handle & indexMask]; +const btMask = 0xf0000000; // 4 bits, 16 slots +const typeMask = 0x0fc00000; // 6 bits, 64 slots +const bindingMask = 0x003ff800; // 11 bits, 2048 slots +const indexMask = 0x000007ff; // 11 bits, 2048 slots +const genHandle = (bt: GFXBindingType, type: GFXType, binding: number, index: number = 0) => + ((bt << 28) & btMask) | ((type << 22) & typeMask) | ((binding << 11) & bindingMask) | (index & indexMask); +const getBindingTypeFromHandle = (handle: number) => (handle & btMask) >>> 28; +const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22; +const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 11; +const getIndexFromHandle = (handle: number) => (handle & indexMask); -interface Block { +interface IBlock { buffer: ArrayBuffer; views: Float32Array[]; dirty: boolean; } 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; @@ -72,26 +82,25 @@ export class Pass { protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; protected _stage: RenderPassStage = RenderPassStage.DEFAULT; protected _handleMap: Record = {}; - protected _typeMap: Record = {}; - protected _blocks: Block[] = []; + protected _blocks: IBlock[] = []; protected _layoutDirty: boolean = false; // external references protected _device: GFXDevice; protected _shader: GFXShader | null = null; protected _renderPass: GFXRenderPass | null = null; - public constructor(device: GFXDevice) { + public constructor (device: GFXDevice) { this._device = device; } - public initialize(info: PassInfo) { + public initialize (info: IPassInfo) { this._programName = info.program; // pipeline state const device = this._device; const bindings = info.blocks.map((u) => - ({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER }) + ({ name: u.name, binding: u.binding, type: GFXBindingType.UNIFORM_BUFFER }), ).concat(info.samplers.map((u) => - ({ name: u.name, binding: u.binding, type: GFXBindingType.SAMPLER }) + ({ name: u.name, binding: u.binding, type: GFXBindingType.SAMPLER }), )); this._bindingLayout = device.createBindingLayout({ bindings }); if (!this._bindingLayout) { console.error('create binding layout failed'); return; } @@ -104,10 +113,10 @@ export class Pass { for (const u of info.blocks) { // create gfx buffer resource const buffer = device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: u.size, stride: 1, // N/A for blocks + usage: GFXBufferUsageBit.UNIFORM, }); if (buffer) { this._bindingLayout.bindBuffer(u.binding, buffer); @@ -117,19 +126,18 @@ export class Pass { return; } // buffer data processing system - const block: Block = this._blocks[u.binding] = { + const block: IBlock = this._blocks[u.binding] = { buffer: new ArrayBuffer(u.size), - views: [], dirty: false, + views: [], }; u.members.reduce((acc, cur, idx) => { // create property-specific buffer views const view = new Float32Array(block.buffer, acc, cur.size / Float32Array.BYTES_PER_ELEMENT); block.views.push(view); // store handle map, type and initial value - const handle = this._handleMap[cur.name] = genHandle(u.binding, idx); const inf = info.uniforms[cur.name]; - this._typeMap[handle] = inf.type; + this._handleMap[cur.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, inf.type, u.binding, idx); _type2fn[inf.type](view, inf.value); // proceed the counter return acc + cur.size; @@ -137,7 +145,7 @@ export class Pass { buffer.update(block.buffer); } for (const u of info.samplers) { - this._handleMap[u.name] = genHandle(u.binding); + this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); const sampler = device.createSampler({ name: u.name, // TODO: specify filter modes in effect @@ -152,25 +160,24 @@ export class Pass { this._bindingLayout.update(); } - public getHandleFromName(name: string) { + public getHandle (name: string) { return this._handleMap[name]; } - public getBindingFromName(name: string) { - const handle = this.getHandleFromName(name); - if (handle === undefined) { return -1; } - return parseHandle(handle)[0]; + public getBinding (name: string) { + return Pass.getBindingFromHandle(this.getHandle(name)); } - public setUniform(handle: number, value: any) { - const [ binding, idx ] = parseHandle(handle); + public setUniform (handle: number, value: any) { + const binding = Pass.getBindingFromHandle(handle); + const type = Pass.getTypeFromHandle(handle); + const idx = Pass.getIndexFromHandle(handle); const block = this._blocks[binding]; - const type = this._typeMap[handle]; _type2fn[type](block.views[idx], value); block.dirty = true; } - public bindTextureView(binding: number, value: GFXTextureView) { + public bindTextureView (binding: number, value: GFXTextureView) { const bl = this._bindingLayout; if (bl && bl.getBindingUnit(binding).texView !== value) { bl.bindTextureView(binding, value); @@ -178,7 +185,7 @@ export class Pass { } } - public bindSampler(binding: number, value: GFXSampler) { + public bindSampler (binding: number, value: GFXSampler) { const bl = this._bindingLayout; if (bl && bl.getBindingUnit(binding).sampler !== value) { bl.bindSampler(binding, value); @@ -186,12 +193,12 @@ export class Pass { } } - public setStates(info: PassInfoBase) { + public setStates (info: IPassInfoBase) { if (this._pipelineState) { this._pipelineState.destroy(); } this.createPipelineState(info); } - public destroy() { + 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; } @@ -199,7 +206,7 @@ export class Pass { if (this._pipelineState) { this._pipelineState.destroy(); this._pipelineState = null; } } - public update() { + public update () { const len = this._blocks.length; for (let i = 0; i < len; i++) { const block = this._blocks[i]; @@ -214,7 +221,7 @@ export class Pass { } } - protected createPipelineState(info: PassInfoBase) { + protected createPipelineState (info: IPassInfoBase) { if (info.primitive) { this._primitive = info.primitive; } if (info.stage) { this._stage = info.stage; } @@ -233,13 +240,14 @@ export class Pass { Object.assign(bs, bsInfo); } const stateInfo = { - primitive: info.primitive || this._primitive, - rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), + bs, dss: Object.assign(new GFXDepthStencilState(), info.depthStencilState), - is: new GFXInputState(), bs, - shader: this._shader, + is: new GFXInputState(), layout: this._pipelineLayout, + primitive: info.primitive || this._primitive, renderPass: this._renderPass, + rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), + shader: this._shader, }; if (this._pipelineState) { this._pipelineState.initialize(stateInfo); @@ -248,7 +256,7 @@ export class Pass { } } - get programName() { return this._programName; } - get pipelineState() { return this._pipelineState; } - get bindingLayout() { return this._bindingLayout; } + get programName () { return this._programName; } + get pipelineState () { return this._pipelineState as GFXPipelineState; } + get bindingLayout () { return this._bindingLayout as GFXBindingLayout; } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index f8641466c7..15fb5cff82 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -1,15 +1,15 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { DefineInfo, ShaderInfo } from '../../3d/assets/effect-asset'; +import { IDefineInfo, IShaderInfo } from '../../3d/assets/effect-asset'; import { GFXShaderType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXShader } from '../../gfx/shader'; -import { DefineMap } from './effect'; +import { IDefineMap } from './effect'; function _generateDefines( device: GFXDevice, - defs: DefineMap, - tDefs: DefineInfo[], + defs: IDefineMap, + tDefs: IDefineInfo[], deps: Record ) { const defines: string[] = []; @@ -27,11 +27,11 @@ function _generateDefines( } let _shdID = 0; -interface DefineRecord extends DefineInfo { +interface DefineRecord extends IDefineInfo { _map: (value: any) => number; _offset: number; } -interface ProgramInfo extends ShaderInfo { +interface ProgramInfo extends IShaderInfo { id: number; defines: DefineRecord[]; } @@ -64,7 +64,7 @@ export class ProgramLib { * }; * programLib.define(program); */ - public define(prog: ShaderInfo) { + public define(prog: IShaderInfo) { if (this._templates[prog.name]) { return; } const tmpl = Object.assign({ id: ++_shdID }, prog); tmpl.vert = this._precision + prog.vert; @@ -99,7 +99,7 @@ export class ProgramLib { return this._templates[name] !== undefined; } - public getKey(name: string, defines: DefineMap) { + public getKey(name: string, defines: IDefineMap) { const tmpl = this._templates[name]; let key = 0; for (const tmplDef of tmpl.defines) { @@ -112,7 +112,7 @@ export class ProgramLib { return key << 8 | (tmpl.id & 0xff); } - public getGFXShader(name: string, defines: DefineMap = {}) { + public getGFXShader(name: string, defines: IDefineMap = {}) { const key = this.getKey(name, defines); let program = this._cache[key]; if (program !== undefined) { diff --git a/tslint.json b/tslint.json index 3304af09b8..c301dca5b8 100644 --- a/tslint.json +++ b/tslint.json @@ -11,7 +11,8 @@ "max-classes-per-file": false, "variable-name": false, "object-literal-sort-keys": false, - "ban-types": false + "ban-types": false, + "no-bitwise": false }, "rulesDirectory": [] -} \ No newline at end of file +} From 2ba51db195ce407634d73134b713b80f0fcb10f3 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 9 Jan 2019 14:10:00 +0800 Subject: [PATCH 068/267] add ubo common header --- cocos/3d/geom-utils/frustum.js | 119 --------- cocos/3d/geom-utils/frustum.ts | 124 ++++++++++ cocos/3d/geom-utils/index.js | 2 +- cocos/core/vmath/mat4.ts | 19 +- cocos/pipeline/forward/forward-pipeline.ts | 1 + cocos/pipeline/forward/forward-stage.ts | 14 +- cocos/pipeline/forward/test-stage.ts | 16 +- cocos/pipeline/render-pipeline.ts | 266 +++++++++++++-------- cocos/pipeline/render-queue.ts | 33 +-- cocos/pipeline/render-view.ts | 17 +- cocos/renderer/scene/camera.ts | 48 ++-- cocos/renderer/scene/model.ts | 10 +- tslint.json | 3 +- 13 files changed, 397 insertions(+), 275 deletions(-) delete mode 100644 cocos/3d/geom-utils/frustum.js create mode 100644 cocos/3d/geom-utils/frustum.ts diff --git a/cocos/3d/geom-utils/frustum.js b/cocos/3d/geom-utils/frustum.js deleted file mode 100644 index d75fa293fa..0000000000 --- a/cocos/3d/geom-utils/frustum.js +++ /dev/null @@ -1,119 +0,0 @@ -import enums from './enums'; -import plane from './plane'; -import { vec3 } from '../../core/vmath'; - -let _v = new Array(8); -_v[0] = vec3.create( 1, 1, 1); -_v[1] = vec3.create(-1, 1, 1); -_v[2] = vec3.create(-1, -1, 1); -_v[3] = vec3.create( 1, -1, 1); -_v[4] = vec3.create( 1, 1, -1); -_v[5] = vec3.create(-1, 1, -1); -_v[6] = vec3.create(-1, -1, -1); -_v[7] = vec3.create( 1, -1, -1); - -export default class frustum { - constructor() { - this._type = enums.SHAPE_FRUSTUM; - this.planes = new Array(6); - for (let i = 0; i < 6; ++i) { - this.planes[i] = plane.create(); - } - this.vertices = new Array(8); - for (let i = 0; i < 8; ++i) { - this.vertices[i] = vec3.create(); - } - } - - /** - * create a new frustum - * - * @return {frustum} - */ - static create() { - return new frustum(); - } - - /** - * Clone a frustum - * - * @param {frustum} f frustum to clone - * @return {frustum} the new frustum - */ - static clone(f) { - return frustum.copy(new frustum(), f); - } - - /** - * Copy the values from one frustum to another - * - * @param {frustum} out the receiving frustum - * @param {frustum} f the source frustum - * @return {frustum} - */ - static copy(out, f) { - out._type = f._type; - for (let i = 0; i < 6; ++i) { - plane.copy(out.planes[i], f.planes[i]); - } - for (let i = 0; i < 8; ++i) { - vec3.copy(out.vertices[i], f.vertices[i]); - } - return out; - } - - /** - * Set whether to use accurate intersection testing function on this frustum - * - * @param {boolean} b - */ - set accurate(b) { - this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; - } - - /** - * Update the frustum information according to the given transform matrix. - * Note that the resulting planes are not normalized under normal mode. - * - * @param {mat4} m the view-projection matrix - * @param {mat4} inv the inverse view-projection matrix - */ - update(m, inv) { - // RTR4, ch. 22.14.1, p. 983 - // extract frustum planes from view-proj matrix. - - // left plane - vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08); - this.planes[0].d = -(m.m15 + m.m12); - // right plane - vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08); - this.planes[1].d = -(m.m15 - m.m12); - // bottom plane - vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09); - this.planes[2].d = -(m.m15 + m.m13); - // top plane - vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09); - this.planes[3].d = -(m.m15 - m.m13); - // near plane - vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10); - this.planes[4].d = -(m.m15 + m.m14); - // far plane - vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10); - this.planes[5].d = -(m.m15 - m.m14); - - if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) return; - - // normalize planes - for (let i = 0; i < 6; i++) { - let plane = this.planes[i]; - let invDist = 1 / vec3.magnitude(plane.n); - vec3.scale(plane.n, plane.n, invDist); - plane.d *= invDist; - } - - // update frustum vertices - for (let i = 0; i < 8; i++) { - vec3.transformMat4(this.vertices[i], _v[i], inv); - } - } -} diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/3d/geom-utils/frustum.ts new file mode 100644 index 0000000000..9f7caa9f8a --- /dev/null +++ b/cocos/3d/geom-utils/frustum.ts @@ -0,0 +1,124 @@ +import enums from './enums'; +import plane from './plane'; +import { vec3, mat4 } from '../../core/vmath'; + +let _v = new Array(8); +_v[0] = vec3.create(1, 1, 1); +_v[1] = vec3.create(-1, 1, 1); +_v[2] = vec3.create(-1, -1, 1); +_v[3] = vec3.create(1, -1, 1); +_v[4] = vec3.create(1, 1, -1); +_v[5] = vec3.create(-1, 1, -1); +_v[6] = vec3.create(-1, -1, -1); +_v[7] = vec3.create(1, -1, -1); + +export class frustum { + + public planes: plane[]; + public vertices: vec3[]; + private _type: number; + + constructor() { + this._type = enums.SHAPE_FRUSTUM; + this.planes = new Array(6); + for (let i = 0; i < 6; ++i) { + this.planes[i] = plane.create(); + } + this.vertices = new Array(8); + for (let i = 0; i < 8; ++i) { + this.vertices[i] = vec3.create(); + } + } + + /** + * create a new frustum + * + * @return {frustum} + */ + static create() { + return new frustum(); + } + + /** + * Clone a frustum + * + * @param {frustum} f frustum to clone + * @return {frustum} the new frustum + */ + static clone(f: frustum) { + return frustum.copy(new frustum(), f); + } + + /** + * Copy the values from one frustum to another + * + * @param {frustum} out the receiving frustum + * @param {frustum} f the source frustum + * @return {frustum} + */ + static copy(out, f) { + out._type = f._type; + for (let i = 0; i < 6; ++i) { + plane.copy(out.planes[i], f.planes[i]); + } + for (let i = 0; i < 8; ++i) { + vec3.copy(out.vertices[i], f.vertices[i]); + } + return out; + } + + /** + * Set whether to use accurate intersection testing function on this frustum + * + * @param {boolean} b + */ + set accurate(b) { + this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; + } + + /** + * Update the frustum information according to the given transform matrix. + * Note that the resulting planes are not normalized under normal mode. + * + * @param {mat4} m the view-projection matrix + * @param {mat4} inv the inverse view-projection matrix + */ + update(m: mat4, inv: mat4) { + // RTR4, ch. 22.14.1, p. 983 + // extract frustum planes from view-proj matrix. + + // left plane + vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08); + this.planes[0].d = -(m.m15 + m.m12); + // right plane + vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08); + this.planes[1].d = -(m.m15 - m.m12); + // bottom plane + vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09); + this.planes[2].d = -(m.m15 + m.m13); + // top plane + vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09); + this.planes[3].d = -(m.m15 - m.m13); + // near plane + vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10); + this.planes[4].d = -(m.m15 + m.m14); + // far plane + vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10); + this.planes[5].d = -(m.m15 - m.m14); + + if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) return; + + // normalize planes + for (let i = 0; i < 6; i++) { + let plane = this.planes[i]; + let invDist = 1 / vec3.magnitude(plane.n); + vec3.scale(plane.n, plane.n, invDist); + plane.d *= invDist; + } + + // update frustum vertices + for (let i = 0; i < 8; i++) { + vec3.transformMat4(this.vertices[i], _v[i], inv); + } + } +} diff --git a/cocos/3d/geom-utils/index.js b/cocos/3d/geom-utils/index.js index 30b4011744..99bd86140e 100644 --- a/cocos/3d/geom-utils/index.js +++ b/cocos/3d/geom-utils/index.js @@ -8,6 +8,6 @@ export { default as triangle } from './triangle'; export { default as sphere } from './sphere'; export { default as aabb } from './aabb'; export { default as obb } from './obb'; -export { default as frustum } from './frustum'; +export { frustum } from './frustum'; export { default as Octree } from './octree'; export { Keyframe, AnimationCurve } from './curve'; diff --git a/cocos/core/vmath/mat4.ts b/cocos/core/vmath/mat4.ts index ab86e056af..a2a99a9539 100644 --- a/cocos/core/vmath/mat4.ts +++ b/cocos/core/vmath/mat4.ts @@ -28,6 +28,23 @@ import { EPSILON } from './utils'; */ class mat4 { + public m00: number = 1; + public m01: number = 0; + public m02: number = 0; + public m03: number = 0; + public m04: number = 0; + public m05: number = 1; + public m06: number = 0; + public m07: number = 0; + public m08: number = 0; + public m09: number = 0; + public m10: number = 1; + public m11: number = 0; + public m12: number = 0; + public m13: number = 0; + public m14: number = 0; + public m15: number = 1; + /** * Creates a matrix, with elements specified separately. * @@ -985,7 +1002,7 @@ class mat4 { out.x = (mat.m06 - mat.m09) / S; out.y = (mat.m08 - mat.m02) / S; out.z = (mat.m01 - mat.m04) / S; - } else if ((mat.m00 > mat.m05) & (mat.m00 > mat.m10)) { + } else if ((mat.m00 > mat.m05) && (mat.m00 > mat.m10)) { S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; out.w = (mat.m06 - mat.m09) / S; out.x = 0.25 * S; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index 59634d6023..815c0b9c37 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -3,6 +3,7 @@ import { Root } from "../../core/root"; import { ForwardFlow } from "./forward-flow"; import { GFXRenderPass } from "../../gfx/render-pass"; import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../../gfx/define"; +import { RenderQueue } from "../render-queue"; export enum ForwardFlowPriority { FORWARD = 0, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index ef33409370..5eb9acff31 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -14,7 +14,7 @@ export class ForwardStage extends RenderStage { public initialize(info: RenderStageInfo): boolean { - if(info.name !== undefined) { + if (info.name !== undefined) { this._name = info.name; } @@ -38,13 +38,21 @@ export class ForwardStage extends RenderStage { } public render(view: RenderView) { - let cmdBuff = this._cmdBuff; + + let cmdBuff = this._cmdBuff as GFXCommandBuffer; + let queue = this._pipeline.queue; + this._renderArea.width = view.width; this._renderArea.height = view.height; cmdBuff.begin(); cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); - cmdBuff.draw(this._pipeline.quadIA); + + for (let item of queue.opaques) { + item.model.commandBuffers + } + + cmdBuff.endRenderPass(); cmdBuff.end(); diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 677bc3c90d..1c8aec9925 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -13,6 +13,7 @@ import { GFXTexture } from "../../gfx/texture"; import { GFXTextureView } from "../../gfx/texture-view"; import { GFXSampler } from "../../gfx/sampler"; import { GFXBuffer } from "../../gfx/buffer"; +import { UBOGlobal } from "../render-pipeline"; /* declare module '*.png' { @@ -88,20 +89,7 @@ export class TestStage extends RenderStage { this._shader = this._device.createShader({ name: "test", stages: [vsStage, fsStage], - blocks: [{ - binding: 0, name: "Global", members: [ - { name: "u_time", type: GFXType.FLOAT4, count: 1 }, - { name: "u_screenSize", type: GFXType.FLOAT4, count: 1 }, - { name: "u_screenScale", type: GFXType.FLOAT4, count: 1 }, - { name: "u_matView", type: GFXType.MAT4, count: 1 }, - { name: "u_matViewInv", type: GFXType.MAT4, count: 1 }, - { name: "u_matProj", type: GFXType.MAT4, count: 1 }, - { name: "u_matProjInv", type: GFXType.MAT4, count: 1 }, - { name: "u_matViewProj", type: GFXType.MAT4, count: 1 }, - { name: "u_matViewProjInv", type: GFXType.MAT4, count: 1 }, - { name: "u_cameraPos", type: GFXType.FLOAT4, count: 1 }, - ] - }, { + blocks: [UBOGlobal.BLOCK, { binding: 5, name: "UBO", members: [ { name: "u_color", type: GFXType.FLOAT4, count: 1 }, ] diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 6287654950..d8bd058c91 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,53 +1,127 @@ -import { RenderView } from "./render-view"; -import { RenderFlow, RenderFlowInfo } from "./render-flow"; -import { Root } from "../core/root"; -import { GFXRenderPass } from "../gfx/render-pass"; -import { GFXDevice } from "../gfx/device"; -import { GFXBuffer } from "../gfx/buffer"; -import { GFXInputAssembler, GFXInputAttribute } from "../gfx/input-assembler"; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../gfx/define"; -import { Camera } from "../renderer/scene/camera"; -import vec4 from "../core/vmath/vec4"; -import mat4 from "../core/vmath/mat4"; +import { Root } from '../core/root'; +import mat4 from '../core/vmath/mat4'; +import { GFXBuffer } from '../gfx/buffer'; +import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXType } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; +import { GFXInputAssembler, GFXInputAttribute } from '../gfx/input-assembler'; +import { GFXRenderPass } from '../gfx/render-pass'; +import { GFXTexture } from '../gfx/texture'; +import { GFXTextureView } from '../gfx/texture-view'; +import { Camera } from '../renderer/scene/camera'; +import { RenderFlow, RenderFlowInfo } from './render-flow'; +import { RenderView } from './render-view'; +import { vec3 } from '../core/vmath'; +import { RenderQueue } from './render-queue'; +import { intersect } from '../3d/geom-utils'; +import { GFXUniformBlock } from '../gfx/shader'; export enum RenderPassStage { DEFAULT = 100, -}; +} export class UBOGlobal { - static TIME_OFFSET: number = 0; - static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; - static SCREEN_SCALE_OFFSET: number = UBOGlobal.SCREEN_SIZE_OFFSET + 4; - static MAT_VIEW_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4; - static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16; - static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; - static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16; - static MAT_VIEW_PROJ_OFFSET: number = UBOGlobal.MAT_PROJ_INV_OFFSET + 16; - static MAT_VIEW_PROJ_INV_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_OFFSET + 16; - static CAMERA_POS_OFFSET: number = UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET + 16; - static COUNT: number = UBOGlobal.CAMERA_POS_OFFSET + 4; - static SIZE: number = UBOGlobal.COUNT * 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; + public static MAT_VIEW_OFFSET: number = UBOGlobal.SCREEN_SCALE_OFFSET + 4; + public static MAT_VIEW_INV_OFFSET: number = UBOGlobal.MAT_VIEW_OFFSET + 16; + public static MAT_PROJ_OFFSET: number = UBOGlobal.MAT_VIEW_INV_OFFSET + 16; + public static MAT_PROJ_INV_OFFSET: number = UBOGlobal.MAT_PROJ_OFFSET + 16; + 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 COUNT: number = UBOGlobal.CAMERA_POS_OFFSET + 4; + public static SIZE: number = UBOGlobal.COUNT * 4; - view: Float32Array = new Float32Array(UBOGlobal.COUNT); -}; + public static BLOCK: GFXUniformBlock = { + binding: 0, name: "Global", members: [ + { name: "u_time", type: GFXType.FLOAT4, count: 1 }, + { name: "u_screenSize", type: GFXType.FLOAT4, count: 1 }, + { name: "u_screenScale", type: GFXType.FLOAT4, count: 1 }, + { name: "u_matView", type: GFXType.MAT4, count: 1 }, + { name: "u_matViewInv", type: GFXType.MAT4, count: 1 }, + { name: "u_matProj", type: GFXType.MAT4, count: 1 }, + { name: "u_matProjInv", type: GFXType.MAT4, count: 1 }, + { name: "u_matViewProj", type: GFXType.MAT4, count: 1 }, + { name: "u_matViewProjInv", type: GFXType.MAT4, count: 1 }, + { name: "u_cameraPos", type: GFXType.FLOAT4, count: 1 }, + ] + }; + + public view: Float32Array = new Float32Array(UBOGlobal.COUNT); +} export class UBOLocal { - static MAT_WORLD_OFFSET: number = 0; - static MAT_WORLD_VIEW_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16; - static MAT_WORLD_VIEW_PROJ_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_OFFSET + 16; - static WORLD_POS_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_PROJ_OFFSET + 16; - static COUNT: number = UBOLocal.WORLD_POS_OFFSET + 4; - static SIZE: number = UBOGlobal.COUNT * 4; + public static MAT_WORLD_OFFSET: number = 0; + public static MAT_WORLD_VIEW_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16; + public static MAT_WORLD_VIEW_PROJ_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_OFFSET + 16; + public static WORLD_POS_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_PROJ_OFFSET + 16; + public static COUNT: number = UBOLocal.WORLD_POS_OFFSET + 4; + public static SIZE: number = UBOLocal.COUNT * 4; - view: Float32Array = new Float32Array(UBOLocal.COUNT); -}; + public static BLOCK: GFXUniformBlock = { + binding: 1, name: "Local", members: [ + { name: "u_matWorld", type: GFXType.MAT4, count: 1 }, + { name: "u_matWorldView", type: GFXType.MAT4, count: 1 }, + { name: "u_matWorldViewProj", type: GFXType.MAT4, count: 1 }, + { name: "u_worldPos", type: GFXType.FLOAT4, count: 1 }, + ] + }; -let _vec4Array = new Float32Array(4); -let _mat4Array = new Float32Array(16); -let _outMat = new mat4; + public view: Float32Array = new Float32Array(UBOLocal.COUNT); +} + +const _vec4Array = new Float32Array(4); +const _mat4Array = new Float32Array(16); +const _outMat = new mat4; export abstract class RenderPipeline { + public get root(): Root { + return this._root; + } + + public get device(): GFXDevice { + return this._device; + } + + public get queue(): RenderQueue { + return this._queue; + } + + public get flows(): RenderFlow[] { + return this._flows; + } + + public get quadIA(): GFXInputAssembler { + return this._quadIA as GFXInputAssembler; + } + + public get uboGlobal(): UBOGlobal { + return this._uboGlobal; + } + + public get globalUBO(): GFXBuffer { + return this._globalUBO as GFXBuffer; + } + + public get defaultTexture(): GFXTexture { + return this._defaultTex as GFXTexture; + } + + protected _root: Root; + protected _device: GFXDevice; + protected _queue: RenderQueue = new RenderQueue(); + protected _renderPasses: Map = new Map(); + protected _flows: RenderFlow[] = []; + protected _quadVB: GFXBuffer | null = null; + protected _quadIB: GFXBuffer | null = null; + protected _quadIA: GFXInputAssembler | null = null; + protected _uboGlobal: UBOGlobal = new UBOGlobal(); + protected _globalUBO: GFXBuffer | null = null; + protected _defaultTex: GFXTexture | null = null; + protected _defaultTexView: GFXTextureView | null = null; + constructor(root: Root) { this._root = root; this._device = root.device; @@ -58,6 +132,10 @@ export abstract class RenderPipeline { public render(view: RenderView) { + view.camera.update(); + + this.sceneCulling(view); + this.updateUBOs(view); for (let i = 0; i < this._flows.length; ++i) { @@ -72,7 +150,7 @@ export abstract class RenderPipeline { } public getRenderPass(stage: number): GFXRenderPass | null { - let renderPass = this._renderPasses.get(stage); + const renderPass = this._renderPasses.get(stage); if (renderPass) { return renderPass; } else { @@ -89,7 +167,7 @@ export abstract class RenderPipeline { } public createFlow(clazz: new (pipeline: RenderPipeline) => T, info: RenderFlowInfo): RenderFlow | null { - let flow: RenderFlow = new clazz(this); + const flow: RenderFlow = new clazz(this); if (flow.initialize(info)) { this._flows.push(flow); this._flows.sort((a: RenderFlow, b: RenderFlow) => { @@ -103,42 +181,18 @@ export abstract class RenderPipeline { } public destroyFlows() { - for (let i = 0; i < this._flows.length; ++i) { - this._flows[i].destroy(); + for (const flow of this._flows) { + flow.destroy(); } this._flows = []; } - public get root(): Root { - return this._root; - } - - public get device(): GFXDevice { - return this._device; - } - - public get flows(): RenderFlow[] { - return this._flows; - } - - public get quadIA(): GFXInputAssembler { - return this._quadIA; - } - - public get uboGlobal(): UBOGlobal { - return this._uboGlobal; - } - - public get globalUBO(): GFXBuffer { - return this._globalUBO; - } - protected createQuadInputAssembler(): boolean { // create vertex buffer - let vbStride = Float32Array.BYTES_PER_ELEMENT * 4; - let vbSize = vbStride * 4; + const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; + const vbSize = vbStride * 4; this._quadVB = this._device.createBuffer({ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, @@ -147,11 +201,11 @@ export abstract class RenderPipeline { stride: vbStride, }); - if(!this._quadVB) { + if (!this._quadVB) { return false; } - let verts = new Float32Array(4 * 4); + const verts = new Float32Array(4 * 4); let n = 0; verts[n++] = -1.0; verts[n++] = -1.0; verts[n++] = 0.0; verts[n++] = 0.0; verts[n++] = 1.0; verts[n++] = -1.0; verts[n++] = 1.0; verts[n++] = 0.0; @@ -161,8 +215,8 @@ export abstract class RenderPipeline { this._quadVB.update(verts); // create index buffer - let ibStride = Uint8Array.BYTES_PER_ELEMENT; - let ibSize = ibStride * 6; + const ibStride = Uint8Array.BYTES_PER_ELEMENT; + const ibSize = ibStride * 6; this._quadIB = this._device.createBuffer({ usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, @@ -171,11 +225,11 @@ export abstract class RenderPipeline { stride: ibStride, }); - if(!this._quadIB) { + if (!this._quadIB) { return false; } - let indices = new Uint8Array(6); + const indices = new Uint8Array(6); indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 1; indices[4] = 3; indices[5] = 2; @@ -183,9 +237,9 @@ export abstract class RenderPipeline { // create input assembler - let attributes: GFXInputAttribute[] = [ - {name: "a_position", format: GFXFormat.RG32F}, - {name: "a_texCoord", format: GFXFormat.RG32F}, + const attributes: GFXInputAttribute[] = [ + { name: 'a_position', format: GFXFormat.RG32F }, + { name: 'a_texCoord', format: GFXFormat.RG32F }, ]; this._quadIA = this._device.createInputAssembler({ @@ -198,17 +252,17 @@ export abstract class RenderPipeline { } protected destroyQuadInputAssembler() { - if(this._quadVB) { + if (this._quadVB) { this._quadVB.destroy(); this._quadVB = null; } - if(this._quadIB) { + if (this._quadIB) { this._quadIB.destroy(); this._quadIB = null; } - if(this._quadIA) { + if (this._quadIA) { this._quadIA.destroy(); this._quadIA = null; } @@ -221,7 +275,7 @@ export abstract class RenderPipeline { size: UBOGlobal.SIZE, }); - if(!this._globalUBO) { + if (!this._globalUBO) { return false; } @@ -229,14 +283,14 @@ export abstract class RenderPipeline { } protected destroyUBOs() { - if(this._globalUBO) { + if (this._globalUBO) { this._globalUBO.destroy(); this._globalUBO = null; } } protected updateUBOs(view: RenderView) { - let camera = view.camera; + const camera = view.camera as Camera; camera.update(); // update UBOGlobal @@ -248,8 +302,8 @@ export abstract class RenderPipeline { _vec4Array[0] = this._root.device.width; _vec4Array[1] = this._root.device.height; - _vec4Array[2] = 1.0/_vec4Array[0]; - _vec4Array[3] = 1.0/_vec4Array[1]; + _vec4Array[2] = 1.0 / _vec4Array[0]; + _vec4Array[3] = 1.0 / _vec4Array[1]; this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SIZE_OFFSET); _vec4Array[0] = 1.0; @@ -275,25 +329,41 @@ export abstract class RenderPipeline { mat4.array(_mat4Array, camera.matViewProj); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_OFFSET); - mat4.invert(_outMat, camera.matViewProj); - mat4.array(_mat4Array, _outMat); + mat4.array(_mat4Array, camera.matViewProjInv); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); - vec4.array(_vec4Array, camera.position); + vec3.array(_vec4Array, camera.position); _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); // update ubos - (this._globalUBO).update(this._uboGlobal.view); + (this._globalUBO as GFXBuffer).update(this._uboGlobal.view); } - protected _root: Root; - protected _device: GFXDevice; - protected _renderPasses: Map = new Map; - protected _flows: RenderFlow[] = []; - protected _quadVB: GFXBuffer | null = null; - protected _quadIB: GFXBuffer | null = null; - protected _quadIA: GFXInputAssembler | null = null; - protected _uboGlobal: UBOGlobal = new UBOGlobal; - protected _globalUBO: GFXBuffer | null = null; -}; + protected sceneCulling(view: RenderView) { + + let scene = view.scene; + let camera = view.camera; + + for (let model of scene.models) { + + // filter model by view visibility + if (view.visibility > 0 && model._viewID !== view.visibility) { + continue; + } + + model._updateTransform(); + + // frustum culling + if (model._boundingShape) { // if model does not have boundingBox, skip culling. + if (!intersect.aabb_frustum(model._boundingShape, camera.frustum)) { + // console.log('model is not in view frustum.'); + continue; + } + } + + // add model pass to render queue + this._queue.add(model); + } + } +} diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index d33721abb1..efb8e7002d 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -18,23 +18,28 @@ export class RenderQueue { constructor() { } - public add(model: Model, pass: Pass) { - let pso = pass.pipelineState; + public add(model: Model) { - let isTransparent = pso.blendState.targets[0].blend; + for(let i = 0; i < model.passes.length; ++i) { + let pass = model.passes[i]; - let hash: number = 0; + let pso = pass.pipelineState; - if(!isTransparent) { - // Opaque objects are sorted by depth front to back, then by shader id. - hash = (0 << 63) | (pso.shader.id << 13); - - this._opaques.push({hash, model, pass}); - } else { - // Transparent objects are sorted by depth back to front, then by by shader id. - hash = (1 << 63) | (pso.shader.id << 13); - - this._transparents.push({hash, model, pass}); + let isTransparent = pso.blendState.targets[0].blend; + + let hash: number = 0; + + if(!isTransparent) { + // Opaque objects are sorted by depth front to back, then by shader id. + hash = (0 << 63) | (pso.shader.id << 13); + + this._opaques.push({hash, model, pass}); + } else { + // Transparent objects are sorted by depth back to front, then by by shader id. + hash = (1 << 63) | (pso.shader.id << 13); + + this._transparents.push({hash, model, pass}); + } } } diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index 32447eaf43..88f0e30e04 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -84,6 +84,10 @@ export class RenderView { return this._priority; } + public get visibility(): number { + return this._visiblity; + } + public get width(): number { return this._width; } @@ -92,17 +96,22 @@ export class RenderView { return this._height; } - public get camera(): Camera | null { - return this._camera; + public get camera(): Camera { + return this._camera as Camera; } - public get scene(): RenderScene | null { - return this._scene; + public get scene(): RenderScene { + return this._scene as RenderScene; + } + + public set visibility(vis: number) { + this._visiblity = vis; } private _name: string = ""; private _window: GFXWindow | null = null; private _priority: number = 0; + private _visiblity: number = 0; private _width: number = 0; private _height: number = 0; private _scene: RenderScene | null = null; diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 6b59e7c0de..760c0a2e4c 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,6 +1,7 @@ import { RenderScene } from "./render-scene"; import Node from "../../scene-graph/node"; import { vec3, mat4, quat } from "../../core/vmath"; +import { frustum } from "../../3d/geom-utils/frustum"; export enum NodeSpace { @@ -16,6 +17,25 @@ export enum CameraProjection { export class Camera { + private _scene: RenderScene; + private _name: string; + private _node: Node; + private _proj: CameraProjection; + private _width: number; + private _height: number; + private _aspect: number; + private _fov: number; + private _nearClip: number; + private _farClip: number; + private _matView: mat4 = new mat4; + private _matProj: mat4 = new mat4; + private _matViewProj: mat4 = new mat4; + private _matViewProjInv: mat4 = new mat4; + private _position: vec3 = new vec3; + private _rotation: quat = new quat; + private _direction: vec3 = new vec3; + private _frustum: frustum = new frustum; + constructor(scene: RenderScene, name: string) { this._scene = scene; this._name = name; @@ -59,6 +79,9 @@ export class Camera { // view-projection mat4.mul(this._matViewProj, this._matProj, this._matView); + mat4.invert(this._matViewProjInv, this._matViewProj); + + this._frustum.update(this._matViewProj, this._matViewProjInv); } public set fov(fov: number) { @@ -121,6 +144,14 @@ export class Camera { return this._matViewProj; } + public get matViewProjInv(): mat4 { + return this._matViewProjInv; + } + + public get frustum(): frustum { + return this._frustum; + } + public get position(): vec3 { this._node.getWorldPosition(this._position); return this._position; @@ -211,21 +242,4 @@ export class Camera { quat.rotationTo(this._rotation, vec3.UNIT_Z, dir); this._node.setRotation(this._rotation); } - - private _scene: RenderScene; - private _name: string; - private _node: Node; - private _proj: CameraProjection; - private _width: number; - private _height: number; - private _aspect: number; - private _fov: number; - private _nearClip: number; - private _farClip: number; - private _matView: mat4 = new mat4; - private _matProj: mat4 = new mat4; - private _matViewProj: mat4 = new mat4; - private _position: vec3 = new vec3; - private _rotation: quat = new quat; - private _direction: vec3 = new vec3; }; diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 4a90af6393..7e5840880a 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -11,6 +11,7 @@ import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { Material } from '../../3d/assets/material'; +import { RenderItem } from '../../pipeline/render-queue'; /** * A representation of a model @@ -149,7 +150,10 @@ export default class Model { this.recordCommandBuffer(i); } for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { - this._cmdBuffers.pop().destroy(); + let cmdBuff = this._cmdBuffers.pop(); + if(cmdBuff) { + cmdBuff.destroy(); + } } } @@ -177,11 +181,11 @@ export default class Model { this._userKey = key; } - get passList(): Pass[] { + get passes(): Pass[] { return (this._material).passes; } - get cmdBufferList(): GFXCommandBuffer[] { + get commandBuffers(): GFXCommandBuffer[] { return this._cmdBuffers; } diff --git a/tslint.json b/tslint.json index 3304af09b8..f3229bf7da 100644 --- a/tslint.json +++ b/tslint.json @@ -11,7 +11,8 @@ "max-classes-per-file": false, "variable-name": false, "object-literal-sort-keys": false, - "ban-types": false + "ban-types": false, + "no-bitwise:": false, }, "rulesDirectory": [] } \ No newline at end of file From 7e511572e37c7a716501ab42df43408c4ef8f68d Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 9 Jan 2019 16:58:53 +0800 Subject: [PATCH 069/267] fix tslint error rules --- cocos/core/root.ts | 4 +- cocos/gfx/binding-layout.ts | 69 +- cocos/gfx/buffer.ts | 34 +- cocos/gfx/command-allocator.ts | 14 +- cocos/gfx/command-buffer.ts | 56 +- cocos/gfx/define.ts | 36 +- cocos/gfx/device.ts | 64 +- cocos/gfx/framebuffer.ts | 31 +- cocos/gfx/index.ts | 16 +- cocos/gfx/input-assembler.ts | 82 +-- cocos/gfx/pipeline-layout.ts | 36 +- cocos/gfx/pipeline-state.ts | 150 ++--- cocos/gfx/queue.ts | 32 +- cocos/gfx/render-pass.ts | 86 ++- cocos/gfx/sampler.ts | 85 ++- cocos/gfx/shader.ts | 74 +-- cocos/gfx/texture-view.ts | 36 +- cocos/gfx/texture.ts | 44 +- cocos/gfx/webgl/webgl-binding-layout.ts | 34 +- cocos/gfx/webgl/webgl-buffer.ts | 44 +- cocos/gfx/webgl/webgl-command-allocator.ts | 54 +- cocos/gfx/webgl/webgl-command-buffer.ts | 114 ++-- cocos/gfx/webgl/webgl-commands.ts | 632 +++++++++---------- cocos/gfx/webgl/webgl-device.ts | 694 ++++++++++----------- cocos/gfx/webgl/webgl-framebuffer.ts | 39 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 298 ++++----- cocos/gfx/webgl/webgl-input-assembler.ts | 40 +- cocos/gfx/webgl/webgl-pipeline-layout.ts | 32 +- cocos/gfx/webgl/webgl-pipeline-state.ts | 30 +- cocos/gfx/webgl/webgl-queue.ts | 23 +- cocos/gfx/webgl/webgl-render-pass.ts | 32 +- cocos/gfx/webgl/webgl-sampler.ts | 64 +- cocos/gfx/webgl/webgl-shader.ts | 34 +- cocos/gfx/webgl/webgl-state-cache.ts | 93 ++- cocos/gfx/webgl/webgl-texture-view.ts | 32 +- cocos/gfx/webgl/webgl-texture.ts | 36 +- cocos/gfx/webgl/webgl-window.ts | 38 +- cocos/gfx/window.ts | 46 +- cocos/pipeline/forward/forward-flow.ts | 6 +- cocos/pipeline/forward/test-stage.ts | 146 ++--- cocos/pipeline/render-pipeline.ts | 108 ++-- cocos/pipeline/render-stage.ts | 10 +- cocos/renderer/scene/model.ts | 2 +- tslint.json | 11 +- 44 files changed, 1800 insertions(+), 1841 deletions(-) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 26dbfe5c87..c42b2019da 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,4 +1,4 @@ -import { GFXWindow, GFXWindowInfo } from "../gfx/window"; +import { GFXWindow, IGFXWindowInfo } from "../gfx/window"; import { GFXDevice } from "../gfx/device"; import { RenderView, RenderViewInfo } from "../pipeline/render-view"; import { RenderPipeline } from "../pipeline/render-pipeline"; @@ -60,7 +60,7 @@ export class Root { (this._device).present(); } - public createWindow(info: GFXWindowInfo): GFXWindow | null { + public createWindow(info: IGFXWindowInfo): GFXWindow | null { if (this._device) { let window = this._device.createWindow(info); if (window) { diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index b2b6e37724..33156a860e 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -1,84 +1,81 @@ -import { GFXDevice } from './device'; import { GFXBuffer } from './buffer'; -import { GFXTextureView } from './texture-view'; -import { GFXSampler } from './sampler'; import { GFXBindingType } from './define'; +import { GFXDevice } from './device'; +import { GFXSampler } from './sampler'; +import { GFXTextureView } from './texture-view'; -export interface GFXBinding { +export interface IGFXBinding { binding: number; type: GFXBindingType; name: string; -}; +} -export interface GFXBindingLayoutInfo { - bindings: GFXBinding[]; -}; +export interface IGFXBindingLayoutInfo { + bindings: IGFXBinding[]; +} export class GFXBindingUnit { - binding: number = 0; - type: GFXBindingType = GFXBindingType.UNKNOWN; - name: string = ""; - buffer: GFXBuffer | null = null; - texView: GFXTextureView | null = null; - sampler: GFXSampler | null = null; -}; + public binding: number = 0; + public type: GFXBindingType = GFXBindingType.UNKNOWN; + public name: string = ''; + public buffer: GFXBuffer | null = null; + public texView: GFXTextureView | null = null; + public sampler: GFXSampler | null = null; +} export abstract class GFXBindingLayout { - constructor(device: GFXDevice) { + protected _device: GFXDevice; + protected _bindingUnits: GFXBindingUnit[] = []; + + constructor (device: GFXDevice) { this._device = device; } - public abstract initialize(info: GFXBindingLayoutInfo): boolean; - public abstract destroy(); - public abstract update(); + public abstract initialize (info: IGFXBindingLayoutInfo): boolean; + public abstract destroy (); + public abstract update (); - public bindBuffer(binding: number, buffer: GFXBuffer) { - for (let i = 0; i < this._bindingUnits.length; ++i) { - let bindingUnit = this._bindingUnits[i]; + public bindBuffer (binding: number, buffer: GFXBuffer) { + for (const bindingUnit of this._bindingUnits) { if (bindingUnit.binding === binding) { if (bindingUnit.type === GFXBindingType.UNIFORM_BUFFER) { bindingUnit.buffer = buffer; } else { - console.error("Setting binding is not GFXBindingType.UNIFORM_BUFFER."); + console.error('Setting binding is not GFXBindingType.UNIFORM_BUFFER.'); } return; } } } - public bindSampler(binding: number, sampler: GFXSampler) { - for (let i = 0; i < this._bindingUnits.length; ++i) { - let bindingUnit = this._bindingUnits[i]; + public bindSampler (binding: number, sampler: GFXSampler) { + for (const bindingUnit of this._bindingUnits) { if (bindingUnit.binding === binding) { if (bindingUnit.type === GFXBindingType.SAMPLER) { bindingUnit.sampler = sampler; } else { - console.error("Setting binding is not GFXBindingType.SAMPLER."); + console.error('Setting binding is not GFXBindingType.SAMPLER.'); } return; } } } - public bindTextureView(binding: number, texView: GFXTextureView) { - for (let i = 0; i < this._bindingUnits.length; ++i) { - let bindingUnit = this._bindingUnits[i]; + public bindTextureView (binding: number, texView: GFXTextureView) { + for (const bindingUnit of this._bindingUnits) { if (bindingUnit.binding === binding) { if (bindingUnit.type === GFXBindingType.SAMPLER) { bindingUnit.texView = texView; } else { - console.error("Setting binding is not GFXBindingType.SAMPLER."); + console.error('Setting binding is not GFXBindingType.SAMPLER.'); } return; } } } - public getBindingUnit(binding: number): GFXBindingUnit { + public getBindingUnit (binding: number): GFXBindingUnit { return this._bindingUnits[binding]; } - - protected _device: GFXDevice; - protected _bindingUnits: GFXBindingUnit[] = []; -}; +} diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index f575bb4310..58a9cb0518 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -1,40 +1,32 @@ +import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from './define'; import { GFXDevice } from './device'; -import { GFXBufferUsage, GFXMemoryUsage, GFXBufferUsageBit, GFXMemoryUsageBit } from './define'; -export interface GFXBufferInfo { +export interface IGFXBufferInfo { usage: GFXBufferUsage; memUsage: GFXMemoryUsage; size: number; stride?: number; -}; +} export abstract class GFXBuffer { - constructor(device: GFXDevice) { - this._device = device; - } - - public abstract initialize(info: GFXBufferInfo): boolean; - public abstract destroy(): void; - public abstract update(buffer: ArrayBuffer, offset?: number); - - public get usage(): GFXBufferUsage { + public get usage (): GFXBufferUsage { return this._usage; } - public get memUsage(): GFXMemoryUsage { + public get memUsage (): GFXMemoryUsage { return this._memUsage; } - public get size(): number { + public get size (): number { return this._size; } - public get stride(): number { + public get stride (): number { return this._stride; } - public get buffer(): ArrayBuffer | null { + public get buffer (): ArrayBuffer | null { return this._buffer; } @@ -45,4 +37,12 @@ export abstract class GFXBuffer { protected _stride: number = 1; protected _buffer: ArrayBuffer | null = null; protected _bufferView: Uint8Array | null = null; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXBufferInfo): boolean; + public abstract destroy (): void; + public abstract update (buffer: ArrayBuffer, offset?: number); +} diff --git a/cocos/gfx/command-allocator.ts b/cocos/gfx/command-allocator.ts index 5ac927da20..2fd580eed8 100644 --- a/cocos/gfx/command-allocator.ts +++ b/cocos/gfx/command-allocator.ts @@ -1,16 +1,16 @@ import { GFXDevice } from './device'; -export interface GFXCommandAllocatorInfo { -}; +export interface IGFXCommandAllocatorInfo { +} export abstract class GFXCommandAllocator { - constructor(device : GFXDevice) { + protected _device: GFXDevice; + + constructor (device: GFXDevice) { this._device = device; } - public abstract initialize(info: GFXCommandAllocatorInfo) : boolean; - public abstract destroy(); - - protected _device : GFXDevice; + public abstract initialize (info: IGFXCommandAllocatorInfo): boolean; + public abstract destroy (); } diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index c131262d9d..142474ccbe 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -1,44 +1,44 @@ -import { GFXDevice } from './device'; -import { GFXCommandAllocator } from './command-allocator'; +import { GFXBindingLayout } from './binding-layout'; import { GFXBuffer } from './buffer'; +import { GFXCommandAllocator } from './command-allocator'; +import { GFXBufferTextureCopy, GFXCommandBufferType, GFXTextureLayout, IGFXColor, IGFXRect } from './define'; +import { GFXDevice } from './device'; +import { GFXFramebuffer } from './framebuffer'; import { GFXInputAssembler } from './input-assembler'; import { GFXPipelineState } from './pipeline-state'; -import { GFXBindingLayout } from './binding-layout'; import { GFXTexture } from './texture'; -import { GFXFramebuffer } from './framebuffer'; -import { GFXColor, GFXRect, GFXCommandBufferType, GFXBufferTextureCopy, GFXTextureLayout } from './define'; -export interface GFXCommandBufferInfo { +export interface IGFXCommandBufferInfo { allocator: GFXCommandAllocator; type: GFXCommandBufferType; -}; +} export abstract class GFXCommandBuffer { - constructor(device: GFXDevice) { - this._device = device; - } - - public abstract initialize(info: GFXCommandBufferInfo): boolean; - public abstract destroy(); - - public abstract begin(); - public abstract end(); - public abstract beginRenderPass(framebuffer: GFXFramebuffer, renderArea: GFXRect, clearColors: GFXColor[], clearDepth: number, clearStencil: number); - public abstract endRenderPass(); - public abstract bindPipelineState(pipelineState: GFXPipelineState); - public abstract bindBindingLayout(bindingLayout: GFXBindingLayout); - public abstract bindInputAssembler(inputAssembler: GFXInputAssembler); - 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[]); - public abstract execute(cmdBuffs: GFXCommandBuffer[]); - - public get type(): number { + public get type (): number { return this._type; } protected _device: GFXDevice; protected _allocator: GFXCommandAllocator | null = null; protected _type: GFXCommandBufferType = GFXCommandBufferType.PRIMARY; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXCommandBufferInfo): boolean; + public abstract destroy (); + + public abstract begin (); + public abstract end (); + public abstract beginRenderPass (framebuffer: GFXFramebuffer, renderArea: IGFXRect, clearColors: IGFXColor[], clearDepth: number, clearStencil: number); + public abstract endRenderPass (); + public abstract bindPipelineState (pipelineState: GFXPipelineState); + public abstract bindBindingLayout (bindingLayout: GFXBindingLayout); + public abstract bindInputAssembler (inputAssembler: GFXInputAssembler); + 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[]); + public abstract execute (cmdBuffs: GFXCommandBuffer[]); +} diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index eb4da23120..edb48d1f32 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -414,14 +414,14 @@ export enum GFXQueueType { // Interfaces -export interface GFXRect { +export interface IGFXRect { x: number; y: number; width: number; height: number; } -export interface GFXViewport { +export interface IGFXViewport { left: number; top: number; width: number; @@ -430,20 +430,20 @@ export interface GFXViewport { maxDepth: number; } -export interface GFXColor { +export interface IGFXColor { r: number; g: number; b: number; a: number; } -export interface GFXOffset { +export interface IGFXOffset { x: number; y: number; z: number; } -export interface GFXExtent { +export interface IGFXExtent { width: number; height: number; depth: number; @@ -457,23 +457,23 @@ export class GFXTextureSubres { } export class GFXTextureCopy { - public srcSubres: GFXTextureSubres = new GFXTextureSubres; - public srcOffset: GFXOffset = { x: 0, y: 0, z: 0 }; - public dstSubres: GFXTextureSubres = new GFXTextureSubres; - public dstOffset: GFXOffset = { x: 0, y: 0, z: 0 }; - public extent: GFXExtent = { width: 0, height: 0, depth: 0 }; + public srcSubres: GFXTextureSubres = new GFXTextureSubres(); + public srcOffset: IGFXOffset = { x: 0, y: 0, z: 0 }; + public dstSubres: GFXTextureSubres = new GFXTextureSubres(); + public dstOffset: IGFXOffset = { x: 0, y: 0, z: 0 }; + public extent: IGFXExtent = { width: 0, height: 0, depth: 0 }; } export class GFXBufferTextureCopy { public buffOffset: number = 0; public buffStride: number = 0; public buffTexHeight: number = 0; - public texOffset: GFXOffset = { x: 0, y: 0, z: 0 }; - public texExtent: GFXExtent = { width: 0, height: 0, depth: 0 }; - public texSubres: GFXTextureSubres = new GFXTextureSubres; + public texOffset: IGFXOffset = { x: 0, y: 0, z: 0 }; + public texExtent: IGFXExtent = { width: 0, height: 0, depth: 0 }; + public texSubres: GFXTextureSubres = new GFXTextureSubres(); } -export interface GFXFormatInfo { +export interface IGFXFormatInfo { readonly name: string; readonly size: number; readonly count: number; @@ -484,7 +484,7 @@ export interface GFXFormatInfo { readonly isCompressed: boolean; } -export const GFXFormatInfos: GFXFormatInfo[] = [ +export const GFXFormatInfos: IGFXFormatInfo[] = [ { name: 'UNKNOWN', size: 0, count: 0, isFloating: false, hasAlpha: false, hasDepth: false, hasStencil: false, isCompressed: false }, @@ -590,7 +590,7 @@ export const GFXFormatInfos: GFXFormatInfo[] = [ { name: 'PVRTC2_4BPP', size: 2, count: 4, isFloating: false, hasAlpha: true, hasDepth: false, hasStencil: false, isCompressed: true }, ]; -export function GFXFormatSize(format: GFXFormat, width: number, height: number, depth: number): number { +export function GFXFormatSize (format: GFXFormat, width: number, height: number, depth: number): number { if (!GFXFormatInfos[format].isCompressed) { return (width * height * depth * GFXFormatInfos[format].size); @@ -644,7 +644,7 @@ export function GFXFormatSize(format: GFXFormat, width: number, height: number, } } -export function GFXFormatSurfaceSize(format: GFXFormat, width: number, height: number, depth: number, mips: number): number { +export function GFXFormatSurfaceSize (format: GFXFormat, width: number, height: number, depth: number, mips: number): number { let size = 0; @@ -658,7 +658,7 @@ export function GFXFormatSurfaceSize(format: GFXFormat, width: number, height: n return size; } -export function GFXGetTypeSize(type: GFXType): number { +export function GFXGetTypeSize (type: GFXType): number { switch (type) { case GFXType.BOOL: case GFXType.INT: diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 0a9e3b6a21..8d118b7d59 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -1,24 +1,24 @@ -import { GFXBindingLayout, GFXBindingLayoutInfo } from './binding-layout'; -import { GFXBuffer, GFXBufferInfo } from './buffer'; -import { GFXCommandAllocator, GFXCommandAllocatorInfo } from './command-allocator'; -import { GFXCommandBuffer, GFXCommandBufferInfo } from './command-buffer'; +import { GFXBindingLayout, IGFXBindingLayoutInfo } from './binding-layout'; +import { GFXBuffer, IGFXBufferInfo } from './buffer'; +import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from './command-allocator'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from './command-buffer'; import { GFXBufferTextureCopy, GFXFormat } from './define'; -import { GFXFramebuffer, GFXFramebufferInfo } from './framebuffer'; -import { GFXInputAssembler, GFXInputAssemblerInfo } from './input-assembler'; -import { GFXPipelineLayout, GFXPipelineLayoutInfo } from './pipeline-layout'; -import { GFXPipelineState, GFXPipelineStateInfo } from './pipeline-state'; -import { GFXQueue, GFXQueueInfo } from './queue'; -import { GFXRenderPass, GFXRenderPassInfo } from './render-pass'; -import { GFXSampler, GFXSamplerInfo } from './sampler'; -import { GFXShader, GFXShaderInfo } from './shader'; -import { GFXTexture, GFXTextureInfo } from './texture'; -import { GFXTextureView, GFXTextureViewInfo } from './texture-view'; -import { GFXWindow, GFXWindowInfo } from './window'; +import { GFXFramebuffer, IGFXFramebufferInfo } from './framebuffer'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from './input-assembler'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from './pipeline-layout'; +import { GFXPipelineState, IGFXPipelineStateInfo } from './pipeline-state'; +import { GFXQueue, IGFXQueueInfo } from './queue'; +import { GFXRenderPass, IGFXRenderPassInfo } from './render-pass'; +import { GFXSampler, IGFXSamplerInfo } from './sampler'; +import { GFXShader, IGFXShaderInfo } from './shader'; +import { GFXTexture, IGFXTextureInfo } from './texture'; +import { GFXTextureView, IGFXTextureViewInfo } from './texture-view'; +import { GFXWindow, IGFXWindowInfo } from './window'; export enum GFXFeature { } -export interface GFXDeviceInfo { +export interface IGFXDeviceInfo { canvasElm: HTMLElement; isAntialias?: boolean; isPremultipliedAlpha?: boolean; @@ -120,23 +120,23 @@ export abstract class GFXDevice { protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; protected _shaderIdGen: number = 0; - public abstract initialize (info: GFXDeviceInfo): boolean; + public abstract initialize (info: IGFXDeviceInfo): boolean; public abstract destroy (): void; - public abstract createBuffer (info: GFXBufferInfo): GFXBuffer | null; - public abstract createTexture (info: GFXTextureInfo): GFXTexture | null; - public abstract createTextureView (info: GFXTextureViewInfo): GFXTextureView | null; - public abstract createSampler (info: GFXSamplerInfo): GFXSampler | null; - public abstract createBindingLayout (info: GFXBindingLayoutInfo): GFXBindingLayout | null; - public abstract createShader (info: GFXShaderInfo): GFXShader | null; - public abstract createInputAssembler (info: GFXInputAssemblerInfo): GFXInputAssembler | null; - public abstract createRenderPass (info: GFXRenderPassInfo): GFXRenderPass | null; - public abstract createFramebuffer (info: GFXFramebufferInfo): GFXFramebuffer | null; - public abstract createPipelineLayout (info: GFXPipelineLayoutInfo): GFXPipelineLayout | null; - public abstract createPipelineState (info: GFXPipelineStateInfo): GFXPipelineState | null; - public abstract createCommandAllocator (info: GFXCommandAllocatorInfo): GFXCommandAllocator | null; - public abstract createCommandBuffer (info: GFXCommandBufferInfo): GFXCommandBuffer | null; - public abstract createQueue (info: GFXQueueInfo): GFXQueue | null; - public abstract createWindow (info: GFXWindowInfo): GFXWindow | null; + public abstract createBuffer (info: IGFXBufferInfo): GFXBuffer | null; + public abstract createTexture (info: IGFXTextureInfo): GFXTexture | null; + public abstract createTextureView (info: IGFXTextureViewInfo): GFXTextureView | null; + public abstract createSampler (info: IGFXSamplerInfo): GFXSampler | null; + public abstract createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout | null; + public abstract createShader (info: IGFXShaderInfo): GFXShader | null; + public abstract createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler | null; + public abstract createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass | null; + public abstract createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer | null; + public abstract createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout | null; + public abstract createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState | null; + public abstract createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator | null; + public abstract createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer | null; + public abstract createQueue (info: IGFXQueueInfo): GFXQueue | null; + public abstract createWindow (info: IGFXWindowInfo): GFXWindow | null; public abstract present (); public abstract copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); diff --git a/cocos/gfx/framebuffer.ts b/cocos/gfx/framebuffer.ts index c5a6f3d7ef..e20a240b7a 100644 --- a/cocos/gfx/framebuffer.ts +++ b/cocos/gfx/framebuffer.ts @@ -1,37 +1,29 @@ import { GFXDevice } from './device'; -import { GFXTextureView } from './texture-view'; import { GFXRenderPass } from './render-pass'; -import { GFXFormat } from './define'; +import { GFXTextureView } from './texture-view'; -export interface GFXFramebufferInfo { +export interface IGFXFramebufferInfo { renderPass: GFXRenderPass; colorViews?: GFXTextureView[]; depthStencilView?: GFXTextureView; isOffscreen?: boolean; -}; +} export abstract class GFXFramebuffer { - constructor(device: GFXDevice) { - this._device = device; - } - - public abstract initialize(info: GFXFramebufferInfo): boolean; - public abstract destroy(): void; - - public get renderPass(): GFXRenderPass | null { + public get renderPass (): GFXRenderPass | null { return this._renderPass; } - public get colorViews(): GFXTextureView[] { + public get colorViews (): GFXTextureView[] { return this._colorViews; } - public get depthStencilView(): GFXTextureView | null { + public get depthStencilView (): GFXTextureView | null { return this._depthStencilView; } - public get isOffscreen(): boolean { + public get isOffscreen (): boolean { return this._isOffscreen; } @@ -40,4 +32,11 @@ export abstract class GFXFramebuffer { protected _colorViews: GFXTextureView[] = []; protected _depthStencilView: GFXTextureView | null = null; protected _isOffscreen: boolean = true; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXFramebufferInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/index.ts b/cocos/gfx/index.ts index 7ddb6bb1fa..c29b229b47 100644 --- a/cocos/gfx/index.ts +++ b/cocos/gfx/index.ts @@ -1,16 +1,16 @@ -import { GFXDevice } from './device'; import { GFXBuffer } from './buffer'; -import { GFXTexture } from './texture'; -import { GFXTextureView } from './texture-view'; -import { GFXSampler } from './sampler'; -import { GFXShader } from './shader'; -import { GFXInputAssembler } from './input-assembler'; -import { GFXRenderPass } from './render-pass'; +import { GFXCommandBuffer } from './command-buffer'; +import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; +import { GFXInputAssembler } from './input-assembler'; import { GFXPipelineLayout } from './pipeline-layout'; import { GFXPipelineState } from './pipeline-state'; -import { GFXCommandBuffer } from './command-buffer'; import { GFXQueue } from './queue'; +import { GFXRenderPass } from './render-pass'; +import { GFXSampler } from './sampler'; +import { GFXShader } from './shader'; +import { GFXTexture } from './texture'; +import { GFXTextureView } from './texture-view'; import { WebGLGFXDevice } from './webgl/webgl-device'; cc.GFXDevice = GFXDevice; diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 9bac9ff01f..b17caeb8c1 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,110 +1,95 @@ -import { GFXDevice } from './device'; -import { GFXFormat } from './define'; import { GFXBuffer } from './buffer'; +import { GFXFormat } from './define'; +import { GFXDevice } from './device'; -export interface GFXInputAttribute { +export interface IGFXInputAttribute { binding?: number; name: string; format: GFXFormat; isNormalized?: boolean; stream?: number; isInstanced?: boolean; -}; +} -export interface GFXInputAssemblerInfo { - attributes: GFXInputAttribute[]; +export interface IGFXInputAssemblerInfo { + attributes: IGFXInputAttribute[]; vertexBuffers: GFXBuffer[]; indexBuffer?: GFXBuffer; isIndirect?: boolean; -}; +} export abstract class GFXInputAssembler { - constructor(device: GFXDevice) { - this._device = device; - } - - public abstract initialize(info: GFXInputAssemblerInfo): boolean; - public abstract destroy(): void; - - public get vertexBuffers(): GFXBuffer[] { + public get vertexBuffers (): GFXBuffer[] { return this._vertexBuffers; } - public get indexBuffer(): GFXBuffer | null { + public get indexBuffer (): GFXBuffer | null { return this._indexBuffer; } - public getVertexBuffer(stream: number): GFXBuffer | null { - if (stream < this._vertexBuffers.length) { - return this._vertexBuffers[stream]; - } else { - return null; - } - } - - public get attributes(): GFXInputAttribute[] { + public get attributes (): IGFXInputAttribute[] { return this._attributes; } - public get vertexCount(): number { + public get vertexCount (): number { return this._vertexCount; } - public set vertexCount(count : number) { + public set vertexCount (count: number) { this._vertexCount = count; } - public get firstVertex(): number { + public get firstVertex (): number { return this._firstVertex; } - public set firstVertex(first : number) { + public set firstVertex (first: number) { this._firstVertex = first; } - public get indexCount(): number { + public get indexCount (): number { return this._indexCount; } - public set indexCount(count : number) { + public set indexCount (count: number) { this._indexCount = count; } - public get firstIndex(): number { + public get firstIndex (): number { return this._firstIndex; } - public set firstIndex(first : number) { + public set firstIndex (first: number) { this._firstIndex = first; } - public get vertexOffset(): number { + public get vertexOffset (): number { return this._vertexOffset; } - public set vertexOffset(offset : number) { + public set vertexOffset (offset: number) { this._vertexOffset = offset; } - public get instanceCount(): number { + public get instanceCount (): number { return this._instanceCount; } - public set instanceCount(count : number) { + public set instanceCount (count: number) { this._instanceCount = count; } - public get firstInstance(): number { + public get firstInstance (): number { return this._firstInstance; } - public set firstInstance(first : number) { + public set firstInstance (first: number) { this._firstInstance = first; } protected _device: GFXDevice; - protected _attributes: GFXInputAttribute[] = []; + protected _attributes: IGFXInputAttribute[] = []; protected _vertexBuffers: GFXBuffer[] = []; protected _indexBuffer: GFXBuffer | null = null; protected _vertexCount: number = 0; @@ -115,4 +100,19 @@ export abstract class GFXInputAssembler { protected _instanceCount: number = 0; protected _firstInstance: number = 0; protected _isIndirect: boolean = false; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXInputAssemblerInfo): boolean; + public abstract destroy (): void; + + public getVertexBuffer (stream: number): GFXBuffer | null { + if (stream < this._vertexBuffers.length) { + return this._vertexBuffers[stream]; + } else { + return null; + } + } +} diff --git a/cocos/gfx/pipeline-layout.ts b/cocos/gfx/pipeline-layout.ts index 9f883248bf..7137bced05 100644 --- a/cocos/gfx/pipeline-layout.ts +++ b/cocos/gfx/pipeline-layout.ts @@ -1,28 +1,28 @@ -import { GFXDevice } from './device'; import { GFXBindingLayout } from './binding-layout'; import { GFXShaderType } from './define'; +import { GFXDevice } from './device'; -export interface GFXPushConstantRange { - shaderType : GFXShaderType; - offset : number; - count : number; -}; +export interface IGFXPushConstantRange { + shaderType: GFXShaderType; + offset: number; + count: number; +} -export interface GFXPipelineLayoutInfo { - pushConstantsRanges? : GFXPushConstantRange[]; - layouts : GFXBindingLayout[]; -}; +export interface IGFXPipelineLayoutInfo { + pushConstantsRanges?: IGFXPushConstantRange[]; + layouts: GFXBindingLayout[]; +} export abstract class GFXPipelineLayout { - constructor(device : GFXDevice) { + protected _device: GFXDevice; + protected _pushConstantsRanges: IGFXPushConstantRange[] = []; + protected _layouts: GFXBindingLayout[] = []; + + constructor (device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXPipelineLayoutInfo) : boolean; - public abstract destroy() : void; - - protected _device : GFXDevice; - protected _pushConstantsRanges : GFXPushConstantRange[] = []; - protected _layouts: GFXBindingLayout[] = []; -}; + public abstract initialize (info: IGFXPipelineLayoutInfo): boolean; + public abstract destroy (); +} diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index 8d091141b0..c2d22276ce 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -1,23 +1,23 @@ +import { GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXComparisonFunc, GFXCullMode, GFXPolygonMode, GFXPrimitiveMode, GFXShadeModel, GFXStencilOp } from './define'; import { GFXDevice } from './device'; -import { GFXShader } from './shader'; -import { GFXRenderPass } from './render-pass'; +import { IGFXInputAttribute } from './input-assembler'; import { GFXPipelineLayout } from './pipeline-layout'; -import { GFXInputAttribute } from './input-assembler'; -import { GFXPolygonMode, GFXShadeModel, GFXCullMode, GFXComparisonFunc, GFXStencilOp, GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXPrimitiveMode } from './define'; +import { GFXRenderPass } from './render-pass'; +import { GFXShader } from './shader'; export class GFXRasterizerState { - isDiscard: boolean = false; - polygonMode: GFXPolygonMode = GFXPolygonMode.FILL; - shadeModel: GFXShadeModel = GFXShadeModel.GOURAND; - cullMode: GFXCullMode = GFXCullMode.BACK; - isFrontFaceCCW: boolean = true; - depthBias: number = 0.0; - depthBiasFactor: number = 0.0; - isDepthClip: boolean = true; - isMultisample: boolean = false; + public isDiscard: boolean = false; + public polygonMode: GFXPolygonMode = GFXPolygonMode.FILL; + 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 isDepthClip: boolean = true; + public isMultisample: boolean = false; // lineWidth: number = 1.0; - public compare(state: GFXRasterizerState): boolean { + public compare (state: GFXRasterizerState): boolean { return (this.isDiscard === state.isDiscard) && (this.polygonMode === state.polygonMode) && (this.shadeModel === state.shadeModel) && @@ -29,30 +29,30 @@ export class GFXRasterizerState { // (this.lineWidth === state.lineWidth) && (this.isMultisample === state.isMultisample); } -}; +} export class GFXDepthStencilState { - depthTest: boolean = true; - depthWrite: boolean = true; - depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; - stencilTestFront: boolean = false; - stencilFuncFront: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - stencilReadMaskFront: number = 0xffffffff; - stencilWriteMaskFront: number = 0xffffffff; - stencilFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; - stencilZFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; - stencilPassOpFront: GFXStencilOp = GFXStencilOp.KEEP; - stencilRefFront: number = 1; - stencilTestBack: boolean = false; - stencilFuncBack: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - stencilReadMaskBack: number = 0xffffffff; - stencilWriteMaskBack: number = 0xffffffff; - stencilFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; - stencilZFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; - stencilPassOpBack: GFXStencilOp = GFXStencilOp.KEEP; - stencilRefBack: number = 1; + public depthTest: boolean = true; + public depthWrite: boolean = true; + public depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; + public stencilTestFront: boolean = false; + public stencilFuncFront: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + public stencilReadMaskFront: number = 0xffffffff; + public stencilWriteMaskFront: number = 0xffffffff; + public stencilFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; + public stencilZFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; + public stencilPassOpFront: GFXStencilOp = GFXStencilOp.KEEP; + public stencilRefFront: number = 1; + public stencilTestBack: boolean = false; + public stencilFuncBack: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; + public stencilReadMaskBack: number = 0xffffffff; + public stencilWriteMaskBack: number = 0xffffffff; + public stencilFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; + public stencilZFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; + public stencilPassOpBack: GFXStencilOp = GFXStencilOp.KEEP; + public stencilRefBack: number = 1; - public compare(state: GFXDepthStencilState): boolean { + public compare (state: GFXDepthStencilState): boolean { return (this.depthTest === state.depthTest) && (this.depthWrite === state.depthWrite) && (this.depthFunc === state.depthFunc) && @@ -73,19 +73,19 @@ export class GFXDepthStencilState { (this.stencilPassOpBack === state.stencilPassOpBack) && (this.stencilRefBack === state.stencilRefBack); } -}; +} export class GFXBlendTarget { - blend: boolean = false; - blendSrc: GFXBlendFactor = GFXBlendFactor.ONE; - blendDst: GFXBlendFactor = GFXBlendFactor.ZERO; - blendEq: GFXBlendOp = GFXBlendOp.ADD; - blendSrcAlpha: GFXBlendFactor = GFXBlendFactor.ONE; - blendDstAlpha: GFXBlendFactor = GFXBlendFactor.ZERO; - blendAlphaEq: GFXBlendOp = GFXBlendOp.ADD; - blendColorMask: GFXColorMask = GFXColorMask.ALL; + public blend: boolean = false; + public blendSrc: GFXBlendFactor = GFXBlendFactor.ONE; + public blendDst: GFXBlendFactor = GFXBlendFactor.ZERO; + public blendEq: GFXBlendOp = GFXBlendOp.ADD; + public blendSrcAlpha: GFXBlendFactor = GFXBlendFactor.ONE; + public blendDstAlpha: GFXBlendFactor = GFXBlendFactor.ZERO; + public blendAlphaEq: GFXBlendOp = GFXBlendOp.ADD; + public blendColorMask: GFXColorMask = GFXColorMask.ALL; - public compare(state: GFXBlendTarget): boolean { + public compare (state: GFXBlendTarget): boolean { return (this.blend === state.blend) && (this.blendSrc === state.blendSrc) && (this.blendDst === state.blendDst) && @@ -95,20 +95,20 @@ export class GFXBlendTarget { (this.blendAlphaEq === state.blendAlphaEq) && (this.blendColorMask === state.blendColorMask); } -}; +} export class GFXBlendState { - isA2C: boolean = false; - isIndepend: boolean = false; - blendColor: number[] = [0, 0, 0, 0]; - targets: GFXBlendTarget[] = [new GFXBlendTarget]; + public isA2C: boolean = false; + public isIndepend: boolean = false; + public blendColor: number[] = [0, 0, 0, 0]; + public targets: GFXBlendTarget[] = [new GFXBlendTarget()]; } export class GFXInputState { - attributes: GFXInputAttribute[] = []; -}; + public attributes: IGFXInputAttribute[] = []; +} -export interface GFXPipelineStateInfo { +export interface IGFXPipelineStateInfo { primitive: GFXPrimitiveMode; shader: GFXShader; is: GFXInputState; @@ -117,43 +117,36 @@ export interface GFXPipelineStateInfo { bs: GFXBlendState; layout: GFXPipelineLayout; renderPass: GFXRenderPass; -}; +} export abstract class GFXPipelineState { - constructor(device: GFXDevice) { - this._device = device; + public get shader (): GFXShader { + return this._shader as GFXShader; } - public abstract initialize(info: GFXPipelineStateInfo): boolean; - public abstract destroy(): void; - - public get shader() : GFXShader { - return this._shader; - } - - public get primitive() : GFXPrimitiveMode { + public get primitive (): GFXPrimitiveMode { return this._primitive; } - public get rasterizerState() : GFXRasterizerState { - return this._rs; + public get rasterizerState (): GFXRasterizerState { + return this._rs as GFXRasterizerState; } - public get depthStencilState() : GFXDepthStencilState { - return this._dss; + public get depthStencilState (): GFXDepthStencilState { + return this._dss as GFXDepthStencilState; } - public get blendState() : GFXBlendState { - return this._bs; + public get blendState (): GFXBlendState { + return this._bs as GFXBlendState; } - public get pipelineLayout() : GFXPipelineLayout { - return this._layout; + public get pipelineLayout (): GFXPipelineLayout { + return this._layout as GFXPipelineLayout; } - public get renderPass() : GFXRenderPass { - return this._renderPass; + public get renderPass (): GFXRenderPass { + return this._renderPass as GFXRenderPass; } protected _device: GFXDevice; @@ -165,4 +158,11 @@ export abstract class GFXPipelineState { protected _bs: GFXBlendState | null = null; protected _layout: GFXPipelineLayout | null = null; protected _renderPass: GFXRenderPass | null = null; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXPipelineStateInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/queue.ts b/cocos/gfx/queue.ts index 15de82f7c5..0c11f60b2a 100644 --- a/cocos/gfx/queue.ts +++ b/cocos/gfx/queue.ts @@ -1,25 +1,25 @@ -import { GFXDevice } from './device'; import { GFXCommandBuffer } from './command-buffer'; import { GFXQueueType } from './define'; +import { GFXDevice } from './device'; -export interface GFXQueueInfo { - type : GFXQueueType; -}; +export interface IGFXQueueInfo { + type: GFXQueueType; +} export abstract class GFXQueue { - constructor(device : GFXDevice) { - this._device = device; - } - - public abstract initialize(info : GFXQueueInfo) : boolean; - public abstract destroy(); - public abstract submit(cmdBuffs: GFXCommandBuffer[], fence?); - - public get type(): number { + public get type (): number { return this._type; } - protected _device : GFXDevice; - protected _type : GFXQueueType = GFXQueueType.GRAPHICS; -}; + protected _device: GFXDevice; + protected _type: GFXQueueType = GFXQueueType.GRAPHICS; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXQueueInfo): boolean; + public abstract destroy (); + public abstract submit (cmdBuffs: GFXCommandBuffer[], fence?); +} diff --git a/cocos/gfx/render-pass.ts b/cocos/gfx/render-pass.ts index ae832ee6c2..23250bb97e 100644 --- a/cocos/gfx/render-pass.ts +++ b/cocos/gfx/render-pass.ts @@ -1,56 +1,52 @@ -import { GFXFormat, GFXLoadOp, GFXStoreOp, GFXTextureLayout, GFXPipelineBindPoint } from './define'; +import { GFXFormat, GFXLoadOp, GFXPipelineBindPoint, GFXStoreOp, GFXTextureLayout } from './define'; import { GFXDevice } from './device'; -export class GFXColorAttachment -{ - format : GFXFormat = GFXFormat.UNKNOWN; - loadOp : GFXLoadOp = GFXLoadOp.CLEAR; - storeOp : GFXStoreOp = GFXStoreOp.STORE; - sampleCount : number = 1; - beginLayout : GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; - endLayout : GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; -}; +export class GFXColorAttachment { + public format: GFXFormat = GFXFormat.UNKNOWN; + public loadOp: GFXLoadOp = GFXLoadOp.CLEAR; + public storeOp: GFXStoreOp = GFXStoreOp.STORE; + public sampleCount: number = 1; + public beginLayout: GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; + public endLayout: GFXTextureLayout = GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL; +} -export class GFXDepthStencilAttachment -{ - format : GFXFormat = GFXFormat.UNKNOWN; - depthLoadOp : GFXLoadOp = GFXLoadOp.CLEAR; - depthStoreOp : GFXStoreOp = GFXStoreOp.STORE; - stencilLoadOp : GFXLoadOp = GFXLoadOp.CLEAR; - stencilStoreOp : GFXStoreOp = GFXStoreOp.STORE; - sampleCount : number = 1; - beginLayout : GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - endLayout : GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; -}; +export class GFXDepthStencilAttachment { + public format: GFXFormat = GFXFormat.UNKNOWN; + public depthLoadOp: GFXLoadOp = GFXLoadOp.CLEAR; + public depthStoreOp: GFXStoreOp = GFXStoreOp.STORE; + public stencilLoadOp: GFXLoadOp = GFXLoadOp.CLEAR; + public stencilStoreOp: GFXStoreOp = GFXStoreOp.STORE; + public sampleCount: number = 1; + public beginLayout: GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + public endLayout: GFXTextureLayout = GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL; +} -export interface GFXSubPassInfo -{ - bindPoint : GFXPipelineBindPoint; - inputs : number[]; - colors : number[]; - resolves : number[]; - depthStencil : number; - preserves : number[]; -}; +export interface IGFXSubPassInfo { + bindPoint: GFXPipelineBindPoint; + inputs: number[]; + colors: number[]; + resolves: number[]; + depthStencil: number; + preserves: number[]; +} -export interface GFXRenderPassInfo -{ - colorAttachments? : GFXColorAttachment[]; - depthStencilAttachment? : GFXDepthStencilAttachment; - //subPasses? : GFXSubPassInfo[]; -}; +export interface IGFXRenderPassInfo { + colorAttachments?: GFXColorAttachment[]; + depthStencilAttachment?: GFXDepthStencilAttachment; + // subPasses? : GFXSubPassInfo[]; +} export abstract class GFXRenderPass { - constructor(device : GFXDevice) { + protected _device: GFXDevice; + protected _colorInfos: GFXColorAttachment[] = []; + protected _depthStencilInfo: GFXDepthStencilAttachment | null = null; + + constructor (device: GFXDevice) { this._device = device; } - public abstract initialize(info : GFXRenderPassInfo) : boolean; - public abstract destroy() : void; - - protected _device : GFXDevice; - protected _colorInfos : GFXColorAttachment[] = []; - protected _depthStencilInfo : GFXDepthStencilAttachment | null = null; - //protected _subPasses : GFXSubPassInfo[] = []; -}; + public abstract initialize (info: IGFXRenderPassInfo): boolean; + public abstract destroy (): void; + // protected _subPasses : GFXSubPassInfo[] = []; +} diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index c7f8fc38d4..c1647abdf9 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -1,38 +1,38 @@ +import { GFXAddress, GFXComparisonFunc, GFXFilter } from './define'; import { GFXDevice } from './device'; -import { GFXFilter, GFXAddress, GFXComparisonFunc } from './define'; -export interface GFXSamplerInfo { - name? : string; - minFilter? : GFXFilter; - magFilter? : GFXFilter; - mipFilter? : GFXFilter; - addressU? : GFXAddress; - addressV? : GFXAddress; - addressW? : GFXAddress; - maxAnisotropy? : number; - cmpFunc? : GFXComparisonFunc; - borderColor? : number[]; - minLOD? : number; - maxLOD? : number; - mipLODBias? : number; -}; +export interface IGFXSamplerInfo { + name?: string; + minFilter?: GFXFilter; + magFilter?: GFXFilter; + mipFilter?: GFXFilter; + addressU?: GFXAddress; + addressV?: GFXAddress; + addressW?: GFXAddress; + maxAnisotropy?: number; + cmpFunc?: GFXComparisonFunc; + borderColor?: number[]; + minLOD?: number; + maxLOD?: number; + mipLODBias?: number; +} export class GFXSamplerState { - name : string = ""; - minFilter : GFXFilter = GFXFilter.LINEAR; - magFilter : GFXFilter = GFXFilter.LINEAR; - mipFilter : GFXFilter = GFXFilter.NONE; - addressU : GFXAddress = GFXAddress.WRAP; - addressV : GFXAddress = GFXAddress.WRAP; - addressW : GFXAddress = GFXAddress.WRAP; - maxAnisotropy : number = 16; - cmpFunc : GFXComparisonFunc = GFXComparisonFunc.NEVER; - borderColor : number[] = [0.0, 0.0, 0.0, 0.0]; - minLOD : number = 0; - maxLOD : number = 1000; - mipLODBias : number = 0.0; + public name: string = ''; + public minFilter: GFXFilter = GFXFilter.LINEAR; + public magFilter: GFXFilter = GFXFilter.LINEAR; + public mipFilter: GFXFilter = GFXFilter.NONE; + public addressU: GFXAddress = GFXAddress.WRAP; + public addressV: GFXAddress = GFXAddress.WRAP; + public addressW: GFXAddress = GFXAddress.WRAP; + public maxAnisotropy: number = 16; + public cmpFunc: GFXComparisonFunc = GFXComparisonFunc.NEVER; + public borderColor: number[] = [0.0, 0.0, 0.0, 0.0]; + public minLOD: number = 0; + public maxLOD: number = 1000; + public mipLODBias: number = 0.0; - public compare(state : GFXSamplerState) : boolean { + public compare (state: GFXSamplerState): boolean { return (this.minFilter === state.minFilter) && (this.magFilter === state.magFilter) && (this.mipFilter === state.mipFilter) && @@ -46,22 +46,21 @@ export class GFXSamplerState { (this.maxLOD === state.maxLOD) && (this.mipLODBias === state.mipLODBias); } -}; +} export abstract class GFXSampler { - constructor(device : GFXDevice) { - this._device = device; - this._state = new GFXSamplerState; - } - - public abstract initialize(info : GFXSamplerInfo) : boolean; - public abstract destroy() : void; - - public get state(): GFXSamplerState { + public get state (): GFXSamplerState { return this._state; } - protected _device : GFXDevice; - protected _state : GFXSamplerState; -}; + protected _device: GFXDevice; + protected _state: GFXSamplerState = new GFXSamplerState(); + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXSamplerInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index 41d2451f9c..02e21132a0 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -1,65 +1,65 @@ +import { GFXShaderType, GFXType } from './define'; import { GFXDevice } from './device'; -import { GFXType, GFXShaderType } from './define'; -export interface GFXShaderMacro { +export interface IGFXShaderMacro { macro: string; value: string; -}; +} -export interface GFXShaderStage { +export interface IGFXShaderStage { type: GFXShaderType; source: string; - macros?: GFXShaderMacro[]; -}; + macros?: IGFXShaderMacro[]; +} export class GFXUniform { - name: string = ""; - type: GFXType = GFXType.UNKNOWN; - count: number = 1; -}; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public count: number = 1; +} export class GFXUniformBlock { - binding: number = -1; - name: string = ""; - //instance : string; - members: GFXUniform[] = []; -}; + public binding: number = -1; + public name: string = ''; + // instance : string; + public members: GFXUniform[] = []; +} export class GFXUniformSampler { - binding: number = -1; - name: string = ""; - type: GFXType = GFXType.UNKNOWN; - count: number = 1; -}; + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public count: number = 1; +} -export interface GFXShaderInfo { +export interface IGFXShaderInfo { name: string; - stages: GFXShaderStage[]; - //bindings: GFXBinding[]; + stages: IGFXShaderStage[]; + // bindings: GFXBinding[]; blocks?: GFXUniformBlock[]; samplers?: GFXUniformSampler[]; -}; +} export abstract class GFXShader { - constructor(device: GFXDevice) { - this._device = device; - this._id = device.genShaderId(); - } - - public abstract initialize(info: GFXShaderInfo): boolean; - public abstract destroy(); - - public get id(): number { + public get id (): number { return this._id; } protected _device: GFXDevice; protected _id: number; - protected _name: string = ""; - protected _stages: GFXShaderStage[] = []; - //protected _bindings: GFXBinding[] = []; + protected _name: string = ''; + protected _stages: IGFXShaderStage[] = []; + // protected _bindings: GFXBinding[] = []; protected _blocks: GFXUniformBlock[] = []; // blocks are used for being compatible with single uniforms protected _samplers: GFXUniformSampler[] = []; -}; + + constructor (device: GFXDevice) { + this._device = device; + this._id = device.genShaderId(); + } + + public abstract initialize (info: IGFXShaderInfo): boolean; + public abstract destroy (); +} diff --git a/cocos/gfx/texture-view.ts b/cocos/gfx/texture-view.ts index bceeeb3d56..f6e026d82c 100644 --- a/cocos/gfx/texture-view.ts +++ b/cocos/gfx/texture-view.ts @@ -2,7 +2,7 @@ import { GFXFormat, GFXTextureViewType } from './define'; import { GFXDevice } from './device'; import { GFXTexture } from './texture'; -export interface GFXTextureViewInfo { +export interface IGFXTextureViewInfo { texture: GFXTexture; type: GFXTextureViewType; format: GFXFormat; @@ -10,42 +10,35 @@ export interface GFXTextureViewInfo { levelCount?: number; baseLayer?: number; layerCount?: number; -}; +} export abstract class GFXTextureView { - constructor(device: GFXDevice) { - this._device = device; + public get texture (): GFXTexture { + return this._texture as GFXTexture; } - public abstract initialize(info: GFXTextureViewInfo): boolean; - public abstract destroy(): void; - - public get texture(): GFXTexture { - return this._texture; - } - - public get type(): GFXTextureViewType { + public get type (): GFXTextureViewType { return this._type; } - public get format(): GFXFormat { + public get format (): GFXFormat { return this._format; } - public get baseLevel(): number { + public get baseLevel (): number { return this._baseLevel; } - public get levelCount(): number { + public get levelCount (): number { return this._levelCount; } - public get baseLayer(): number { + public get baseLayer (): number { return this._baseLayer; } - public get layerCount(): number { + public get layerCount (): number { return this._layerCount; } @@ -57,4 +50,11 @@ export abstract class GFXTextureView { protected _levelCount: number = 1; protected _baseLayer: number = 0; protected _layerCount: number = 1; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXTextureViewInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/texture.ts b/cocos/gfx/texture.ts index 92e8e1d6d0..c3969b65dc 100644 --- a/cocos/gfx/texture.ts +++ b/cocos/gfx/texture.ts @@ -1,7 +1,7 @@ -import { GFXFormat, GFXTextureType, GFXTextureUsage, GFXTextureFlags, GFXTextureUsageBit, GFXTextureFlagBit } from './define'; +import { GFXFormat, GFXTextureFlagBit, GFXTextureFlags, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit } from './define'; import { GFXDevice } from './device'; -export interface GFXTextureInfo { +export interface IGFXTextureInfo { type: GFXTextureType; usage: GFXTextureUsage; format: GFXFormat; @@ -11,58 +11,51 @@ export interface GFXTextureInfo { arrayLayer?: number; mipLevel?: number; flags?: GFXTextureFlags; -}; +} export abstract class GFXTexture { - constructor(device: GFXDevice) { - this._device = device; - } - - public abstract initialize(info: GFXTextureInfo): boolean; - public abstract destroy(): void; - - public get type(): GFXTextureType { + public get type (): GFXTextureType { return this._type; } - public get usage(): GFXTextureUsage { + public get usage (): GFXTextureUsage { return this._usage; } - public get format(): GFXFormat { + public get format (): GFXFormat { return this._format; } - public get width(): number { + public get width (): number { return this._width; } - public get height(): number { + public get height (): number { return this._height; } - public get depth(): number { + public get depth (): number { return this._depth; } - public get arrayLayer(): number { + public get arrayLayer (): number { return this._arrayLayer; } - public get mipLevel(): number { + public get mipLevel (): number { return this._mipLevel; } - public get flags(): GFXTextureFlags { + public get flags (): GFXTextureFlags { return this._flags; } - public get size(): number { + public get size (): number { return this._size; } - public get buffer(): ArrayBuffer | null { + public get buffer (): ArrayBuffer | null { return this._buffer; } @@ -78,4 +71,11 @@ export abstract class GFXTexture { protected _flags: GFXTextureFlags = GFXTextureFlagBit.NONE; protected _size: number = 0; protected _buffer: ArrayBuffer | null = null; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXTextureInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/gfx/webgl/webgl-binding-layout.ts b/cocos/gfx/webgl/webgl-binding-layout.ts index 9cabcec35f..d3d12821d2 100644 --- a/cocos/gfx/webgl/webgl-binding-layout.ts +++ b/cocos/gfx/webgl/webgl-binding-layout.ts @@ -1,19 +1,29 @@ +import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBindingLayout } from './webgl-gpu-objects'; -import { GFXBindingLayout, GFXBindingLayoutInfo, GFXBindingUnit } from '../binding-layout'; export class WebGLGFXBindingLayout extends GFXBindingLayout { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuBindingLayout (): WebGLGPUBindingLayout { + return this._gpuBindingLayout as WebGLGPUBindingLayout; + } + + private _gpuBindingLayout: WebGLGPUBindingLayout | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXBindingLayoutInfo): boolean { + public initialize (info: IGFXBindingLayoutInfo): boolean { this._bindingUnits = new Array(info.bindings.length); for (let i = 0; i < info.bindings.length; ++i) { - let binding = info.bindings[i]; + const binding = info.bindings[i]; this._bindingUnits[i] = { binding: binding.binding, type: binding.type, @@ -29,26 +39,16 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { return true; } - public destroy() { + public destroy () { if (this._gpuBindingLayout) { this.webGLDevice.emitCmdDestroyGPUBindingLayout(this._gpuBindingLayout); this._gpuBindingLayout = null; } } - public update() { + public update () { if (this._gpuBindingLayout) { this.webGLDevice.emitCmdUpdateGPUBindingLayout(this._gpuBindingLayout, this._bindingUnits); } } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuBindingLayout(): WebGLGPUBindingLayout { - return this._gpuBindingLayout; - } - - private _gpuBindingLayout: WebGLGPUBindingLayout | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 078ed87aed..14d8d4c7bb 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,22 +1,32 @@ -import { GFXBufferInfo, GFXBuffer } from '../buffer'; -import { GFXDevice } from '../device'; -import { WebGLGPUBuffer } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-device'; +import { GFXBuffer, IGFXBufferInfo } from '../buffer'; import { GFXMemoryUsageBit } from '../define'; +import { GFXDevice } from '../device'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUBuffer } from './webgl-gpu-objects'; export class WebGLGFXBuffer extends GFXBuffer { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuBuffer (): WebGLGPUBuffer { + return this._gpuBuffer as WebGLGPUBuffer; + } + + private _gpuBuffer: WebGLGPUBuffer | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXBufferInfo): boolean { + public initialize (info: IGFXBufferInfo): boolean { this._usage = info.usage; this._memUsage = info.memUsage; this._size = info.size; - if(info.stride !== undefined) { + if (info.stride !== undefined) { this._stride = info.stride; } this._stride = Math.max(this._stride, 1); @@ -26,13 +36,13 @@ export class WebGLGFXBuffer extends GFXBuffer { this._bufferView = new Uint8Array(this._buffer); } - //this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; + // this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); return true; } - public destroy() { + public destroy () { if (this._gpuBuffer) { this.webGLDevice.emitCmdDestroyGPUBuffer(this._gpuBuffer); this._gpuBuffer = null; @@ -42,22 +52,12 @@ export class WebGLGFXBuffer extends GFXBuffer { this._bufferView = null; } - public update(buffer: ArrayBuffer, offset?: number) { + public update (buffer: ArrayBuffer, offset?: number) { if (this._bufferView) { this._bufferView.set(new Uint8Array(buffer), offset); } - this.webGLDevice.emitCmdUpdateGPUBuffer(this._gpuBuffer, offset? offset : 0, buffer); + this.webGLDevice.emitCmdUpdateGPUBuffer( this._gpuBuffer as WebGLGPUBuffer, offset ? offset : 0, buffer); } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuBuffer(): WebGLGPUBuffer { - return this._gpuBuffer; - } - - private _gpuBuffer: WebGLGPUBuffer | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 2a7b30d167..f5ea380c72 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -1,12 +1,16 @@ +import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXDevice } from '../device'; -import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../command-allocator'; -import { WebGLCmdUpdateBuffer, WebGLCmdBeginRenderPass, WebGLCmdBindInputAssembler, WebGLCmdDraw, WebGLCmdBindPipelineState, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture } from './webgl-commands'; +import { WebGLCmdBeginRenderPass, WebGLCmdBindBindingLayout, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdCopyBufferToTexture, WebGLCmdDraw, WebGLCmdUpdateBuffer } from './webgl-commands'; export class WebGLGFXCommandPool { - constructor(clazz: new() => T, count: number, increase : number) { + private _frees: Array; + private _freeIdx: number = 0; + private _increase: number = 0; + + constructor (clazz: new() => T, count: number, increase: number) { this._frees = new Array(count); - for(let i = 0; i < count; ++i) { + for (let i = 0; i < count; ++i) { this._frees[i] = new clazz(); } @@ -14,50 +18,46 @@ export class WebGLGFXCommandPool { this._increase = increase; } - alloc(clazz: new() => T) : T | null { + public alloc (clazz: new() => T): T | null { if (this._freeIdx <= 0) { - let size = this._frees.length + this._increase; - let temp = this._frees; + const size = this._frees.length + this._increase; + const temp = this._frees; this._frees = new Array(size); - for(let i = 0; i < temp.length; ++i) { + for (let i = 0; i < temp.length; ++i) { this._frees[i] = temp[i]; } - for(let i = temp.length + 1; i < size; ++i) { + for (let i = temp.length + 1; i < size; ++i) { this._frees[i] = new clazz(); } this._freeIdx += (size - temp.length); } - let item = this._frees[this._freeIdx]; + const item = this._frees[this._freeIdx]; this._frees[this._freeIdx--] = null; return item; } - free(cmd : T) { + public free (cmd: T) { this._frees[++this._freeIdx] = cmd; } - - private _frees : (T|null)[]; - private _freeIdx : number = 0; - private _increase : number = 0; -}; +} export class WebGLGFXCommandAllocator extends GFXCommandAllocator { - beginRenderPassCmdPool : WebGLGFXCommandPool; - bindPipelineStateCmdPool : WebGLGFXCommandPool; - bindBindingLayoutCmdPool : WebGLGFXCommandPool; - bindInputAssemblerCmdPool : WebGLGFXCommandPool; - drawCmdPool : WebGLGFXCommandPool; - updateBufferCmdPool : WebGLGFXCommandPool; - copyBufferToTextureCmdPool : WebGLGFXCommandPool; + public beginRenderPassCmdPool: WebGLGFXCommandPool; + public bindPipelineStateCmdPool: WebGLGFXCommandPool; + public bindBindingLayoutCmdPool: WebGLGFXCommandPool; + public bindInputAssemblerCmdPool: WebGLGFXCommandPool; + public drawCmdPool: WebGLGFXCommandPool; + public updateBufferCmdPool: WebGLGFXCommandPool; + public copyBufferToTextureCmdPool: WebGLGFXCommandPool; - constructor(device : GFXDevice) { + constructor (device: GFXDevice) { super(device); this.beginRenderPassCmdPool = new WebGLGFXCommandPool(WebGLCmdBeginRenderPass, 64, 32); this.bindPipelineStateCmdPool = new WebGLGFXCommandPool(WebGLCmdBindPipelineState, 64, 32); @@ -68,12 +68,12 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { this.copyBufferToTextureCmdPool = new WebGLGFXCommandPool(WebGLCmdCopyBufferToTexture, 64, 32); } - public initialize(info: GFXCommandAllocatorInfo) : boolean { + public initialize (info: IGFXCommandAllocatorInfo): boolean { return true; } - public destroy() { + public destroy () { } -}; +} diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 73397df6a1..8aa6a42445 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,33 +1,33 @@ -import { GFXDevice } from '../device'; -import { GFXCommandBuffer, GFXCommandBufferInfo } from '../command-buffer'; -import { GFXBuffer } from '../buffer'; -import { WebGLCmdUpdateBuffer, WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdPackage, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdDraw, WebGLCmdBindBindingLayout, WebGLCmdCopyBufferToTexture, WebGLGFXBufferTextureCopy } from './webgl-commands'; -import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; -import { WebGLGFXDevice } from './webgl-device'; -import { WebGLGFXBuffer } from './webgl-buffer'; -import { GFXFramebuffer } from '../framebuffer'; -import { WebGLGFXFramebuffer } from './webgl-framebuffer'; -import { GFXInputAssembler } from '../input-assembler'; -import { WebGLGFXInputAssembler } from './webgl-input-assembler'; -import { GFXPipelineState } from '../pipeline-state'; -import { WebGLGFXPipelineState } from './webgl-pipeline-state'; import { GFXBindingLayout } from '../binding-layout'; -import { WebGLGFXBindingLayout } from './webgl-binding-layout'; +import { GFXBuffer } from '../buffer'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; +import { GFXBufferTextureCopy, GFXTextureLayout, IGFXColor, IGFXRect, IGFXViewport } from '../define'; +import { GFXDevice } from '../device'; +import { GFXFramebuffer } from '../framebuffer'; +import { GFXInputAssembler } from '../input-assembler'; +import { GFXPipelineState } from '../pipeline-state'; import { GFXTexture } from '../texture'; +import { WebGLGFXBindingLayout } from './webgl-binding-layout'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdBindBindingLayout, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdCopyBufferToTexture, WebGLCmdDraw, WebGLCmdPackage, WebGLCmdUpdateBuffer, WebGLGFXBufferTextureCopy } from './webgl-commands'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { WebGLGFXInputAssembler } from './webgl-input-assembler'; +import { WebGLGFXPipelineState } from './webgl-pipeline-state'; import { WebGLGFXTexture } from './webgl-texture'; -import { GFXColor, GFXViewport, GFXRect, GFXBufferTextureCopy, GFXTextureLayout } from '../define'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { - cmdPackage : WebGLCmdPackage = new WebGLCmdPackage; + public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); - constructor(device : GFXDevice) { + constructor (device: GFXDevice) { super(device); } - public initialize(info : GFXCommandBufferInfo) : boolean { + public initialize (info: IGFXCommandBufferInfo): boolean { - if(!info.allocator) { + if (!info.allocator) { return false; } @@ -37,25 +37,25 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { return true; } - public destroy() { - if(this._allocator) { - this.cmdPackage.clearCmds(this._allocator); + public destroy () { + if (this._allocator) { + this.cmdPackage.clearCmds( this._allocator as WebGLGFXCommandAllocator); } } - public begin() { - if(this._allocator) { - this.cmdPackage.clearCmds(this._allocator); + public begin () { + if (this._allocator) { + this.cmdPackage.clearCmds( this._allocator as WebGLGFXCommandAllocator); } } - public end() { + public end () { } - public beginRenderPass(framebuffer : GFXFramebuffer, renderArea : GFXRect, clearColors : GFXColor[], clearDepth: number, clearStencil : number) { - let cmd = (this._allocator).beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); + public beginRenderPass (framebuffer: GFXFramebuffer, renderArea: IGFXRect, clearColors: IGFXColor[], clearDepth: number, clearStencil: number) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator).beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); if (cmd) { - cmd.gpuFramebuffer = (framebuffer).gpuFramebuffer; + cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; cmd.renderArea = renderArea; cmd.clearColors = clearColors.slice(); cmd.clearStencil = clearStencil; @@ -65,42 +65,42 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public endRenderPass() { + public endRenderPass () { } - public bindPipelineState(pipelineState : GFXPipelineState) { - let cmd = (this._allocator).bindPipelineStateCmdPool.alloc(WebGLCmdBindPipelineState); + public bindPipelineState (pipelineState: GFXPipelineState) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator).bindPipelineStateCmdPool.alloc(WebGLCmdBindPipelineState); if (cmd) { - cmd.gpuPipelineState = (pipelineState).gpuPipelineState; + cmd.gpuPipelineState = ( pipelineState as WebGLGFXPipelineState).gpuPipelineState; this.cmdPackage.bindPipelineStateCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.BIND_PIPELINE_STATE); } } - public bindBindingLayout(bindingLayout : GFXBindingLayout) { - let cmd = (this._allocator).bindBindingLayoutCmdPool.alloc(WebGLCmdBindBindingLayout); + public bindBindingLayout (bindingLayout: GFXBindingLayout) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator).bindBindingLayoutCmdPool.alloc(WebGLCmdBindBindingLayout); if (cmd) { - cmd.gpuBindingLayout= (bindingLayout).gpuBindingLayout; + cmd.gpuBindingLayout = ( bindingLayout as WebGLGFXBindingLayout).gpuBindingLayout; this.cmdPackage.bindBindingLayoutCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.BIND_BINDING_LAYOUT); } } - public bindInputAssembler(inputAssembler : GFXInputAssembler) { + public bindInputAssembler (inputAssembler: GFXInputAssembler) { - let cmd = (this._allocator).bindInputAssemblerCmdPool.alloc(WebGLCmdBindInputAssembler); + const cmd = ( this._allocator as WebGLGFXCommandAllocator).bindInputAssemblerCmdPool.alloc(WebGLCmdBindInputAssembler); if (cmd) { - cmd.gpuInputAssembler = (inputAssembler).gpuInputAssembler; + cmd.gpuInputAssembler = ( inputAssembler as WebGLGFXInputAssembler).gpuInputAssembler; this.cmdPackage.bindInputAssemblerCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.BIND_INPUT_ASSEMBLER); } } - public draw(inputAssembler : GFXInputAssembler) { - let cmd = (this._allocator).drawCmdPool.alloc(WebGLCmdDraw); + public draw (inputAssembler: GFXInputAssembler) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator).drawCmdPool.alloc(WebGLCmdDraw); if (cmd) { cmd.vertexCount = inputAssembler.vertexCount; cmd.firstVertex = inputAssembler.firstVertex; @@ -116,14 +116,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public updateBuffer(buffer : GFXBuffer, data : ArrayBuffer, offset?: number) { - let gpuBuffer = (buffer).gpuBuffer; - if(gpuBuffer) { - let cmd = (this._allocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); + public updateBuffer (buffer: GFXBuffer, data: ArrayBuffer, offset?: number) { + const gpuBuffer = ( buffer as WebGLGFXBuffer).gpuBuffer; + if (gpuBuffer) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { cmd.gpuBuffer = gpuBuffer; cmd.buffer = data; - cmd.offset = (offset !== undefined? offset : 0); + cmd.offset = (offset !== undefined ? offset : 0); this.cmdPackage.updateBufferCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); @@ -131,11 +131,11 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public copyBufferToTexture(srcBuff : GFXBuffer, dstTex : GFXTexture, dstLayout: GFXTextureLayout, regions : GFXBufferTextureCopy[]) { - let gpuBuffer = (srcBuff).gpuBuffer; - let gpuTexture = (dstTex).gpuTexture; - if(gpuBuffer && gpuTexture) { - let cmd = (this._allocator).copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); + public copyBufferToTexture (srcBuff: GFXBuffer, dstTex: GFXTexture, dstLayout: GFXTextureLayout, regions: GFXBufferTextureCopy[]) { + const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; + const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; + if (gpuBuffer && gpuTexture) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator).copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); if (cmd) { cmd.gpuBuffer = gpuBuffer; cmd.gpuTexture = gpuTexture; @@ -148,10 +148,10 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public execute(cmdBuffs : GFXCommandBuffer[]) { + public execute (cmdBuffs: GFXCommandBuffer[]) { - for(let i = 0; i < cmdBuffs.length; ++i) { - let webGLCmdBuff = cmdBuffs[i]; + for (const cmdBuff of cmdBuffs) { + const webGLCmdBuff = cmdBuff as WebGLGFXCommandBuffer; this.cmdPackage.beginRenderPassCmds = this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); this.cmdPackage.bindPipelineStateCmds = this.cmdPackage.bindPipelineStateCmds.concat(webGLCmdBuff.cmdPackage.bindPipelineStateCmds); @@ -164,7 +164,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public get webGLDevice() : WebGLGFXDevice { - return this._device; + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; } -}; +} diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index a1221a7f4e..81dc054a79 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,15 +1,15 @@ -import { WebGLGPUBuffer, WebGLGPUTexture, WebGLGPUInputAssembler, WebGLGPUFramebuffer, WebGLGPUShader, WebGLGPUInput, WebGLAttrib, WebGLGPUPipelineState, WebGLGPUUniformBlock, WebGLGPUBindingLayout, WebGLGPUUniform, WebGLGPUUniformSampler } from "./webgl-gpu-objects"; -import { WebGLGFXDevice } from "./webgl-device"; -import { GFXFormatInfos, GFXFormat, WebGLEXT, GFXType, GFX_MAX_VERTEX_ATTRIBUTES, GFXFormatSize, GFXColor, GFXRect, GFXBindingType, GFXBufferTextureCopy, GFXColorMask, GFXCullMode, GFXShaderType, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXTextureFlagBit, GFXMemoryUsageBit, GFXBufferUsageBit } from "../define"; -import { WebGLGFXCommandAllocator } from "./webgl-command-allocator"; -import { WebGLTexUnit } from "./webgl-state-cache"; +import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, GFXCullMode, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, GFXMemoryUsageBit, GFXShaderType, GFXTextureFlagBit, GFXTextureLayout, GFXTextureViewType, GFXType, IGFXColor, IGFXRect, WebGLEXT} from '../define'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer, WebGLGPUInput, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniform, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; +import { IWebGLTexUnit } from './webgl-state-cache'; -function CmpF32NotEuqal(a: number, b: number): boolean { - let c = a - b; +function CmpF32NotEuqal (a: number, b: number): boolean { + const c = a - b; return (c > 0.000001 || c < -0.000001); } -function GFXFormatToWebGLType(format: GFXFormat, device: WebGLGFXDevice): GLenum { +function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenum { switch (format) { case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; @@ -112,7 +112,7 @@ function GFXFormatToWebGLType(format: GFXFormat, device: WebGLGFXDevice): GLenum } } -function GFXFormatToWebGLInternalFormat(format: GFXFormat): GLenum { +function GFXFormatToWebGLInternalFormat (format: GFXFormat): GLenum { switch (format) { case GFXFormat.A8: return WebGLRenderingContext.ALPHA; case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; @@ -146,13 +146,13 @@ function GFXFormatToWebGLInternalFormat(format: GFXFormat): GLenum { case GFXFormat.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; default: { - console.error("Unsupported GFXFormat, convert to WebGL internal format failed."); + console.error('Unsupported GFXFormat, convert to WebGL internal format failed.'); return WebGLRenderingContext.RGBA; } } } -function GFXFormatToWebGLFormat(format: GFXFormat): GLenum { +function GFXFormatToWebGLFormat (format: GFXFormat): GLenum { switch (format) { case GFXFormat.A8: return WebGLRenderingContext.ALPHA; case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; @@ -186,13 +186,13 @@ function GFXFormatToWebGLFormat(format: GFXFormat): GLenum { case GFXFormat.PVRTC_RGBA4: return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; default: { - console.error("Unsupported GFXFormat, convert to WebGL format failed."); + console.error('Unsupported GFXFormat, convert to WebGL format failed.'); return WebGLRenderingContext.RGBA; } } } -function GFXTypeToWebGLType(type: GFXType): GLenum { +function GFXTypeToWebGLType (type: GFXType): GLenum { switch (type) { case GFXType.BOOL: return WebGLRenderingContext.BOOL; case GFXType.BOOL2: return WebGLRenderingContext.BOOL_VEC2; @@ -214,13 +214,13 @@ function GFXTypeToWebGLType(type: GFXType): GLenum { case GFXType.SAMPLER2D: return WebGLRenderingContext.SAMPLER_2D; case GFXType.SAMPLER_CUBE: return WebGLRenderingContext.SAMPLER_CUBE; default: { - console.error("Unsupported GLType, convert to GL type failed."); + console.error('Unsupported GLType, convert to GL type failed.'); return GFXType.UNKNOWN; } } } -function WebGLTypeToGFXType(glType: GLenum): GFXType { +function WebGLTypeToGFXType (glType: GLenum): GFXType { switch (glType) { case WebGLRenderingContext.BOOL: return GFXType.BOOL; case WebGLRenderingContext.BOOL_VEC2: return GFXType.BOOL2; @@ -241,13 +241,13 @@ function WebGLTypeToGFXType(glType: GLenum): GFXType { case WebGLRenderingContext.SAMPLER_2D: return GFXType.SAMPLER2D; case WebGLRenderingContext.SAMPLER_CUBE: return GFXType.SAMPLER_CUBE; default: { - console.error("Unsupported GLType, convert to GFXType failed."); + console.error('Unsupported GLType, convert to GFXType failed.'); return GFXType.UNKNOWN; } } } -function WebGLGetTypeSize(glType: GLenum): GFXType { +function WebGLGetTypeSize (glType: GLenum): GFXType { switch (glType) { case WebGLRenderingContext.BOOL: return 4; case WebGLRenderingContext.BOOL_VEC2: return 8; @@ -268,13 +268,13 @@ function WebGLGetTypeSize(glType: GLenum): GFXType { case WebGLRenderingContext.SAMPLER_2D: return 4; case WebGLRenderingContext.SAMPLER_CUBE: return 4; default: { - console.error("Unsupported GLType, get type failed."); + console.error('Unsupported GLType, get type failed.'); return 0; } } } -function WebGLGetComponentCount(glType: GLenum): GFXType { +function WebGLGetComponentCount (glType: GLenum): GFXType { switch (glType) { case WebGLRenderingContext.FLOAT_MAT2: return 2; case WebGLRenderingContext.FLOAT_MAT3: return 3; @@ -341,169 +341,169 @@ export enum WebGLCmd { UPDATE_BUFFER, COPY_BUFFER_TO_TEXTURE, COUNT, -}; +} export class WebGLCmdObject { - cmdType: WebGLCmd; + public cmdType: WebGLCmd; - constructor(type: WebGLCmd) { + constructor (type: WebGLCmd) { this.cmdType = type; } -}; +} export class WebGLCmdBeginRenderPass extends WebGLCmdObject { - gpuFramebuffer: WebGLGPUFramebuffer | null = null; - renderArea: GFXRect = { x: 0, y: 0, width: 0, height: 0 }; - clearColors: GFXColor[] = []; - clearDepth: number = 1.0; - clearStencil: number = 0; + public gpuFramebuffer: WebGLGPUFramebuffer | null = null; + public renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; + public clearColors: IGFXColor[] = []; + public clearDepth: number = 1.0; + public clearStencil: number = 0; - constructor() { + constructor () { super(WebGLCmd.BEGIN_RENDER_PASS); } } export class WebGLCmdBindPipelineState extends WebGLCmdObject { - gpuPipelineState: WebGLGPUPipelineState | null = null; + public gpuPipelineState: WebGLGPUPipelineState | null = null; - constructor() { + constructor () { super(WebGLCmd.BIND_PIPELINE_STATE); } -}; +} export class WebGLCmdBindInputAssembler extends WebGLCmdObject { - gpuInputAssembler: WebGLGPUInputAssembler | null = null; + public gpuInputAssembler: WebGLGPUInputAssembler | null = null; - constructor() { + constructor () { super(WebGLCmd.BIND_INPUT_ASSEMBLER); } -}; +} export class WebGLCmdBindBindingLayout extends WebGLCmdObject { - gpuBindingLayout: WebGLGPUBindingLayout | null = null; + public gpuBindingLayout: WebGLGPUBindingLayout | null = null; - constructor() { + constructor () { super(WebGLCmd.BIND_BINDING_LAYOUT); } -}; +} export class WebGLCmdDraw extends WebGLCmdObject { - vertexCount: number = 0; - firstVertex: number = 0; + public vertexCount: number = 0; + public firstVertex: number = 0; - indexCount: number = 0; - firstIndex: number = 0; - vertexOffset: number = 0; + public indexCount: number = 0; + public firstIndex: number = 0; + public vertexOffset: number = 0; - instanceCount: number = 0; - firstInstance: number = 0; + public instanceCount: number = 0; + public firstInstance: number = 0; - constructor() { + constructor () { super(WebGLCmd.DRAW); } -}; +} export class WebGLCmdUpdateBuffer extends WebGLCmdObject { - gpuBuffer: WebGLGPUBuffer | null = null; - buffer: ArrayBuffer | null = null; - offset: number = 0; + public gpuBuffer: WebGLGPUBuffer | null = null; + public buffer: ArrayBuffer | null = null; + public offset: number = 0; - constructor() { + constructor () { super(WebGLCmd.UPDATE_BUFFER); } -}; +} export class WebGLGFXTextureSubres { - baseMipLevel: number = 0; - levelCount: number = 1; - baseArrayLayer: number = 0; - layerCount: number = 1; + public baseMipLevel: number = 0; + public levelCount: number = 1; + public baseArrayLayer: number = 0; + public layerCount: number = 1; } export class WebGLGFXBufferTextureCopy { - buffOffset: number = 0; - buffStride: number = 0; - buffTexHeight: number = 0; - texOffset: number[] = [0, 0, 0]; - texExtent: number[] = [0, 0, 0]; - texSubres: WebGLGFXTextureSubres = new WebGLGFXTextureSubres; + public buffOffset: number = 0; + public buffStride: number = 0; + public buffTexHeight: number = 0; + public texOffset: number[] = [0, 0, 0]; + public texExtent: number[] = [0, 0, 0]; + public texSubres: WebGLGFXTextureSubres = new WebGLGFXTextureSubres(); } export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { - gpuBuffer: WebGLGPUBuffer | null = null; - gpuTexture: WebGLGPUTexture | null = null; - dstLayout: GFXTextureLayout | null = null; - regions: GFXBufferTextureCopy[] = []; + public gpuBuffer: WebGLGPUBuffer | null = null; + public gpuTexture: WebGLGPUTexture | null = null; + public dstLayout: GFXTextureLayout | null = null; + public regions: GFXBufferTextureCopy[] = []; - constructor() { + constructor () { super(WebGLCmd.COPY_BUFFER_TO_TEXTURE); } -}; +} export class WebGLCmdPackage { - cmds: WebGLCmd[] = []; - beginRenderPassCmds: WebGLCmdBeginRenderPass[] = []; - bindPipelineStateCmds: WebGLCmdBindPipelineState[] = []; - bindBindingLayoutCmds: WebGLCmdBindBindingLayout[] = []; - bindInputAssemblerCmds: WebGLCmdBindInputAssembler[] = []; - drawCmds: WebGLCmdDraw[] = []; - updateBufferCmds: WebGLCmdUpdateBuffer[] = []; - copyBufferToTextureCmds: WebGLCmdCopyBufferToTexture[] = []; + public cmds: WebGLCmd[] = []; + public beginRenderPassCmds: WebGLCmdBeginRenderPass[] = []; + public bindPipelineStateCmds: WebGLCmdBindPipelineState[] = []; + public bindBindingLayoutCmds: WebGLCmdBindBindingLayout[] = []; + public bindInputAssemblerCmds: WebGLCmdBindInputAssembler[] = []; + public drawCmds: WebGLCmdDraw[] = []; + public updateBufferCmds: WebGLCmdUpdateBuffer[] = []; + public copyBufferToTextureCmds: WebGLCmdCopyBufferToTexture[] = []; - clearCmds(allocator: WebGLGFXCommandAllocator) { + public clearCmds (allocator: WebGLGFXCommandAllocator) { if (this.beginRenderPassCmds.length) { - for (let i = 0; i < this.beginRenderPassCmds.length; ++i) { - allocator.beginRenderPassCmdPool.free(this.beginRenderPassCmds[i]); + for (const beginRenderPassCmd of this.beginRenderPassCmds) { + allocator.beginRenderPassCmdPool.free(beginRenderPassCmd); } this.beginRenderPassCmds = []; } if (this.bindPipelineStateCmds.length) { - for (let i = 0; i < this.bindPipelineStateCmds.length; ++i) { - allocator.bindPipelineStateCmdPool.free(this.bindPipelineStateCmds[i]); + for (const bindPipelineStateCmd of this.bindPipelineStateCmds) { + allocator.bindPipelineStateCmdPool.free(bindPipelineStateCmd); } this.bindPipelineStateCmds = []; } if (this.bindBindingLayoutCmds.length) { - for (let i = 0; i < this.bindBindingLayoutCmds.length; ++i) { - allocator.bindBindingLayoutCmdPool.free(this.bindBindingLayoutCmds[i]); + for (const bindBindingLayoutCmd of this.bindBindingLayoutCmds) { + allocator.bindBindingLayoutCmdPool.free(bindBindingLayoutCmd); } this.bindBindingLayoutCmds = []; } if (this.bindInputAssemblerCmds.length) { - for (let i = 0; i < this.bindInputAssemblerCmds.length; ++i) { - allocator.bindInputAssemblerCmdPool.free(this.bindInputAssemblerCmds[i]); + for (const bindInputAssemblerCmd of this.bindInputAssemblerCmds) { + allocator.bindInputAssemblerCmdPool.free(bindInputAssemblerCmd); } this.bindInputAssemblerCmds = []; } if (this.drawCmds.length) { - for (let i = 0; i < this.drawCmds.length; ++i) { - allocator.drawCmdPool.free(this.drawCmds[i]); + for (const drawCmd of this.drawCmds) { + allocator.drawCmdPool.free(drawCmd); } this.drawCmds = []; } if (this.updateBufferCmds.length) { - for (let i = 0; i < this.updateBufferCmds.length; ++i) { - allocator.updateBufferCmdPool.free(this.updateBufferCmds[i]); + for (const updateBufferCmd of this.updateBufferCmds) { + allocator.updateBufferCmdPool.free(updateBufferCmd); } this.updateBufferCmds = []; } if (this.copyBufferToTextureCmds.length) { - for (let i = 0; i < this.copyBufferToTextureCmds.length; ++i) { - allocator.copyBufferToTextureCmdPool.free(this.copyBufferToTextureCmds[i]); + for (const copyBufferToTextureCmd of this.copyBufferToTextureCmds) { + allocator.copyBufferToTextureCmdPool.free(copyBufferToTextureCmd); } this.copyBufferToTextureCmds = []; } @@ -512,14 +512,14 @@ export class WebGLCmdPackage { } } -export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { +export function WebGLCmdFuncCreateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { - let gl = device.gl; + const gl = device.gl; if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { gpuBuffer.glTarget = WebGLRenderingContext.ARRAY_BUFFER; - let glBuffer = gl.createBuffer(); + const glBuffer = gl.createBuffer(); if (glBuffer) { gpuBuffer.glBuffer = glBuffer; @@ -528,7 +528,7 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - let glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); @@ -537,7 +537,7 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { gpuBuffer.glTarget = WebGLRenderingContext.ELEMENT_ARRAY_BUFFER; - let glBuffer = gl.createBuffer(); + const glBuffer = gl.createBuffer(); if (glBuffer) { gpuBuffer.glBuffer = glBuffer; @@ -546,14 +546,14 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - let glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); device.stateCache.glElementArrayBuffer = 0; } } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { - //console.error("WebGL 1.0 doesn't support uniform buffer."); + // console.error("WebGL 1.0 doesn't support uniform buffer."); gpuBuffer.glTarget = WebGLRenderingContext.NONE; if (gpuBuffer.buffer) { @@ -565,26 +565,26 @@ export function WebGLCmdFuncCreateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) { gpuBuffer.glTarget = WebGLRenderingContext.NONE; } else { - console.error("Unsupported GFXBufferType, create buffer failed."); + console.error('Unsupported GFXBufferType, create buffer failed.'); gpuBuffer.glTarget = WebGLRenderingContext.NONE; } } -export function WebGLCmdFuncDestroyBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { +export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { if (gpuBuffer.glBuffer > 0) { device.gl.deleteBuffer(gpuBuffer.glBuffer); gpuBuffer.glBuffer = 0; } } -export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { +export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { if (gpuBuffer.viewF32 && buffer) { gpuBuffer.viewF32.set(new Float32Array(buffer), offset); } } else { - let gl = device.gl; + const gl = device.gl; switch (gpuBuffer.glTarget) { case WebGLRenderingContext.ARRAY_BUFFER: { @@ -604,15 +604,15 @@ export function WebGLCmdFuncUpdateBuffer(device: WebGLGFXDevice, gpuBuffer: WebG break; } default: { - console.error("Unsupported GFXBufferType, update buffer failed."); + console.error('Unsupported GFXBufferType, update buffer failed.'); } } } } -export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { +export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { - let gl = device.gl; + const gl = device.gl; gpuTexture.glInternelFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format); gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format); @@ -624,10 +624,10 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We gpuTexture.viewType = GFXTextureViewType.TV2D; gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; - let glTexture = gl.createTexture(); + const glTexture = gl.createTexture(); if (glTexture) { gpuTexture.glTexture = glTexture; - let glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); @@ -644,7 +644,7 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We h = Math.max(1, h >> 1); } } else { - let view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; + const view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; for (let i = 0; i < gpuTexture.mipLevel; ++i) { gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_2D, i, gpuTexture.glInternelFmt, w, h, 0, view); w = Math.max(1, w >> 1); @@ -660,10 +660,10 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We gpuTexture.viewType = GFXTextureViewType.CUBE; gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_CUBE_MAP; - let glTexture = gl.createTexture(); + const glTexture = gl.createTexture(); if (glTexture) { gpuTexture.glTexture = glTexture; - let glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + const glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); @@ -681,7 +681,7 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We } } } else { - let view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; + const view: ArrayBufferView = { buffer: new ArrayBuffer(0), byteLength: 0, byteOffset: 0 }; for (let f = 0; f < 6; ++f) { let w = gpuTexture.width; @@ -698,27 +698,27 @@ export function WebGLCmdFuncCreateTexture(device: WebGLGFXDevice, gpuTexture: We break; } default: { - console.error("Unsupported GFXTextureType, create texture failed."); + console.error('Unsupported GFXTextureType, create texture failed.'); gpuTexture.viewType = GFXTextureViewType.TV2D; gpuTexture.glTarget = WebGLRenderingContext.TEXTURE_2D; } } } -export function WebGLCmdFuncDestroyTexture(device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { +export function WebGLCmdFuncDestroyTexture (device: WebGLGFXDevice, gpuTexture: WebGLGPUTexture) { if (gpuTexture.glTexture > 0) { device.gl.deleteTexture(gpuTexture.glTexture); gpuTexture.glTexture = 0; } } -export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { +export function WebGLCmdFuncCreateFramebuffer (device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { if (!gpuFramebuffer.isOffscreen) { - let gl = device.gl; + const gl = device.gl; - let glFramebuffer = gl.createFramebuffer(); + const glFramebuffer = gl.createFramebuffer(); if (glFramebuffer) { gpuFramebuffer.glFramebuffer = glFramebuffer; @@ -729,7 +729,7 @@ export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebu for (let i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) { - let gpuColorView = gpuFramebuffer.gpuColorViews[i]; + const gpuColorView = gpuFramebuffer.gpuColorViews[i]; if (gpuColorView) { gl.framebufferTexture2D( WebGLRenderingContext.FRAMEBUFFER, @@ -742,7 +742,7 @@ export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebu if (gpuFramebuffer.gpuDepthStencilView) { - let glAttachment = GFXFormatInfos[gpuFramebuffer.gpuDepthStencilView.format].hasStencil ? + const glAttachment = GFXFormatInfos[gpuFramebuffer.gpuDepthStencilView.format].hasStencil ? WebGLRenderingContext.DEPTH_STENCIL_ATTACHMENT : WebGLRenderingContext.DEPTH_ATTACHMENT; gl.framebufferTexture2D( @@ -753,74 +753,72 @@ export function WebGLCmdFuncCreateFramebuffer(device: WebGLGFXDevice, gpuFramebu gpuFramebuffer.gpuDepthStencilView.baseLevel); } - let status = gl.checkFramebufferStatus(WebGLRenderingContext.FRAMEBUFFER); + const status = gl.checkFramebufferStatus(WebGLRenderingContext.FRAMEBUFFER); if (status !== WebGLRenderingContext.FRAMEBUFFER_COMPLETE) { switch (status) { case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: { - console.error("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT'); break; } case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: { - console.error("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'); break; } case WebGLRenderingContext.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: { - console.error("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS'); break; } case WebGLRenderingContext.FRAMEBUFFER_UNSUPPORTED: { - console.error("glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); + console.error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED'); break; } - default: ; + default: } } } } } -export function WebGLCmdFuncDestroyFramebuffer(device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { +export function WebGLCmdFuncDestroyFramebuffer (device: WebGLGFXDevice, gpuFramebuffer: WebGLGPUFramebuffer) { if (gpuFramebuffer.glFramebuffer > 0) { device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer); gpuFramebuffer.glFramebuffer = 0; } } -export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { - let gl = device.gl; +export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { + const gl = device.gl; - for (let i = 0; i < gpuShader.gpuStages.length; ++i) { - let gpuStage = gpuShader.gpuStages[i]; + for (const gpuStage of gpuShader.gpuStages) { let glShaderType: GLenum = 0; - let shaderTypeStr = ""; + let shaderTypeStr = ''; switch (gpuStage.type) { case GFXShaderType.VERTEX: { - shaderTypeStr = "VertexShader"; + shaderTypeStr = 'VertexShader'; glShaderType = WebGLRenderingContext.VERTEX_SHADER; break; } case GFXShaderType.FRAGMENT: { - shaderTypeStr = "FragmentShader"; + shaderTypeStr = 'FragmentShader'; glShaderType = WebGLRenderingContext.FRAGMENT_SHADER; break; } default: { - console.error("Unsupported GFXShaderType."); + console.error('Unsupported GFXShaderType.'); return; } } - let glShader = gl.createShader(glShaderType); + const glShader = gl.createShader(glShaderType); if (glShader) { gpuStage.glShader = glShader; gl.shaderSource(gpuStage.glShader, gpuStage.source); gl.compileShader(gpuStage.glShader); - var isSuccess = gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS); - if (!isSuccess) { - console.error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed."); + if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) { + console.error(shaderTypeStr + ' in \'' + gpuShader.name + '\' compilation failed.'); console.error(gpuStage.source); console.error(gl.getShaderInfoLog(gpuStage.glShader)); @@ -830,28 +828,24 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } } - let glProgram = gl.createProgram(); + const glProgram = gl.createProgram(); if (glProgram) { gpuShader.glProgram = glProgram; // link program - for (let i = 0; i < gpuShader.gpuStages.length; ++i) { - let gpuStage = gpuShader.gpuStages[i]; - + for (const gpuStage of gpuShader.gpuStages) { gl.attachShader(gpuShader.glProgram, gpuStage.glShader); } } gl.linkProgram(gpuShader.glProgram); - var isSuccess = gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS); - if (isSuccess) { - console.info("Shader '" + gpuShader.name + "' compilation successed."); + if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { + console.info('Shader \'' + gpuShader.name + '\' compilation successed.'); } else { - console.error("Failed to link shader '" + gpuShader.name + "'."); + console.error('Failed to link shader \'' + gpuShader.name + '\'.'); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); - for (let i = 0; i < gpuShader.gpuStages.length; ++i) { - let gpuStage = gpuShader.gpuStages[i]; + for (const gpuStage of gpuShader.gpuStages) { if (gpuStage.glShader > 0) { gl.deleteShader(gpuStage.glShader); gpuStage.glShader = 0; @@ -860,34 +854,34 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // parse inputs - let activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); + const activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES); gpuShader.glInputs = new Array(activeAttribCount); for (let i = 0; i < activeAttribCount; ++i) { - let attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i); + const attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i); if (attribInfo) { let varName: string; - let nameOffset = attribInfo.name.indexOf('['); + const nameOffset = attribInfo.name.indexOf('['); if (nameOffset !== -1) { varName = attribInfo.name.substr(0, nameOffset); } else { varName = attribInfo.name; } - let glLoc = gl.getAttribLocation(gpuShader.glProgram, varName); - let type = WebGLTypeToGFXType(attribInfo.type); - let stride = WebGLGetTypeSize(attribInfo.type); + const glLoc = gl.getAttribLocation(gpuShader.glProgram, varName); + const type = WebGLTypeToGFXType(attribInfo.type); + const stride = WebGLGetTypeSize(attribInfo.type); gpuShader.glInputs[i] = { binding: glLoc, name: varName, - type: type, - stride: stride, + type, + stride, count: attribInfo.size, size: stride * attribInfo.size, glType: attribInfo.type, - glLoc: glLoc, + glLoc, }; } } @@ -896,9 +890,9 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG if (gpuShader.blocks.length > 0) { gpuShader.glBlocks = new Array(gpuShader.blocks.length); for (let i = 0; i < gpuShader.blocks.length; ++i) { - let block = gpuShader.blocks[i]; + const block = gpuShader.blocks[i]; - let glBlock: WebGLGPUUniformBlock = { + const glBlock: WebGLGPUUniformBlock = { binding: block.binding, name: block.name, size: 0, @@ -910,24 +904,24 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG gpuShader.glBlocks[i] = glBlock; for (let u = 0; u < block.members.length; ++u) { - let uniform = block.members[u]; - let glType = GFXTypeToWebGLType(uniform.type); - let stride = WebGLGetTypeSize(glType); - let size = stride * uniform.count; + const uniform = block.members[u]; + const glType = GFXTypeToWebGLType(uniform.type); + const stride = WebGLGetTypeSize(glType); + const size = stride * uniform.count; glBlock.glUniforms[u] = { binding: -1, name: uniform.name, type: uniform.type, - stride: stride, + stride, count: uniform.count, - size: size, + size, offset: glBlock.size, - glType: glType, + glType, glLoc: -1, view: null, - } + }; glBlock.size += size; } @@ -941,7 +935,7 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG gpuShader.glSamplers = new Array(gpuShader.samplers.length); for (let i = 0; i < gpuShader.samplers.length; ++i) { - let sampler = gpuShader.samplers[i]; + const sampler = gpuShader.samplers[i]; gpuShader.glSamplers[i] = { binding: sampler.binding, name: sampler.name, @@ -949,47 +943,44 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG units: [], glType: GFXTypeToWebGLType(sampler.type), glLoc: -1, - } + }; } } // parse uniforms - let activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS); + const activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS); let unitIdx = 0; for (let i = 0; i < activeUniformCount; ++i) { - let uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); + const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); if (uniformInfo) { - let glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); + const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name); if (glLoc) { let varName: string; - let nameOffset = uniformInfo.name.indexOf('['); + const nameOffset = uniformInfo.name.indexOf('['); if (nameOffset !== -1) { varName = uniformInfo.name.substr(0, nameOffset); } else { varName = uniformInfo.name; } - let isSampler = (uniformInfo.type === WebGLRenderingContext.SAMPLER_2D) || + const isSampler = (uniformInfo.type === WebGLRenderingContext.SAMPLER_2D) || (uniformInfo.type === WebGLRenderingContext.SAMPLER_CUBE); if (!isSampler) { - //let stride = WebGLGetTypeSize(info.type); + // let stride = WebGLGetTypeSize(info.type); // build uniform block mapping - for (let b = 0; b < gpuShader.glBlocks.length; ++b) { + for (const glBlock of gpuShader.glBlocks) { - let glBlock = gpuShader.glBlocks[b]; - - for (let u = 0; u < glBlock.glUniforms.length; ++u) { - let glUniform = glBlock.glUniforms[u]; + for (const glUniform of glBlock.glUniforms) { if (glUniform.name === varName) { - //let varSize = stride * info.size; + // let varSize = stride * info.size; glUniform.glLoc = glLoc; - //let count = glUniform.size / 4; - //glUniform.view = new Float32Array(glBlock.buffer, glUniform.offset, count); + // let count = glUniform.size / 4; + // glUniform.view = new Float32Array(glBlock.buffer, glUniform.offset, count); switch (glUniform.glType) { case WebGLRenderingContext.BOOL: @@ -1000,13 +991,13 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG case WebGLRenderingContext.INT_VEC3: case WebGLRenderingContext.INT_VEC2: case WebGLRenderingContext.INT_VEC4: { - let count = glUniform.size / 4; - glUniform.view = new Int32Array(glBlock.buffer, glUniform.offset, count); + const count = glUniform.size / 4; + glUniform.view = new Int32Array(glBlock.buffer as ArrayBuffer, glUniform.offset, count); break; } default: { - let count = glUniform.size / 4; - glUniform.view = new Float32Array(glBlock.buffer, glUniform.offset, count); + const count = glUniform.size / 4; + glUniform.view = new Float32Array(glBlock.buffer as ArrayBuffer, glUniform.offset, count); } } @@ -1016,10 +1007,9 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // for } else { - for (let s = 0; s < gpuShader.glSamplers.length; ++s) { - let glSampler = gpuShader.glSamplers[s]; + for (const glSampler of gpuShader.glSamplers) { if (glSampler.name === varName) { - //let varSize = stride * uniformInfo.size; + // let varSize = stride * uniformInfo.size; for (let t = 0; t < uniformInfo.size; ++t) { glSampler.units.push(unitIdx + t); @@ -1038,11 +1028,9 @@ export function WebGLCmdFuncCreateShader(device: WebGLGFXDevice, gpuShader: WebG } // for } -export function WebGLCmdFuncDestroyShader(device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { - - for (let i = 0; i < gpuShader.gpuStages.length; ++i) { - let gpuStage = gpuShader.gpuStages[i]; +export function WebGLCmdFuncDestroyShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { + for (const gpuStage of gpuShader.gpuStages) { if (gpuStage.glShader > 0) { device.gl.deleteShader(gpuStage.glShader); gpuStage.glShader = 0; @@ -1055,28 +1043,28 @@ export function WebGLCmdFuncDestroyShader(device: WebGLGFXDevice, gpuShader: Web } } -export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { +export function WebGLCmdFuncCreateInputAssember (device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length); - let offsets = [0, 0, 0, 0, 0, 0, 0, 0]; + const offsets = [0, 0, 0, 0, 0, 0, 0, 0]; for (let i = 0; i < gpuInputAssembler.attributes.length; ++i) { - let attrib = gpuInputAssembler.attributes[i]; + const attrib = gpuInputAssembler.attributes[i]; - let stream = attrib.stream !== undefined ? attrib.stream : 0; - //if (stream < gpuInputAssembler.gpuVertexBuffers.length) { + const stream = attrib.stream !== undefined ? attrib.stream : 0; + // if (stream < gpuInputAssembler.gpuVertexBuffers.length) { - let gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; + const gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream]; - let glType = GFXFormatToWebGLType(attrib.format, device); - let size = GFXFormatInfos[attrib.format].size; + const glType = GFXFormatToWebGLType(attrib.format, device); + const size = GFXFormatInfos[attrib.format].size; gpuInputAssembler.glAttribs[i] = { name: attrib.name, glBuffer: gpuBuffer.glBuffer, - glType: glType, - size: size, + glType, + size, count: GFXFormatInfos[attrib.format].count, stride: gpuBuffer.stride, componentCount: WebGLGetComponentCount(glType), @@ -1089,31 +1077,30 @@ export function WebGLCmdFuncCreateInputAssember(device: WebGLGFXDevice, gpuInput } } -export function WebGLCmdFuncDestroyInputAssembler(device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { +export function WebGLCmdFuncDestroyInputAssembler (device: WebGLGFXDevice, gpuInputAssembler: WebGLGPUInputAssembler) { } -export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { +export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { - let gl = device.gl; - let cmdIds = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 + const gl = device.gl; + const cmdIds = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 let gpuShader: WebGLGPUShader | null = null; let gpuInputAssembler: WebGLGPUInputAssembler | null = null; let glPrimitive = WebGLRenderingContext.TRIANGLES; - for (let i = 0; i < cmdPackage.cmds.length; ++i) { - let cmd = cmdPackage.cmds[i]; - let cmdId = cmdIds[cmd]++; + for (const cmd of cmdPackage.cmds) { + const cmdId = cmdIds[cmd]++; - switch (cmdPackage.cmds[i]) { + switch (cmd) { case WebGLCmd.BEGIN_RENDER_PASS: { - let cmd0 = cmdPackage.beginRenderPassCmds[cmdId]; + const cmd0 = cmdPackage.beginRenderPassCmds[cmdId]; let clears: GLbitfield = 0; if (cmd0.gpuFramebuffer) { if (device.stateCache.glFramebuffer !== cmd0.gpuFramebuffer.glFramebuffer) { - let glFBO = (cmd0.gpuFramebuffer.glFramebuffer !== 0 ? cmd0.gpuFramebuffer.glFramebuffer : null); + const glFBO = (cmd0.gpuFramebuffer.glFramebuffer !== 0 ? cmd0.gpuFramebuffer.glFramebuffer : null); gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, glFBO); device.stateCache.glFramebuffer = cmd0.gpuFramebuffer.glFramebuffer; } @@ -1144,13 +1131,13 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG device.stateCache.scissorRect.height = cmd0.renderArea.height; } - let curGPURenderPass = cmd0.gpuFramebuffer.gpuRenderPass; + const curGPURenderPass = cmd0.gpuFramebuffer.gpuRenderPass; - let invalidateAttachments: GLenum[] = [0, 0, 0, 0]; + const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; let numInvalidAttach = 0; if (curGPURenderPass.colorAttachments.length > 0) { - let colorAttachment = curGPURenderPass.colorAttachments[0]; + const colorAttachment = curGPURenderPass.colorAttachments[0]; if (colorAttachment.format !== GFXFormat.UNKNOWN) { switch (colorAttachment.loadOp) { @@ -1161,7 +1148,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.colorMask(true, true, true, true); } - let clearColor = cmd0.clearColors[0]; + const clearColor = cmd0.clearColors[0]; gl.clearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); clears |= WebGLRenderingContext.COLOR_BUFFER_BIT; @@ -1172,7 +1159,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.COLOR_ATTACHMENT0; break; } - default: ; + default: } } } // if (curGPURenderPass) @@ -1199,7 +1186,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.DEPTH_ATTACHMENT; break; } - default: ; + default: } if (GFXFormatInfos[curGPURenderPass.depthStencilAttachment.format].hasStencil) { @@ -1225,7 +1212,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG invalidateAttachments[numInvalidAttach++] = WebGLRenderingContext.STENCIL_ATTACHMENT; break; } - default: ; + default: } } } @@ -1244,12 +1231,12 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG // restore states if (clears & WebGLRenderingContext.COLOR_BUFFER_BIT) { - let colorMask = device.stateCache.bs.targets[0].blendColorMask; + const colorMask = device.stateCache.bs.targets[0].blendColorMask; if (colorMask !== GFXColorMask.ALL) { - let r = (colorMask & GFXColorMask.R) != GFXColorMask.NONE; - let g = (colorMask & GFXColorMask.G) != GFXColorMask.NONE; - let b = (colorMask & GFXColorMask.B) != GFXColorMask.NONE; - let a = (colorMask & GFXColorMask.A) != GFXColorMask.NONE; + const r = (colorMask & GFXColorMask.R) !== GFXColorMask.NONE; + const g = (colorMask & GFXColorMask.G) !== GFXColorMask.NONE; + const b = (colorMask & GFXColorMask.B) !== GFXColorMask.NONE; + const a = (colorMask & GFXColorMask.A) !== GFXColorMask.NONE; gl.colorMask(r, g, b, a); } } @@ -1279,14 +1266,14 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLCmd.BIND_PIPELINE_STATE: { - let cmd2 = cmdPackage.bindPipelineStateCmds[cmdId]; + const cmd2 = cmdPackage.bindPipelineStateCmds[cmdId]; if (cmd2.gpuPipelineState) { glPrimitive = cmd2.gpuPipelineState.glPrimitive; if (cmd2.gpuPipelineState.gpuShader) { - let glProgram = cmd2.gpuPipelineState.gpuShader.glProgram; + const glProgram = cmd2.gpuPipelineState.gpuShader.glProgram; if (device.stateCache.glProgram !== glProgram) { gl.useProgram(glProgram); device.stateCache.glProgram = glProgram; @@ -1296,7 +1283,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // rasterizer state - let rs = cmd2.gpuPipelineState.rs; + const rs = cmd2.gpuPipelineState.rs; if (rs) { if (device.stateCache.rs.cullMode !== rs.cullMode) { @@ -1315,7 +1302,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG gl.cullFace(WebGLRenderingContext.BACK); break; } - default: ; + default: } device.stateCache.rs.cullMode = rs.cullMode; @@ -1343,7 +1330,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // rasterizater state // depth-stencil state - let dss = cmd2.gpuPipelineState.dss; + const dss = cmd2.gpuPipelineState.dss; if (dss) { if (device.stateCache.dss.depthTest !== dss.depthTest) { @@ -1450,7 +1437,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // depth-stencil state // blend state - let bs = cmd2.gpuPipelineState.bs; + const bs = cmd2.gpuPipelineState.bs; if (bs) { if (device.stateCache.bs.isA2C !== bs.isA2C) { @@ -1475,8 +1462,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG device.stateCache.bs.blendColor[3] = bs.blendColor[3]; } - let target0 = bs.targets[0]; - let catchTarget0 = device.stateCache.bs.targets[0]; + const target0 = bs.targets[0]; + const catchTarget0 = device.stateCache.bs.targets[0]; if (catchTarget0.blend !== target0.blend) { if (target0.blend) { @@ -1530,10 +1517,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLCmd.BIND_BINDING_LAYOUT: { - let cmd3 = cmdPackage.bindBindingLayoutCmds[cmdId]; + const cmd3 = cmdPackage.bindBindingLayoutCmds[cmdId]; if (cmd3.gpuBindingLayout && gpuShader) { - for (let n = 0; n < cmd3.gpuBindingLayout.gpuBindings.length; ++n) { - let gpuBinding = cmd3.gpuBindingLayout.gpuBindings[n]; + for (const gpuBinding of cmd3.gpuBindingLayout.gpuBindings) { switch (gpuBinding.type) { case GFXBindingType.UNIFORM_BUFFER: { @@ -1542,18 +1528,17 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let glBlock: WebGLGPUUniformBlock | null = null; - for (let b = 0; b < gpuShader.glBlocks.length; ++b) { - if (gpuShader.glBlocks[b].binding === gpuBinding.binding) { - glBlock = gpuShader.glBlocks[b]; + for (const block of gpuShader.glBlocks) { + if (block.binding === gpuBinding.binding) { + glBlock = block; break; } } if (glBlock && gpuBinding.gpuBuffer.viewF32) { - let vf32 = gpuBinding.gpuBuffer.viewF32; + const vf32 = gpuBinding.gpuBuffer.viewF32; - for (let u = 0; u < glBlock.glUniforms.length; ++u) { - let glUniform = glBlock.glUniforms[u]; + for (const glUniform of glBlock.glUniforms) { if (glUniform.glLoc && glUniform.view) { let offset = glUniform.offset / 4; @@ -1563,9 +1548,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.INT: { for (let m = 0; m < glUniform.count; ++m, ++offset) { if (vf32[offset] !== glUniform.view[m]) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); - gl.uniform1iv(glUniform.glLoc, glUniform.view); + gl.uniform1iv(glUniform.glLoc, glUniform.view as Int32Array); glUniform.view[m] = vf32[offset]; break; } @@ -1575,13 +1560,13 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { for (let m = 0; m < glUniform.count; ++m, offset += 2) { - let idx = 2 * m; + const idx = 2 * m; if (vf32[offset] !== glUniform.view[idx] || vf32[offset + 1] !== glUniform.view[idx + 1]) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); - gl.uniform2iv(glUniform.glLoc, glUniform.view); + gl.uniform2iv(glUniform.glLoc, glUniform.view as Int32Array); break; } } @@ -1590,14 +1575,14 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { for (let m = 0; m < glUniform.count; ++m, offset += 3) { - let idx = 3 * m; + const idx = 3 * m; if (vf32[offset] !== glUniform.view[idx] || vf32[offset + 1] !== glUniform.view[idx + 1] || vf32[offset + 2] !== glUniform.view[idx + 2]) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); - gl.uniform3iv(glUniform.glLoc, glUniform.view); + gl.uniform3iv(glUniform.glLoc, glUniform.view as Int32Array); break; } } @@ -1606,15 +1591,15 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG case WebGLRenderingContext.BOOL_VEC4: case WebGLRenderingContext.INT_VEC4: { for (let m = 0; m < glUniform.count; ++m, offset += 4) { - let idx = 4 * m; + const idx = 4 * m; if (vf32[offset] !== glUniform.view[idx] || vf32[offset + 1] !== glUniform.view[idx + 1] || vf32[offset + 2] !== glUniform.view[idx + 2] || vf32[offset + 3] !== glUniform.view[idx + 3]) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniform4iv(glUniform.glLoc, glUniform.view); + gl.uniform4iv(glUniform.glLoc, glUniform.view as Int32Array); break; } } @@ -1622,12 +1607,12 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT: { for (let m = 0; m < glUniform.count; ++m, ++offset) { - let c: number = 0; - + const c: number = 0; + if (CmpF32NotEuqal(vf32[offset], glUniform.view[m])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); - gl.uniform1fv(glUniform.glLoc, glUniform.view); + gl.uniform1fv(glUniform.glLoc, glUniform.view as Float32Array); break; } } @@ -1635,13 +1620,13 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT_VEC2: { for (let m = 0; m < glUniform.count; ++m, offset += 2) { - let idx = 2 * m; + const idx = 2 * m; if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); - gl.uniform2fv(glUniform.glLoc, glUniform.view); + gl.uniform2fv(glUniform.glLoc, glUniform.view as Float32Array); break; } } @@ -1649,32 +1634,32 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT_VEC3: { for (let m = 0; m < glUniform.count; ++m, offset += 3) { - let idx = 3 * m; + const idx = 3 * m; if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); - gl.uniform3fv(glUniform.glLoc, glUniform.view); + gl.uniform3fv(glUniform.glLoc, glUniform.view as Float32Array); break; } - ; + } break; } case WebGLRenderingContext.FLOAT_VEC4: { for (let m = 0; m < glUniform.count; ++m, offset += 4) { - let idx = 4 * m; + const idx = 4 * m; if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniform4fv(glUniform.glLoc, glUniform.view); + gl.uniform4fv(glUniform.glLoc, glUniform.view as Float32Array); break; } } @@ -1682,15 +1667,15 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT_MAT2: { for (let m = 0; m < glUniform.count; ++m, offset += 4) { - let idx = 4 * m; + const idx = 4 * m; if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.view); + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.view as Float32Array); break; } } @@ -1698,7 +1683,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT_MAT3: { for (let m = 0; m < glUniform.count; ++m, offset += 9) { - let idx = 9 * m; + const idx = 9 * m; if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || @@ -1709,9 +1694,9 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG CmpF32NotEuqal(vf32[offset + 7], glUniform.view[idx + 7]) || CmpF32NotEuqal(vf32[offset + 8], glUniform.view[idx + 8])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 9 * glUniform.count)); - gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.view); + gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.view as Float32Array); break; } } @@ -1719,7 +1704,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } case WebGLRenderingContext.FLOAT_MAT4: { for (let m = 0; m < glUniform.count; ++m, offset += 16) { - let idx = 16 * m; + const idx = 16 * m; if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || @@ -1738,15 +1723,15 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG CmpF32NotEuqal(vf32[offset + 14], glUniform.view[idx + 14]) || CmpF32NotEuqal(vf32[offset + 15], glUniform.view[idx + 15])) { - let begin = glUniform.offset / 4; + const begin = glUniform.offset / 4; glUniform.view.set(vf32.subarray(begin, begin + 16 * glUniform.count)); - gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.view); + gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.view as Float32Array); break; } } break; } - default: ; + default: } } // if } @@ -1761,25 +1746,24 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG let glSampler: WebGLGPUUniformSampler | null = null; - for (let s = 0; s < gpuShader.glSamplers.length; ++s) { - if (gpuShader.glSamplers[s].binding === gpuBinding.binding) { - glSampler = gpuShader.glSamplers[s]; + for (const sampler of gpuShader.glSamplers) { + if (sampler.binding === gpuBinding.binding) { + glSampler = sampler; break; } } if (glSampler) { - let gpuTexture = gpuBinding.gpuTexView.gpuTexture; + const gpuTexture = gpuBinding.gpuTexView.gpuTexture; - for (let u = 0; u < glSampler.units.length; ++u) { + for (const texUnit of glSampler.units) { - let texUnit = glSampler.units[u]; if (device.stateCache.texUnit !== texUnit) { gl.activeTexture(WebGLRenderingContext.TEXTURE0 + texUnit); - device.stateCache.texUnit == texUnit; + device.stateCache.texUnit = texUnit; } - let glTexUnit: WebGLTexUnit | null = null; + let glTexUnit: IWebGLTexUnit | null = null; switch (glSampler.glType) { case WebGLRenderingContext.SAMPLER_2D: { @@ -1800,12 +1784,12 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } default: { - console.error("Unsupported GL Texture type."); + console.error('Unsupported GL Texture type.'); } } if (glTexUnit) { - let gpuSampler = gpuBinding.gpuSampler; + const gpuSampler = gpuBinding.gpuSampler; if (glTexUnit.minFilter !== gpuSampler.glMinFilter) { gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuSampler.glMinFilter); @@ -1847,25 +1831,24 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLCmd.BIND_INPUT_ASSEMBLER: { - let cmd4 = cmdPackage.bindInputAssemblerCmds[cmdId]; + const cmd4 = cmdPackage.bindInputAssemblerCmds[cmdId]; gpuInputAssembler = cmd4.gpuInputAssembler; break; } case WebGLCmd.DRAW: { - let cmd5: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; + const cmd5: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; if (gpuInputAssembler && gpuShader) { for (let a = 0; a < device.maxVertexAttributes; ++a) { device.stateCache.glCurrentAttribLocs[a] = false; } - for (let n = 0; n < gpuShader.glInputs.length; ++n) { - let glInput = gpuShader.glInputs[n]; + for (const glInput of gpuShader.glInputs) { let glAttrib: WebGLAttrib | null = null; - for (let a = 0; a < gpuInputAssembler.glAttribs.length; ++a) { - if (gpuInputAssembler.glAttribs[a].name === glInput.name) { - glAttrib = gpuInputAssembler.glAttribs[a]; + for (const attrib of gpuInputAssembler.glAttribs) { + if (attrib.name === glInput.name) { + glAttrib = attrib; break; } } @@ -1877,8 +1860,8 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } for (let c = 0; c < glAttrib.componentCount; ++c) { - let glLoc = glInput.glLoc + c; - let attribOffset = glAttrib.offset + glAttrib.size * c; + const glLoc = glInput.glLoc + c; + const attribOffset = glAttrib.offset + glAttrib.size * c; if (!device.stateCache.glEnabledAttribLocs[glLoc] && glLoc >= 0) { gl.enableVertexAttribArray(glLoc); @@ -1892,14 +1875,14 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // if if (gpuInputAssembler.gpuIndexBuffer && cmd5.indexCount > 0) { - let gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - let offset = cmd5.firstIndex * gpuBuffer.stride; + const offset = cmd5.firstIndex * gpuBuffer.stride; gl.drawElements(glPrimitive, cmd5.indexCount, gpuInputAssembler.glIndexType, offset); } else { gl.drawArrays(glPrimitive, cmd5.firstVertex, cmd5.vertexCount); @@ -1915,7 +1898,7 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG break; } case WebGLCmd.UPDATE_BUFFER: { - let cmd6 = cmdPackage.updateBufferCmds[cmdId]; + const cmd6 = cmdPackage.updateBufferCmds[cmdId]; if (cmd6.gpuBuffer) { if (cmd6.buffer && cmd6.gpuBuffer.viewUI8) { @@ -1945,14 +1928,14 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } break; } - default: ; + default: } } break; } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { - let cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; + const cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; if (cmd7.gpuBuffer && cmd7.gpuBuffer.viewUI8 && cmd7.gpuTexture) { WebGLCmdFuncCopyBufferToTexture(device, cmd7.gpuBuffer.viewUI8, cmd7.gpuTexture, cmd7.regions); } @@ -1963,34 +1946,33 @@ export function WebGLCmdFuncExecuteCmds(device: WebGLGFXDevice, cmdPackage: WebG } // for } -export function WebGLCmdFuncCopyBufferToTexture( +export function WebGLCmdFuncCopyBufferToTexture ( device: WebGLGFXDevice, bufferView: Uint8Array, gpuTexture: WebGLGPUTexture, regions: GFXBufferTextureCopy[]) { - let gl = device.gl; + const gl = device.gl; switch (gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { - let glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; + const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; } - let isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; + const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; if (!isCompressed) { - for (let r = 0; r < regions.length; ++r) { - let region = regions[r]; - let buffOffset = region.buffOffset; + region.buffTexHeight * region.buffStride; + for (const region of regions) { + let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; let w = region.texExtent.width; let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - let data = bufferView.subarray(buffOffset, buffOffset + memSize); + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = bufferView.subarray(buffOffset, buffOffset + memSize); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, region.texOffset.x, region.texOffset.y, w, h, @@ -2002,16 +1984,15 @@ export function WebGLCmdFuncCopyBufferToTexture( } } } else { - for (let r = 0; r < regions.length; ++r) { - let region = regions[r]; + for (const region of regions) { let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; let w = region.texExtent.width; let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - let data = bufferView.subarray(buffOffset, buffOffset + memSize); + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = bufferView.subarray(buffOffset, buffOffset + memSize); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, region.texOffset.x, region.texOffset.y, w, h, @@ -2026,28 +2007,24 @@ export function WebGLCmdFuncCopyBufferToTexture( break; } case WebGLRenderingContext.TEXTURE_CUBE_MAP: { - let glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; + const glTexUnit = device.stateCache.glTexCubeUnits[device.stateCache.texUnit]; if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; } - let isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; + const isCompressed = GFXFormatInfos[gpuTexture.format].isCompressed; if (!isCompressed) { - for (let r = 0; r < regions.length; ++r) { - let region = regions[r]; + for (const region of regions) { let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - let w = region.texExtent.width; - let h = region.texExtent.height; - for (let f = 0; f < 6; ++f) { let w = region.texExtent.width; let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - let data = bufferView.subarray(buffOffset, buffOffset + memSize); + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = bufferView.subarray(buffOffset, buffOffset + memSize); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, @@ -2060,8 +2037,7 @@ export function WebGLCmdFuncCopyBufferToTexture( } } } else { - for (let r = 0; r < regions.length; ++r) { - let region = regions[r]; + for (const region of regions) { let buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; for (let f = 0; f < 6; ++f) { @@ -2069,8 +2045,8 @@ export function WebGLCmdFuncCopyBufferToTexture( let h = region.texExtent.height; for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { - let memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - let data = bufferView.subarray(buffOffset, buffOffset + memSize); + const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); + const data = bufferView.subarray(buffOffset, buffOffset + memSize); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, @@ -2086,7 +2062,7 @@ export function WebGLCmdFuncCopyBufferToTexture( break; } default: { - console.error("Unsupported GL texture type, copy buffer to texture failed."); + console.error('Unsupported GL texture type, copy buffer to texture failed.'); } } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index ae57c065b4..c450614744 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,38 +1,38 @@ -import { GFXDeviceInfo, GFXDevice } from '../device'; -import { GFXBuffer, GFXBufferInfo } from '../buffer'; -import { WebGLGFXBuffer } from './webgl-buffer'; -import { WebGLGFXQueue } from './webgl-queue'; -import { WebGLStateCache } from './webgl-state-cache'; -import { WebGLGPUBuffer, WebGLGPUObjectType, WebGLGPUTexture, WebGLGPURenderPass, WebGLGPUFramebuffer, WebGLGPUTextureView, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUSampler, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUPipelineLayout, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBinding } from './webgl-gpu-objects'; -import { WebGLCmdFuncUpdateBuffer, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncCreateBuffer, WebGLCmdFuncDestroyTexture, WebGLCmdFuncCreateTexture, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncCreateShader, WebGLCmdFuncDestroyShader, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncCopyBufferToTexture } from './webgl-commands'; -import { GFXTexture, GFXTextureInfo } from '../texture'; -import { GFXTextureViewInfo, GFXTextureView } from '../texture-view'; -import { GFXRenderPassInfo, GFXRenderPass } from '../render-pass'; -import { GFXFramebufferInfo, GFXFramebuffer } from '../framebuffer'; -import { WebGLGFXRenderPass } from './webgl-render-pass'; -import { WebGLGFXTextureView } from './webgl-texture-view'; -import { WebGLGFXTexture } from './webgl-texture'; -import { GFXShader, GFXShaderInfo } from '../shader'; -import { GFXSamplerInfo, GFXSampler } from '../sampler'; -import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; -import { GFXInputAssemblerInfo, GFXInputAssembler } from '../input-assembler'; -import { WebGLGFXShader } from './webgl-shader'; -import { GFXCommandAllocator, GFXCommandAllocatorInfo } from '../command-allocator'; -import { GFXPipelineStateInfo, GFXPipelineState, GFXRasterizerState } from '../pipeline-state'; -import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; -import { GFXBindingUnit, GFXBindingLayout, GFXBindingLayoutInfo } from '../binding-layout'; -import { WebGLGFXSampler } from './webgl-sampler'; -import { GFXCommandBufferInfo, GFXCommandBuffer } from '../command-buffer'; -import { GFXQueueInfo, GFXQueue } from '../queue'; -import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; -import { WebGLGFXPipelineState } from './webgl-pipeline-state'; -import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../pipeline-layout'; -import { WebGLGFXFramebuffer } from './webgl-framebuffer'; -import { WebGLGFXInputAssembler } from './webgl-input-assembler'; -import { GFXWindow, GFXWindowInfo } from '../window'; -import { WebGLGFXWindow } from './webgl-window'; -import { GFXBindingType, GFXFilter, GFXAddress, GFXTextureType, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXQueueType, GFXFormat, GFXBufferTextureCopy, GFXMemoryUsageBit, GFXTextureLayout, GFXTextureSubres, GFXRect, GFXFormatInfos, GFXFormatSize } from '../define'; +import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; +import { GFXBuffer, IGFXBufferInfo } from '../buffer'; +import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; +import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; +import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXFilter, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXQueueType, GFXTextureFlagBit, GFXTextureType, GFXTextureViewType } from '../define'; +import { GFXDevice, IGFXDeviceInfo } from '../device'; +import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../pipeline-layout'; +import { GFXPipelineState, IGFXPipelineStateInfo } from '../pipeline-state'; +import { GFXQueue, IGFXQueueInfo } from '../queue'; +import { GFXRenderPass, IGFXRenderPassInfo } from '../render-pass'; +import { GFXSampler, IGFXSamplerInfo } from '../sampler'; +import { GFXShader, IGFXShaderInfo } from '../shader'; +import { GFXTexture, IGFXTextureInfo } from '../texture'; +import { GFXTextureView, IGFXTextureViewInfo } from '../texture-view'; +import { GFXWindow, IGFXWindowInfo } from '../window'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; +import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; +import { WebGLCmdFuncCopyBufferToTexture, WebGLCmdFuncCreateBuffer, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncCreateShader, WebGLCmdFuncCreateTexture, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncDestroyShader, WebGLCmdFuncDestroyTexture, WebGLCmdFuncUpdateBuffer } from './webgl-commands'; +import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { WebGLGPUBinding, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer, WebGLGPUInputAssembler, WebGLGPUObjectType, WebGLGPUPipelineLayout, WebGLGPUPipelineState, WebGLGPURenderPass, WebGLGPUSampler, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUTexture, WebGLGPUTextureView } from './webgl-gpu-objects'; +import { WebGLGFXInputAssembler } from './webgl-input-assembler'; +import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; +import { WebGLGFXPipelineState } from './webgl-pipeline-state'; +import { WebGLGFXQueue } from './webgl-queue'; +import { WebGLGFXRenderPass } from './webgl-render-pass'; +import { WebGLGFXSampler } from './webgl-sampler'; +import { WebGLGFXShader } from './webgl-shader'; +import { WebGLStateCache } from './webgl-state-cache'; +import { WebGLGFXTexture } from './webgl-texture'; +import { WebGLGFXTextureView } from './webgl-texture-view'; +import { WebGLGFXWindow } from './webgl-window'; const WebGLPrimitives: GLenum[] = [ WebGLRenderingContext.POINTS, @@ -60,15 +60,137 @@ const WebGLWraps: GLenum[] = [ export class WebGLGFXDevice extends GFXDevice { - stateCache: WebGLStateCache = new WebGLStateCache; + public get gl (): WebGLRenderingContext { + return this._webGLRC as WebGLRenderingContext; + } - constructor() { + public get webGLQueue (): WebGLGFXQueue { + return this._queue as WebGLGFXQueue; + } + + public get isAntialias (): boolean { + return this._isAntialias; + } + + public get isPremultipliedAlpha (): boolean { + return this._isPremultipliedAlpha; + } + + public get EXT_texture_filter_anisotropic (): EXT_texture_filter_anisotropic | null { + return this._EXT_texture_filter_anisotropic; + } + + public get EXT_frag_depth (): EXT_frag_depth | null { + return this._EXT_frag_depth; + } + + public get EXT_shader_texture_lod (): EXT_shader_texture_lod | null { + return this._EXT_shader_texture_lod; + } + + public get EXT_sRGB (): EXT_sRGB | null { + return this._EXT_sRGB; + } + + public get OES_vertex_array_object (): OES_vertex_array_object | null { + return this._OES_vertex_array_object; + } + + public get WEBGL_color_buffer_float (): WEBGL_color_buffer_float | null { + return this._WEBGL_color_buffer_float; + } + + public get WEBGL_compressed_texture_astc (): WEBGL_compressed_texture_astc | null { + return this._WEBGL_compressed_texture_astc; + } + + public get WEBGL_compressed_texture_s3tc (): WEBGL_compressed_texture_s3tc | null { + return this._WEBGL_compressed_texture_s3tc; + } + + public get WEBGL_compressed_texture_s3tc_srgb (): WEBGL_compressed_texture_s3tc_srgb | null { + return this._WEBGL_compressed_texture_s3tc_srgb; + } + + public get WEBGL_debug_shaders (): WEBGL_debug_shaders | null { + return this._WEBGL_debug_shaders; + } + + public get WEBGL_draw_buffers (): WEBGL_draw_buffers | null { + return this._WEBGL_draw_buffers; + } + + public get WEBGL_lose_context (): WEBGL_lose_context | null { + return this._WEBGL_lose_context; + } + + public get WEBGL_depth_texture (): WEBGL_depth_texture | null { + return this._WEBGL_depth_texture; + } + + public get WEBGL_debug_renderer_info (): WEBGL_debug_renderer_info | null { + return this._WEBGL_debug_renderer_info; + } + + public get OES_texture_half_float (): OES_texture_half_float | null { + return this._OES_texture_half_float; + } + + public get OES_texture_half_float_linear (): OES_texture_half_float_linear | null { + return this._OES_texture_half_float_linear; + } + + public get OES_texture_float (): OES_texture_float | null { + return this._OES_texture_float; + } + + public get OES_standard_derivatives (): OES_standard_derivatives | null { + return this._OES_standard_derivatives; + } + + public get OES_element_index_uint (): OES_element_index_uint | null { + return this._OES_element_index_uint; + } + + public get ANGLE_instanced_arrays (): ANGLE_instanced_arrays | null { + return this._ANGLE_instanced_arrays; + } + + public stateCache: WebGLStateCache = new WebGLStateCache(); + + private _webGLRC: WebGLRenderingContext | null = null; + private _isAntialias: boolean = true; + private _isPremultipliedAlpha: boolean = false; + + private _extensions: string[] | null = null; + private _EXT_texture_filter_anisotropic: EXT_texture_filter_anisotropic | null = null; + private _EXT_frag_depth: EXT_frag_depth | null = null; + private _EXT_shader_texture_lod: EXT_shader_texture_lod | null = null; + private _EXT_sRGB: EXT_sRGB | null = null; + private _OES_vertex_array_object: OES_vertex_array_object | null = null; + private _WEBGL_color_buffer_float: WEBGL_color_buffer_float | null = null; + private _WEBGL_compressed_texture_astc: WEBGL_compressed_texture_astc | null = null; + private _WEBGL_compressed_texture_s3tc: WEBGL_compressed_texture_s3tc | null = null; + private _WEBGL_compressed_texture_s3tc_srgb: WEBGL_compressed_texture_s3tc_srgb | null = null; + private _WEBGL_debug_shaders: WEBGL_debug_shaders | null = null; + private _WEBGL_draw_buffers: WEBGL_draw_buffers | null = null; + private _WEBGL_lose_context: WEBGL_lose_context | null = null; + private _WEBGL_depth_texture: WEBGL_depth_texture | null = null; + private _WEBGL_debug_renderer_info: WEBGL_debug_renderer_info | null = null; + private _OES_texture_half_float: OES_texture_half_float | null = null; + private _OES_texture_half_float_linear: OES_texture_half_float_linear | null = null; + private _OES_texture_float: OES_texture_float | null = null; + private _OES_standard_derivatives: OES_standard_derivatives | null = null; + private _OES_element_index_uint: OES_element_index_uint | null = null; + private _ANGLE_instanced_arrays: ANGLE_instanced_arrays | null = null; + + constructor () { super(); } - public initialize(info: GFXDeviceInfo): boolean { + public initialize (info: IGFXDeviceInfo): boolean { - this._canvas = info.canvasElm; + this._canvas = info.canvasElm as HTMLCanvasElement; if (info.isAntialias) { this._isAntialias = info.isAntialias; @@ -79,14 +201,14 @@ export class WebGLGFXDevice extends GFXDevice { } try { - let webGLCtxAttribs: WebGLContextAttributes = { + const webGLCtxAttribs: WebGLContextAttributes = { alpha: true, antialias: this._isAntialias, depth: true, stencil: true, premultipliedAlpha: this._isPremultipliedAlpha, preserveDrawingBuffer: false, - powerPreference: "default", + powerPreference: 'default', failIfMajorPerformanceCaveat: false, }; @@ -107,10 +229,10 @@ export class WebGLGFXDevice extends GFXDevice { console.info('WebGL device initialized.'); - this._deviceName = "WebGL"; - let gl = this._webGLRC; + this._deviceName = 'WebGL'; + const gl = this._webGLRC; - this._WEBGL_debug_renderer_info = gl.getExtension("WEBGL_debug_renderer_info"); + this._WEBGL_debug_renderer_info = gl.getExtension('WEBGL_debug_renderer_info'); if (this._WEBGL_debug_renderer_info) { this._renderer = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL); this._vendor = gl.getParameter(this._WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL); @@ -146,20 +268,20 @@ export class WebGLGFXDevice extends GFXDevice { } } - console.info("RENDERER: " + this._renderer); - console.info("VENDOR: " + this._vendor); - console.info("VERSION: " + this._version); - console.info("SCREEN_SIZE: " + this._width + " x " + this._height); - console.info("COLOR_FORMAT: " + GFXFormatInfos[this._colorFmt].name); - console.info("DEPTH_STENCIL_FORMAT: " + GFXFormatInfos[this._depthStencilFmt].name); + console.info('RENDERER: ' + this._renderer); + console.info('VENDOR: ' + this._vendor); + console.info('VERSION: ' + this._version); + console.info('SCREEN_SIZE: ' + this._width + ' x ' + this._height); + console.info('COLOR_FORMAT: ' + GFXFormatInfos[this._colorFmt].name); + console.info('DEPTH_STENCIL_FORMAT: ' + GFXFormatInfos[this._depthStencilFmt].name); - console.info("MAX_VERTEX_ATTRIBS: " + this._maxVertexAttributes); - console.info("MAX_VERTEX_UNIFORM_VECTORS: " + this._maxVertexUniformVectors); - console.info("MAX_FRAGMENT_UNIFORM_VECTORS: " + this._maxFragmentUniformVectors); - console.info("MAX_TEXTURE_IMAGE_UNITS: " + this._maxTextureUnits); - console.info("MAX_VERTEX_TEXTURE_IMAGE_UNITS: " + this._maxVertexTextureUnits); - console.info("DEPTH_BITS: " + this._depthBits); - console.info("STENCIL_BITS: " + this._stencilBits); + console.info('MAX_VERTEX_ATTRIBS: ' + this._maxVertexAttributes); + console.info('MAX_VERTEX_UNIFORM_VECTORS: ' + this._maxVertexUniformVectors); + console.info('MAX_FRAGMENT_UNIFORM_VECTORS: ' + this._maxFragmentUniformVectors); + console.info('MAX_TEXTURE_IMAGE_UNITS: ' + this._maxTextureUnits); + console.info('MAX_VERTEX_TEXTURE_IMAGE_UNITS: ' + this._maxVertexTextureUnits); + console.info('DEPTH_BITS: ' + this._depthBits); + console.info('STENCIL_BITS: ' + this._stencilBits); this._extensions = gl.getSupportedExtensions(); /* @@ -170,31 +292,29 @@ export class WebGLGFXDevice extends GFXDevice { } */ - this._EXT_texture_filter_anisotropic = gl.getExtension("EXT_texture_filter_anisotropic"); - this._EXT_frag_depth = gl.getExtension("EXT_frag_depth"); - this._EXT_shader_texture_lod = gl.getExtension("EXT_shader_texture_lod"); - this._EXT_sRGB = gl.getExtension("EXT_sRGB"); - this._OES_vertex_array_object = gl.getExtension("OES_vertex_array_object"); - this._WEBGL_color_buffer_float = gl.getExtension("WEBGL_color_buffer_float"); - this._WEBGL_compressed_texture_astc = gl.getExtension("WEBGL_compressed_texture_astc"); - this._WEBGL_compressed_texture_s3tc = gl.getExtension("WEBGL_compressed_texture_s3tc"); - this._WEBGL_compressed_texture_s3tc_srgb = gl.getExtension("WEBGL_compressed_texture_s3tc_srgb"); - this._WEBGL_debug_shaders = gl.getExtension("WEBGL_debug_shaders"); - this._WEBGL_draw_buffers = gl.getExtension("WEBGL_draw_buffers"); - this._WEBGL_lose_context = gl.getExtension("WEBGL_lose_context"); - this._WEBGL_depth_texture = gl.getExtension("WEBGL_depth_texture"); - this._OES_texture_half_float = gl.getExtension("OES_texture_half_float"); - this._OES_texture_half_float_linear = gl.getExtension("OES_texture_half_float_linear"); - this._OES_texture_float = gl.getExtension("OES_texture_float"); - this._OES_standard_derivatives = gl.getExtension("OES_standard_derivatives"); - this._OES_element_index_uint = gl.getExtension("OES_element_index_uint"); - this._ANGLE_instanced_arrays = gl.getExtension("ANGLE_instanced_arrays"); + this._EXT_texture_filter_anisotropic = gl.getExtension('EXT_texture_filter_anisotropic'); + this._EXT_frag_depth = gl.getExtension('EXT_frag_depth'); + this._EXT_shader_texture_lod = gl.getExtension('EXT_shader_texture_lod'); + this._EXT_sRGB = gl.getExtension('EXT_sRGB'); + this._OES_vertex_array_object = gl.getExtension('OES_vertex_array_object'); + this._WEBGL_color_buffer_float = gl.getExtension('WEBGL_color_buffer_float'); + this._WEBGL_compressed_texture_astc = gl.getExtension('WEBGL_compressed_texture_astc'); + this._WEBGL_compressed_texture_s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc'); + this._WEBGL_compressed_texture_s3tc_srgb = gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'); + this._WEBGL_debug_shaders = gl.getExtension('WEBGL_debug_shaders'); + this._WEBGL_draw_buffers = gl.getExtension('WEBGL_draw_buffers'); + this._WEBGL_lose_context = gl.getExtension('WEBGL_lose_context'); + this._WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture'); + this._OES_texture_half_float = gl.getExtension('OES_texture_half_float'); + this._OES_texture_half_float_linear = gl.getExtension('OES_texture_half_float_linear'); + this._OES_texture_float = gl.getExtension('OES_texture_float'); + this._OES_standard_derivatives = gl.getExtension('OES_standard_derivatives'); + this._OES_element_index_uint = gl.getExtension('OES_element_index_uint'); + this._ANGLE_instanced_arrays = gl.getExtension('ANGLE_instanced_arrays'); // init states this.initStates(gl); - - // create queue this._queue = this.createQueue({ type: GFXQueueType.GRAPHICS }); @@ -214,7 +334,7 @@ export class WebGLGFXDevice extends GFXDevice { return true; } - public destroy(): void { + public destroy (): void { if (this._mainWindow) { this._mainWindow.destroy(); @@ -234,8 +354,8 @@ export class WebGLGFXDevice extends GFXDevice { this._webGLRC = null; } - public createBuffer(info: GFXBufferInfo): GFXBuffer | null { - let buffer = new WebGLGFXBuffer(this); + public createBuffer (info: IGFXBufferInfo): GFXBuffer | null { + const buffer = new WebGLGFXBuffer(this); if (buffer.initialize(info)) { return buffer; } else { @@ -244,8 +364,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createTexture(info: GFXTextureInfo): GFXTexture | null { - let texture = new WebGLGFXTexture(this); + public createTexture (info: IGFXTextureInfo): GFXTexture | null { + const texture = new WebGLGFXTexture(this); if (texture.initialize(info)) { return texture; } else { @@ -254,8 +374,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createTextureView(info: GFXTextureViewInfo): GFXTextureView | null { - let texView = new WebGLGFXTextureView(this); + public createTextureView (info: IGFXTextureViewInfo): GFXTextureView | null { + const texView = new WebGLGFXTextureView(this); if (texView.initialize(info)) { return texView; } else { @@ -264,8 +384,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createSampler(info: GFXSamplerInfo): GFXSampler | null { - let sampler = new WebGLGFXSampler(this); + public createSampler (info: IGFXSamplerInfo): GFXSampler | null { + const sampler = new WebGLGFXSampler(this); if (sampler.initialize(info)) { return sampler; } else { @@ -274,8 +394,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createBindingLayout(info: GFXBindingLayoutInfo): GFXBindingLayout | null { - let bindingLayout = new WebGLGFXBindingLayout(this); + public createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout | null { + const bindingLayout = new WebGLGFXBindingLayout(this); if (bindingLayout.initialize(info)) { return bindingLayout; } else { @@ -284,8 +404,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createShader(info: GFXShaderInfo): GFXShader | null { - let shader = new WebGLGFXShader(this); + public createShader (info: IGFXShaderInfo): GFXShader | null { + const shader = new WebGLGFXShader(this); if (shader.initialize(info)) { return shader; } else { @@ -294,8 +414,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createInputAssembler(info: GFXInputAssemblerInfo): GFXInputAssembler | null { - let inputAssembler = new WebGLGFXInputAssembler(this); + public createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler | null { + const inputAssembler = new WebGLGFXInputAssembler(this); if (inputAssembler.initialize(info)) { return inputAssembler; } else { @@ -304,8 +424,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createRenderPass(info: GFXRenderPassInfo): GFXRenderPass | null { - let renderPass = new WebGLGFXRenderPass(this); + public createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass | null { + const renderPass = new WebGLGFXRenderPass(this); if (renderPass.initialize(info)) { return renderPass; } else { @@ -314,8 +434,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createFramebuffer(info: GFXFramebufferInfo): GFXFramebuffer | null { - let framebuffer = new WebGLGFXFramebuffer(this); + public createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer | null { + const framebuffer = new WebGLGFXFramebuffer(this); if (framebuffer.initialize(info)) { return framebuffer; } else { @@ -324,8 +444,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createPipelineLayout(info: GFXPipelineLayoutInfo): GFXPipelineLayout | null { - let pipelineLayout = new WebGLGFXPipelineLayout(this); + public createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout | null { + const pipelineLayout = new WebGLGFXPipelineLayout(this); if (pipelineLayout.initialize(info)) { return pipelineLayout; } else { @@ -334,8 +454,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createPipelineState(info: GFXPipelineStateInfo): GFXPipelineState | null { - let pipelineState = new WebGLGFXPipelineState(this); + public createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState | null { + const pipelineState = new WebGLGFXPipelineState(this); if (pipelineState.initialize(info)) { return pipelineState; } else { @@ -344,8 +464,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createCommandAllocator(info: GFXCommandAllocatorInfo): GFXCommandAllocator | null { - let cmdAllocator = new WebGLGFXCommandAllocator(this); + public createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator | null { + const cmdAllocator = new WebGLGFXCommandAllocator(this); if (cmdAllocator.initialize(info)) { return cmdAllocator; } else { @@ -354,8 +474,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createCommandBuffer(info: GFXCommandBufferInfo): GFXCommandBuffer | null { - let cmdBuff = new WebGLGFXCommandBuffer(this); + public createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer | null { + const cmdBuff = new WebGLGFXCommandBuffer(this); if (cmdBuff.initialize(info)) { return cmdBuff; } else { @@ -364,8 +484,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createQueue(info: GFXQueueInfo): GFXQueue | null { - let queue = new WebGLGFXQueue(this); + public createQueue (info: IGFXQueueInfo): GFXQueue | null { + const queue = new WebGLGFXQueue(this); if (queue.initialize(info)) { return queue; } else { @@ -374,8 +494,8 @@ export class WebGLGFXDevice extends GFXDevice { } } - public createWindow(info: GFXWindowInfo): GFXWindow | null { - let window = new WebGLGFXWindow(this); + public createWindow (info: IGFXWindowInfo): GFXWindow | null { + const window = new WebGLGFXWindow(this); if (window.initialize(info)) { return window; } else { @@ -384,55 +504,54 @@ export class WebGLGFXDevice extends GFXDevice { } } - public present() { + public present () { } - public copyBufferToTexture(buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - let bufferView = new Uint8Array(buffer); - WebGLCmdFuncCopyBufferToTexture(this, bufferView, (texture).gpuTexture, regions); + const bufferView = new Uint8Array(buffer); + WebGLCmdFuncCopyBufferToTexture(this as WebGLGFXDevice, bufferView, (texture as WebGLGFXTexture).gpuTexture, regions); } - public copyImageSourceToTexture(source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { + public copyImageSourceToTexture (source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { if (this._canvas2D) { - let context = this._canvas2D.getContext('2d'); + const context = this._canvas2D.getContext('2d'); if (context) { this._canvas2D.width = texture.width; this._canvas2D.height = texture.height; context.drawImage(source, 0, 0); - let imgData = context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height); - let bufferView = new Uint8Array(imgData.data); + const imgData = context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height); + const bufferView = new Uint8Array(imgData.data); - WebGLCmdFuncCopyBufferToTexture(this, bufferView, (texture).gpuTexture, regions); + WebGLCmdFuncCopyBufferToTexture(this as WebGLGFXDevice, bufferView, (texture as WebGLGFXTexture).gpuTexture, regions); } } } - public copyFramebufferToBuffer(srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]) { - let gl = this._webGLRC; - let gpuFramebuffer = (srcFramebuffer).gpuFramebuffer; + public copyFramebufferToBuffer (srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]) { + const gl = this._webGLRC as WebGLRenderingContext; + const gpuFramebuffer = (srcFramebuffer as WebGLGFXFramebuffer).gpuFramebuffer; - let curFBO = this.stateCache.glFramebuffer; + const curFBO = this.stateCache.glFramebuffer; if (this.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); this.stateCache.glFramebuffer = gpuFramebuffer.glFramebuffer; } - let view = new Uint8Array(dstBuffer); + const view = new Uint8Array(dstBuffer); - for (let r = 0; r < regions.length; ++r) { - let region = regions[r]; - let buffOffset = region.buffOffset; + region.buffTexHeight * region.buffStride; + for (const region of regions) { + const buffOffset = region.buffOffset + region.buffTexHeight * region.buffStride; - let w = region.texExtent.width; - let h = region.texExtent.height; + const w = region.texExtent.width; + const h = region.texExtent.height; - let memSize = GFXFormatSize(GFXFormat.RGBA8, w, h, 1); - let data = view.subarray(buffOffset, buffOffset + memSize); + const memSize = GFXFormatSize(GFXFormat.RGBA8, w, h, 1); + const data = view.subarray(buffOffset, buffOffset + memSize); gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, data); } @@ -443,17 +562,9 @@ export class WebGLGFXDevice extends GFXDevice { } } - public get gl(): WebGLRenderingContext { - return this._webGLRC; - } + public emitCmdCreateGPUBuffer (info: IGFXBufferInfo, buffer: ArrayBuffer | null): WebGLGPUBuffer | null { - public get webGLQueue(): WebGLGFXQueue { - return this._queue; - } - - public emitCmdCreateGPUBuffer(info: GFXBufferInfo, buffer: ArrayBuffer | null): WebGLGPUBuffer | null { - - let gpuBuffer: WebGLGPUBuffer = { + const gpuBuffer: WebGLGPUBuffer = { objType: WebGLGPUObjectType.BUFFER, usage: info.usage, memUsage: info.memUsage, @@ -471,30 +582,30 @@ export class WebGLGFXDevice extends GFXDevice { gpuBuffer.viewUI8 = new Uint8Array(gpuBuffer.buffer); } - //let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; + // let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncCreateBuffer(this, gpuBuffer); + WebGLCmdFuncCreateBuffer(this as WebGLGFXDevice, gpuBuffer); return gpuBuffer; } - public emitCmdDestroyGPUBuffer(gpuBuffer: WebGLGPUBuffer) { + public emitCmdDestroyGPUBuffer (gpuBuffer: WebGLGPUBuffer) { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncDestroyBuffer(this, gpuBuffer); + WebGLCmdFuncDestroyBuffer(this as WebGLGFXDevice, gpuBuffer); } - public emitCmdUpdateGPUBuffer(gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { + public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { // TODO: Async - let isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; + const isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; if (!isStagingBuffer) { - WebGLCmdFuncUpdateBuffer(this, gpuBuffer, offset, buffer); + WebGLCmdFuncUpdateBuffer(this as WebGLGFXDevice, gpuBuffer, offset, buffer); } } - public emitCmdCreateGPUTexture(info: GFXTextureInfo): WebGLGPUTexture { + public emitCmdCreateGPUTexture (info: IGFXTextureInfo): WebGLGPUTexture { let viewType: GFXTextureViewType; @@ -527,7 +638,6 @@ export class WebGLGFXDevice extends GFXDevice { viewType = GFXTextureViewType.TV2D; } - break; } case GFXTextureType.TEX3D: { @@ -539,10 +649,10 @@ export class WebGLGFXDevice extends GFXDevice { } } - let gpuTexture: WebGLGPUTexture = { + const gpuTexture: WebGLGPUTexture = { objType: WebGLGPUObjectType.TEXTURE, type: info.type, - viewType: viewType, + viewType, format: info.format, usage: info.usage, width: info.width, @@ -562,22 +672,22 @@ export class WebGLGFXDevice extends GFXDevice { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncCreateTexture(this, gpuTexture); + WebGLCmdFuncCreateTexture(this as WebGLGFXDevice, gpuTexture); return gpuTexture; } - public emitCmdDestroyGPUTexture(gpuTexture: WebGLGPUTexture) { + public emitCmdDestroyGPUTexture (gpuTexture: WebGLGPUTexture) { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncDestroyTexture(this, gpuTexture); + WebGLCmdFuncDestroyTexture(this as WebGLGFXDevice, gpuTexture); } - public emitCmdCreateGPUTextureView(info: GFXTextureViewInfo): WebGLGPUTextureView { - let webGLTexture = info.texture; + public emitCmdCreateGPUTextureView (info: IGFXTextureViewInfo): WebGLGPUTextureView { + const webGLTexture = info.texture as WebGLGFXTexture; - let gpuTextureView: WebGLGPUTextureView = { + const gpuTextureView: WebGLGPUTextureView = { objType: WebGLGPUObjectType.TEXTURE_VIEW, gpuTexture: webGLTexture.gpuTexture, type: info.type, @@ -589,62 +699,60 @@ export class WebGLGFXDevice extends GFXDevice { return gpuTextureView; } - public emitCmdDestroyGPUTextureView(gpuTextureView: WebGLGPUTextureView) { + public emitCmdDestroyGPUTextureView (gpuTextureView: WebGLGPUTextureView) { } - public emitCmdCreateGPURenderPass(info: GFXRenderPassInfo): WebGLGPURenderPass { - let gpuRenderPass: WebGLGPURenderPass = { + public emitCmdCreateGPURenderPass (info: IGFXRenderPassInfo): WebGLGPURenderPass { + const gpuRenderPass: WebGLGPURenderPass = { objType: WebGLGPUObjectType.RENDER_PASS, colorAttachments: info.colorAttachments ? info.colorAttachments : [], depthStencilAttachment: info.depthStencilAttachment ? info.depthStencilAttachment : null, - } + }; return gpuRenderPass; } - public emitCmdDestroyGPURenderPass(gpuRenderPass: WebGLGPURenderPass) { + public emitCmdDestroyGPURenderPass (gpuRenderPass: WebGLGPURenderPass) { } - public emitCmdCreateGPUFramebuffer(info: GFXFramebufferInfo): WebGLGPUFramebuffer { + public emitCmdCreateGPUFramebuffer (info: IGFXFramebufferInfo): WebGLGPUFramebuffer { - let renderPass = info.renderPass; + const renderPass = info.renderPass as WebGLGFXRenderPass; - let isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; + const isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; if (isOffscreen) { - let gpuColorViews: WebGLGPUTextureView[] = []; + const gpuColorViews: WebGLGPUTextureView[] = []; if (info.colorViews) { - for (let i = 0; i < info.colorViews.length; ++i) { - let webGLColorView = info.colorViews[i]; - if (webGLColorView.gpuTextureView) { - gpuColorViews.push(webGLColorView.gpuTextureView); - } + for (const colorView of info.colorViews) { + const webGLColorView = colorView as WebGLGFXTextureView; + gpuColorViews.push(webGLColorView.gpuTextureView); } } let gpuDepthStencilView: WebGLGPUTextureView | null = null; if (info.depthStencilView) { - gpuDepthStencilView = (info.depthStencilView).gpuTextureView; + gpuDepthStencilView = (info.depthStencilView as WebGLGFXTextureView).gpuTextureView; } - let gpuFramebuffer: WebGLGPUFramebuffer = { + const gpuFramebuffer: WebGLGPUFramebuffer = { objType: WebGLGPUObjectType.FRAMEBUFFER, gpuRenderPass: renderPass.gpuRenderPass, - gpuColorViews: gpuColorViews, - gpuDepthStencilView: gpuDepthStencilView, + gpuColorViews, + gpuDepthStencilView, isOffscreen: info.isOffscreen, glFramebuffer: 0, }; // TODO: Async - WebGLCmdFuncCreateFramebuffer(this, gpuFramebuffer); + WebGLCmdFuncCreateFramebuffer(this as WebGLGFXDevice, gpuFramebuffer); return gpuFramebuffer; } else { - let gpuFramebuffer: WebGLGPUFramebuffer = { + const gpuFramebuffer: WebGLGPUFramebuffer = { objType: WebGLGPUObjectType.FRAMEBUFFER, gpuRenderPass: renderPass.gpuRenderPass, gpuColorViews: [], @@ -657,21 +765,21 @@ export class WebGLGFXDevice extends GFXDevice { } } - public emitCmdDestroyGPUFramebuffer(gpuFramebuffer: WebGLGPUFramebuffer) { + public emitCmdDestroyGPUFramebuffer (gpuFramebuffer: WebGLGPUFramebuffer) { if (gpuFramebuffer.isOffscreen) { // TODO: Async - WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); + WebGLCmdFuncDestroyFramebuffer(this as WebGLGFXDevice, gpuFramebuffer); } } - public emitCmdCreateGPUSampler(info: GFXSamplerInfo): WebGLGPUSampler { + public emitCmdCreateGPUSampler (info: IGFXSamplerInfo): WebGLGPUSampler { let glMinFilter = WebGLRenderingContext.NONE; let glMagFilter = WebGLRenderingContext.NONE; - let minFilter = (info.minFilter !== undefined ? info.minFilter : GFXFilter.LINEAR); - let magFilter = (info.magFilter !== undefined ? info.magFilter : GFXFilter.LINEAR); - let mipFilter = (info.mipFilter !== undefined ? info.mipFilter : GFXFilter.NONE); + const minFilter = (info.minFilter !== undefined ? info.minFilter : GFXFilter.LINEAR); + const magFilter = (info.magFilter !== undefined ? info.magFilter : GFXFilter.LINEAR); + const mipFilter = (info.mipFilter !== undefined ? info.mipFilter : GFXFilter.NONE); if (minFilter === GFXFilter.LINEAR || minFilter === GFXFilter.ANISOTROPIC) { if (mipFilter === GFXFilter.LINEAR || mipFilter === GFXFilter.ANISOTROPIC) { @@ -697,33 +805,33 @@ export class WebGLGFXDevice extends GFXDevice { glMagFilter = WebGLRenderingContext.NEAREST; } - let glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); - let glWrapT = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); - let glWrapR = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapS = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapT = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); + const glWrapR = (info.addressU !== undefined ? WebGLWraps[info.addressU] : WebGLRenderingContext.REPEAT); - let gpuSampler: WebGLGPUSampler = { + const gpuSampler: WebGLGPUSampler = { objType: WebGLGPUObjectType.SAMPLER, - glMinFilter: glMinFilter, - glMagFilter: glMagFilter, - glWrapS: glWrapS, - glWrapT: glWrapT, - glWrapR: glWrapR, + glMinFilter, + glMagFilter, + glWrapS, + glWrapT, + glWrapR, }; return gpuSampler; } - public emitCmdDestroyGPUSampler(gpuSampler: WebGLGPUSampler) { + public emitCmdDestroyGPUSampler (gpuSampler: WebGLGPUSampler) { // TODO: Async } - public emitCmdCreateGPUShader(info: GFXShaderInfo): WebGLGPUShader { + public emitCmdCreateGPUShader (info: IGFXShaderInfo): WebGLGPUShader { - let gpuStages: WebGLGPUShaderStage[] = new Array(info.stages.length); + const gpuStages: WebGLGPUShaderStage[] = new Array(info.stages.length); for (let i = 0; i < info.stages.length; ++i) { - let stage = info.stages[i]; + const stage = info.stages[i]; gpuStages[i] = { type: stage.type, source: stage.source, @@ -732,13 +840,13 @@ export class WebGLGFXDevice extends GFXDevice { }; } - let gpuShader: WebGLGPUShader = { + const gpuShader: WebGLGPUShader = { objType: WebGLGPUObjectType.SHADER, - name: info.name ? info.name : "", + name: info.name ? info.name : '', blocks: (info.blocks !== undefined ? info.blocks : []), samplers: (info.samplers !== undefined ? info.samplers : []), - gpuStages: gpuStages, + gpuStages, glProgram: 0, glInputs: [], glUniforms: [], @@ -747,56 +855,56 @@ export class WebGLGFXDevice extends GFXDevice { }; // TODO: Async - WebGLCmdFuncCreateShader(this, gpuShader); + WebGLCmdFuncCreateShader(this as WebGLGFXDevice, gpuShader); return gpuShader; } - public emitCmdDestroyGPUShader(gpuShader: WebGLGPUShader) { + public emitCmdDestroyGPUShader (gpuShader: WebGLGPUShader) { // TODO: Async - WebGLCmdFuncDestroyShader(this, gpuShader); + WebGLCmdFuncDestroyShader(this as WebGLGFXDevice, gpuShader); } - public emitCmdCreateGPUPipelineState(info: GFXPipelineStateInfo): WebGLGPUPipelineState { + public emitCmdCreateGPUPipelineState (info: IGFXPipelineStateInfo): WebGLGPUPipelineState { let gpuShader: WebGLGPUShader | null = null; if (info.shader) { - gpuShader = (info.shader).gpuShader; + gpuShader = (info.shader as WebGLGFXShader).gpuShader; } let gpuLayout: WebGLGPUPipelineLayout | null = null; if (info.layout) { - gpuLayout = (info.layout).gpuPipelineLayout; + gpuLayout = (info.layout as WebGLGFXPipelineLayout).gpuPipelineLayout; } let gpuRenderPass: WebGLGPURenderPass | null = null; if (info.renderPass) { - gpuRenderPass = (info.renderPass).gpuRenderPass; + gpuRenderPass = (info.renderPass as WebGLGFXRenderPass).gpuRenderPass; } - let gpuPipelineState: WebGLGPUPipelineState = { + const gpuPipelineState: WebGLGPUPipelineState = { objType: WebGLGPUObjectType.PIPELINE_STATE, glPrimitive: info.primitive, - gpuShader: gpuShader, + gpuShader, rs: info.rs, dss: info.dss, bs: info.bs, - gpuLayout: gpuLayout, - gpuRenderPass: gpuRenderPass, + gpuLayout, + gpuRenderPass, }; return gpuPipelineState; } - public emitCmdDestroyGPUPipelineState(gpuPipelineState: WebGLGPUPipelineState) { + public emitCmdDestroyGPUPipelineState (gpuPipelineState: WebGLGPUPipelineState) { // TODO: Async } - public emitCmdCreateGPUBindingLayout(info: GFXBindingLayoutInfo): WebGLGPUBindingLayout { + public emitCmdCreateGPUBindingLayout (info: IGFXBindingLayoutInfo): WebGLGPUBindingLayout { - let gpuBindings: WebGLGPUBinding[] = new Array(info.bindings.length); + const gpuBindings: WebGLGPUBinding[] = new Array(info.bindings.length); for (let i = 0; i < info.bindings.length; ++i) { - let binding = info.bindings[i]; + const binding = info.bindings[i]; gpuBindings[i] = { binding: binding.binding, type: binding.type, @@ -807,24 +915,24 @@ export class WebGLGFXDevice extends GFXDevice { }; } - let gpuBindingLayout: WebGLGPUBindingLayout = { + const gpuBindingLayout: WebGLGPUBindingLayout = { objType: WebGLGPUObjectType.BINDING_LAYOUT, - gpuBindings: gpuBindings, + gpuBindings, }; return gpuBindingLayout; } - public emitCmdDestroyGPUBindingLayout(gpuBindingLayout: WebGLGPUBindingLayout) { + public emitCmdDestroyGPUBindingLayout (gpuBindingLayout: WebGLGPUBindingLayout) { // TODO: Async } - public emitCmdUpdateGPUBindingLayout(gpuBindingLayout: WebGLGPUBindingLayout, bindingUnits: GFXBindingUnit[]) { + public emitCmdUpdateGPUBindingLayout (gpuBindingLayout: WebGLGPUBindingLayout, bindingUnits: GFXBindingUnit[]) { // TODO: Async for (let i = 0; i < bindingUnits.length; ++i) { - let bindingUnit = bindingUnits[i]; - let gpuBinding = gpuBindingLayout.gpuBindings[i]; + const bindingUnit = bindingUnits[i]; + const gpuBinding = gpuBindingLayout.gpuBindings[i]; gpuBinding.binding = bindingUnit.binding; gpuBinding.type = bindingUnit.type; gpuBinding.name = bindingUnit.name; @@ -832,31 +940,31 @@ export class WebGLGFXDevice extends GFXDevice { switch (bindingUnit.type) { case GFXBindingType.UNIFORM_BUFFER: { if (bindingUnit.buffer) { - gpuBinding.gpuBuffer = (bindingUnit.buffer).gpuBuffer; + gpuBinding.gpuBuffer = (bindingUnit.buffer as WebGLGFXBuffer).gpuBuffer; } break; } case GFXBindingType.SAMPLER: { if (bindingUnit.texView) { - gpuBinding.gpuTexView = (bindingUnit.texView).gpuTextureView; + gpuBinding.gpuTexView = (bindingUnit.texView as WebGLGFXTextureView).gpuTextureView; } if (bindingUnit.sampler) { - gpuBinding.gpuSampler = (bindingUnit.sampler).gpuSampler; + gpuBinding.gpuSampler = (bindingUnit.sampler as WebGLGFXSampler).gpuSampler; } break; } - default: ; + default: } } } - public emitCmdCreateGPUInputAssembler(info: GFXInputAssemblerInfo): WebGLGPUInputAssembler { + public emitCmdCreateGPUInputAssembler (info: IGFXInputAssemblerInfo): WebGLGPUInputAssembler { - let gpuVertexBuffers: WebGLGPUBuffer[] = new Array(info.vertexBuffers.length); + const gpuVertexBuffers: WebGLGPUBuffer[] = new Array(info.vertexBuffers.length); for (let i = 0; i < info.vertexBuffers.length; ++i) { - let vb = info.vertexBuffers[i]; + const vb = info.vertexBuffers[i] as WebGLGFXBuffer; if (vb.gpuBuffer) { gpuVertexBuffers[i] = vb.gpuBuffer; } @@ -866,130 +974,42 @@ export class WebGLGFXDevice extends GFXDevice { let glIndexType = 0; if (info.indexBuffer) { - gpuIndexBuffer = (info.indexBuffer).gpuBuffer; + gpuIndexBuffer = (info.indexBuffer as WebGLGFXBuffer).gpuBuffer; if (gpuIndexBuffer) { switch (gpuIndexBuffer.stride) { case 1: glIndexType = WebGLRenderingContext.UNSIGNED_BYTE; break; case 2: glIndexType = WebGLRenderingContext.UNSIGNED_SHORT; break; case 4: glIndexType = WebGLRenderingContext.UNSIGNED_INT; break; default: { - console.error("Error index buffer stride."); + console.error('Error index buffer stride.'); } } } } - let gpuInputAssembler: WebGLGPUInputAssembler = { + const gpuInputAssembler: WebGLGPUInputAssembler = { objType: WebGLGPUObjectType.INPUT_ASSEMBLER, attributes: info.attributes, - gpuVertexBuffers: gpuVertexBuffers, - gpuIndexBuffer: gpuIndexBuffer, + gpuVertexBuffers, + gpuIndexBuffer, glAttribs: [], - glIndexType: glIndexType, + glIndexType, glVAO: 0, }; - WebGLCmdFuncCreateInputAssember(this, gpuInputAssembler); + WebGLCmdFuncCreateInputAssember(this as WebGLGFXDevice, gpuInputAssembler); // TODO: Async return gpuInputAssembler; } - public emitCmdDestroyGPUInputAssembler(gpuInputAssembler: WebGLGPUInputAssembler) { + public emitCmdDestroyGPUInputAssembler (gpuInputAssembler: WebGLGPUInputAssembler) { // TODO: Async // WebGLCmdFuncDestroyInputAssembler(this, gpuInputAssembler); } - public get isAntialias(): boolean { - return this._isAntialias; - } - - public get isPremultipliedAlpha(): boolean { - return this._isPremultipliedAlpha; - } - - public get EXT_texture_filter_anisotropic(): EXT_texture_filter_anisotropic | null { - return this._EXT_texture_filter_anisotropic; - } - - public get EXT_frag_depth(): EXT_frag_depth | null { - return this._EXT_frag_depth; - } - - public get EXT_shader_texture_lod(): EXT_shader_texture_lod | null { - return this._EXT_shader_texture_lod; - } - - public get EXT_sRGB(): EXT_sRGB | null { - return this._EXT_sRGB; - } - - public get OES_vertex_array_object(): OES_vertex_array_object | null { - return this._OES_vertex_array_object; - } - - public get WEBGL_color_buffer_float(): WEBGL_color_buffer_float | null { - return this._WEBGL_color_buffer_float; - } - - public get WEBGL_compressed_texture_astc(): WEBGL_compressed_texture_astc | null { - return this._WEBGL_compressed_texture_astc; - } - - public get WEBGL_compressed_texture_s3tc(): WEBGL_compressed_texture_s3tc | null { - return this._WEBGL_compressed_texture_s3tc; - } - - public get WEBGL_compressed_texture_s3tc_srgb(): WEBGL_compressed_texture_s3tc_srgb | null { - return this._WEBGL_compressed_texture_s3tc_srgb; - } - - public get WEBGL_debug_shaders(): WEBGL_debug_shaders | null { - return this._WEBGL_debug_shaders; - } - - public get WEBGL_draw_buffers(): WEBGL_draw_buffers | null { - return this._WEBGL_draw_buffers; - } - - public get WEBGL_lose_context(): WEBGL_lose_context | null { - return this._WEBGL_lose_context; - } - - public get WEBGL_depth_texture(): WEBGL_depth_texture | null { - return this._WEBGL_depth_texture; - } - - public get WEBGL_debug_renderer_info(): WEBGL_debug_renderer_info | null { - return this._WEBGL_debug_renderer_info; - } - - public get OES_texture_half_float(): OES_texture_half_float | null { - return this._OES_texture_half_float; - } - - public get OES_texture_half_float_linear(): OES_texture_half_float_linear | null { - return this._OES_texture_half_float_linear; - } - - public get OES_texture_float(): OES_texture_float | null { - return this._OES_texture_float; - } - - public get OES_standard_derivatives(): OES_standard_derivatives | null { - return this._OES_standard_derivatives; - } - - public get OES_element_index_uint(): OES_element_index_uint | null { - return this._OES_element_index_uint; - } - - public get ANGLE_instanced_arrays(): ANGLE_instanced_arrays | null { - return this._ANGLE_instanced_arrays; - } - - private initStates(gl: WebGLRenderingContext) { + private initStates (gl: WebGLRenderingContext) { gl.activeTexture(WebGLRenderingContext.TEXTURE0); gl.pixelStorei(WebGLRenderingContext.PACK_ALIGNMENT, 1); @@ -1025,30 +1045,4 @@ export class WebGLGFXDevice extends GFXDevice { gl.colorMask(true, true, true, true); gl.blendColor(0.0, 0.0, 0.0, 0.0); } - - private _webGLRC: WebGLRenderingContext | null = null; - private _isAntialias: boolean = true; - private _isPremultipliedAlpha: boolean = false; - - private _extensions: string[] | null = null; - private _EXT_texture_filter_anisotropic: EXT_texture_filter_anisotropic | null = null; - private _EXT_frag_depth: EXT_frag_depth | null = null; - private _EXT_shader_texture_lod: EXT_shader_texture_lod | null = null; - private _EXT_sRGB: EXT_sRGB | null = null; - private _OES_vertex_array_object: OES_vertex_array_object | null = null; - private _WEBGL_color_buffer_float: WEBGL_color_buffer_float | null = null; - private _WEBGL_compressed_texture_astc: WEBGL_compressed_texture_astc | null = null; - private _WEBGL_compressed_texture_s3tc: WEBGL_compressed_texture_s3tc | null = null; - private _WEBGL_compressed_texture_s3tc_srgb: WEBGL_compressed_texture_s3tc_srgb | null = null; - private _WEBGL_debug_shaders: WEBGL_debug_shaders | null = null; - private _WEBGL_draw_buffers: WEBGL_draw_buffers | null = null; - private _WEBGL_lose_context: WEBGL_lose_context | null = null; - private _WEBGL_depth_texture: WEBGL_depth_texture | null = null; - private _WEBGL_debug_renderer_info: WEBGL_debug_renderer_info | null = null; - private _OES_texture_half_float: OES_texture_half_float | null = null; - private _OES_texture_half_float_linear: OES_texture_half_float_linear | null = null; - private _OES_texture_float: OES_texture_float | null = null; - private _OES_standard_derivatives: OES_standard_derivatives | null = null; - private _OES_element_index_uint: OES_element_index_uint | null = null; - private _ANGLE_instanced_arrays: ANGLE_instanced_arrays | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index 2ca91f0ef0..67d6152b9d 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -1,46 +1,45 @@ import { GFXDevice } from '../device'; +import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXFramebuffer, GFXFramebufferInfo } from '../framebuffer'; import { WebGLGPUFramebuffer } from './webgl-gpu-objects'; export class WebGLGFXFramebuffer extends GFXFramebuffer { - constructor(device : GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuFramebuffer (): WebGLGPUFramebuffer { + return this._gpuFramebuffer as WebGLGPUFramebuffer; + } + + private _gpuFramebuffer: WebGLGPUFramebuffer | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info : GFXFramebufferInfo) : boolean { + public initialize (info: IGFXFramebufferInfo): boolean { this._renderPass = info.renderPass; - if(info.colorViews !== undefined) { + if (info.colorViews !== undefined) { this._colorViews = info.colorViews; } - this._depthStencilView = info.depthStencilView !== undefined? info.depthStencilView : null; - this._isOffscreen = info.isOffscreen !== undefined? info.isOffscreen : true; + this._depthStencilView = info.depthStencilView !== undefined ? info.depthStencilView : null; + this._isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; this._gpuFramebuffer = this.webGLDevice.emitCmdCreateGPUFramebuffer(info); return true; } - public destroy() { + public destroy () { - if(this._gpuFramebuffer) - { + if (this._gpuFramebuffer) { this.webGLDevice.emitCmdDestroyGPUFramebuffer(this._gpuFramebuffer); this._gpuFramebuffer = null; } } - - public get webGLDevice() : WebGLGFXDevice { - return this._device; - } - - public get gpuFramebuffer() : WebGLGPUFramebuffer { - return this._gpuFramebuffer; - } - - private _gpuFramebuffer : WebGLGPUFramebuffer | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 1f2ddcf769..68dcec205a 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,8 +1,8 @@ -import { GFXFormat, GFXType, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureFlags, GFXTextureFlagBit, GFXShaderType, GFXBindingType, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXMemoryUsage, GFXBufferUsage } from "../define"; -import { GFXColorAttachment, GFXDepthStencilAttachment } from "../render-pass"; -import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; -import { GFXInputAttribute } from "../input-assembler"; -import { GFXUniformBlock, GFXUniformSampler, GFXShaderMacro } from "../shader"; +import { GFXBindingType, GFXBufferUsage, GFXBufferUsageBit, GFXFormat, GFXMemoryUsage, GFXMemoryUsageBit, GFXShaderType, GFXTextureFlagBit, GFXTextureFlags, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureViewType, GFXType } from '../define'; +import { IGFXInputAttribute } from '../input-assembler'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../pipeline-state'; +import { GFXColorAttachment, GFXDepthStencilAttachment } from '../render-pass'; +import { GFXUniformBlock, GFXUniformSampler, IGFXShaderMacro } from '../shader'; export enum WebGLGPUObjectType { UNKNOWN, @@ -17,66 +17,66 @@ export enum WebGLGPUObjectType { BINDING_LAYOUT, INPUT_ASSEMBLER, COMMAND_BUFFER, -}; +} export class WebGLGPUObject { - objType: WebGLGPUObjectType; + public objType: WebGLGPUObjectType; - constructor(type: WebGLGPUObjectType) { + constructor (type: WebGLGPUObjectType) { this.objType = type; } -}; +} export class WebGLGPUBuffer extends WebGLGPUObject { - usage: GFXBufferUsage = GFXBufferUsageBit.NONE; - memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; - size: number = 0; - stride: number = 0; + public usage: GFXBufferUsage = GFXBufferUsageBit.NONE; + public memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; + public size: number = 0; + public stride: number = 0; - glTarget: GLenum = 0; - glBuffer: WebGLBuffer = 0; - buffer: ArrayBuffer | null = null; - viewUI8: Uint8Array | null = null; - viewF32: Float32Array | null = null; + public glTarget: GLenum = 0; + public glBuffer: WebGLBuffer = 0; + public buffer: ArrayBuffer | null = null; + public viewUI8: Uint8Array | null = null; + public viewF32: Float32Array | null = null; - constructor() { + constructor () { super(WebGLGPUObjectType.BUFFER); } -}; +} export class WebGLGPUTexture extends WebGLGPUObject { - type: GFXTextureType = GFXTextureType.TEX2D; - viewType: GFXTextureViewType = GFXTextureViewType.TV2D; - format: GFXFormat = GFXFormat.UNKNOWN; - usage: GFXTextureUsage = GFXTextureUsageBit.NONE; - width: number = 0; - height: number = 0; - depth: number = 1; - arrayLayer: number = 1; - mipLevel: number = 1; - flags: GFXTextureFlags = GFXTextureFlagBit.NONE; + public type: GFXTextureType = GFXTextureType.TEX2D; + public viewType: GFXTextureViewType = GFXTextureViewType.TV2D; + public format: GFXFormat = GFXFormat.UNKNOWN; + public usage: GFXTextureUsage = GFXTextureUsageBit.NONE; + public width: number = 0; + public height: number = 0; + public depth: number = 1; + public arrayLayer: number = 1; + public mipLevel: number = 1; + public flags: GFXTextureFlags = GFXTextureFlagBit.NONE; - glTarget: GLenum = 0; - glInternelFmt: GLenum = 0; - glFormat: GLenum = 0; - glType: GLenum = 0; - glUsage: GLenum = 0; - glTexture: WebGLTexture = 0; + public glTarget: GLenum = 0; + public glInternelFmt: GLenum = 0; + public glFormat: GLenum = 0; + public glType: GLenum = 0; + public glUsage: GLenum = 0; + public glTexture: WebGLTexture = 0; - constructor() { + constructor () { super(WebGLGPUObjectType.TEXTURE); } -}; +} export class WebGLGPUTextureView extends WebGLGPUObject { - gpuTexture: WebGLGPUTexture; - type: GFXTextureViewType = GFXTextureViewType.TV2D; - format: GFXFormat = GFXFormat.UNKNOWN; - baseLevel: number = 0; - levelCount: number = 1; + public gpuTexture: WebGLGPUTexture; + public type: GFXTextureViewType = GFXTextureViewType.TV2D; + public format: GFXFormat = GFXFormat.UNKNOWN; + public baseLevel: number = 0; + public levelCount: number = 1; - constructor(texture: WebGLGPUTexture) { + constructor (texture: WebGLGPUTexture) { super(WebGLGPUObjectType.TEXTURE_VIEW); this.gpuTexture = texture; } @@ -84,172 +84,172 @@ export class WebGLGPUTextureView extends WebGLGPUObject { export class WebGLGPURenderPass extends WebGLGPUObject { - colorAttachments: GFXColorAttachment[] = []; - depthStencilAttachment: GFXDepthStencilAttachment | null = null; + public colorAttachments: GFXColorAttachment[] = []; + public depthStencilAttachment: GFXDepthStencilAttachment | null = null; - constructor() { + constructor () { super(WebGLGPUObjectType.RENDER_PASS); } -}; +} export class WebGLGPUFramebuffer extends WebGLGPUObject { - gpuRenderPass: WebGLGPURenderPass; - gpuColorViews: WebGLGPUTextureView[] = []; - gpuDepthStencilView: WebGLGPUTextureView | null = null; - isOffscreen?: boolean = false; + public gpuRenderPass: WebGLGPURenderPass; + public gpuColorViews: WebGLGPUTextureView[] = []; + public gpuDepthStencilView: WebGLGPUTextureView | null = null; + public isOffscreen?: boolean = false; - glFramebuffer: WebGLFramebuffer = 0; + public glFramebuffer: WebGLFramebuffer = 0; - constructor(gpuRenderPass: WebGLGPURenderPass) { + constructor (gpuRenderPass: WebGLGPURenderPass) { super(WebGLGPUObjectType.FRAMEBUFFER); this.gpuRenderPass = gpuRenderPass; } -}; +} export class WebGLGPUSampler extends WebGLGPUObject { - glMinFilter: GLenum = WebGLRenderingContext.NONE; - glMagFilter: GLenum = WebGLRenderingContext.NONE; - glWrapS: GLenum = WebGLRenderingContext.NONE; - glWrapT: GLenum = WebGLRenderingContext.NONE; - glWrapR: GLenum = WebGLRenderingContext.NONE; + public glMinFilter: GLenum = WebGLRenderingContext.NONE; + public glMagFilter: GLenum = WebGLRenderingContext.NONE; + public glWrapS: GLenum = WebGLRenderingContext.NONE; + public glWrapT: GLenum = WebGLRenderingContext.NONE; + public glWrapR: GLenum = WebGLRenderingContext.NONE; - constructor() { + constructor () { super(WebGLGPUObjectType.SAMPLER); } -}; +} export class WebGLGPUInput { - binding: number = -1; - name: string = ""; - type: GFXType = GFXType.UNKNOWN; - stride: number = 0; - count: number = 0; - size: number = 0; + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public stride: number = 0; + public count: number = 0; + public size: number = 0; - glType: GLenum = 0; - glLoc: GLint = 0; -}; + public glType: GLenum = 0; + public glLoc: GLint = 0; +} export class WebGLGPUUniform { - binding: number = -1; - name: string = ""; - type: GFXType = GFXType.UNKNOWN; - stride: number = 0; - count: number = 0; - size: number = 0; - offset: number = 0; + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public stride: number = 0; + public count: number = 0; + public size: number = 0; + public offset: number = 0; - glType: GLenum = 0; - glLoc: WebGLUniformLocation = -1; - view: Float32Array | Int32Array | null = null; -}; + public glType: GLenum = 0; + public glLoc: WebGLUniformLocation = -1; + public view: Float32Array | Int32Array | null = null; +} export class WebGLGPUUniformBlock { - binding: number = -1; - name: string = ""; - size: number = 0; - glUniforms: WebGLGPUUniform[] = []; + public binding: number = -1; + public name: string = ''; + public size: number = 0; + public glUniforms: WebGLGPUUniform[] = []; - isUniformPackage: boolean = false; // Is a single uniform package? - buffer: ArrayBuffer | null = null; // for cache + public isUniformPackage: boolean = false; // Is a single uniform package? + public buffer: ArrayBuffer | null = null; // for cache } export class WebGLGPUUniformSampler { - binding: number = -1; - name: string = ""; - type: GFXType = GFXType.UNKNOWN; - units: number[] = []; + public binding: number = -1; + public name: string = ''; + public type: GFXType = GFXType.UNKNOWN; + public units: number[] = []; - glType: GLenum = 0; - glLoc: WebGLUniformLocation = -1; + public glType: GLenum = 0; + public glLoc: WebGLUniformLocation = -1; } export class WebGLGPUShaderStage { - type: GFXShaderType = GFXShaderType.VERTEX; - source: string = ""; - macros: GFXShaderMacro[] = []; - glShader: WebGLShader = 0; -}; + public type: GFXShaderType = GFXShaderType.VERTEX; + public source: string = ''; + public macros: IGFXShaderMacro[] = []; + public glShader: WebGLShader = 0; +} export class WebGLGPUShader extends WebGLGPUObject { - name: string = ""; - blocks: GFXUniformBlock[] = []; - samplers: GFXUniformSampler[] = []; + public name: string = ''; + public blocks: GFXUniformBlock[] = []; + public samplers: GFXUniformSampler[] = []; - gpuStages: WebGLGPUShaderStage[] = []; - glProgram: WebGLProgram = 0; - glInputs: WebGLGPUInput[] = []; - glUniforms: WebGLGPUUniform[] = []; - glBlocks: WebGLGPUUniformBlock[] = []; - glSamplers: WebGLGPUUniformSampler[] = []; + public gpuStages: WebGLGPUShaderStage[] = []; + public glProgram: WebGLProgram = 0; + public glInputs: WebGLGPUInput[] = []; + public glUniforms: WebGLGPUUniform[] = []; + public glBlocks: WebGLGPUUniformBlock[] = []; + public glSamplers: WebGLGPUUniformSampler[] = []; - constructor() { + constructor () { super(WebGLGPUObjectType.SHADER); } -}; +} export class WebGLGPUPipelineLayout extends WebGLGPUObject { -}; +} export class WebGLGPUPipelineState extends WebGLGPUObject { - glPrimitive: GLenum = WebGLRenderingContext.TRIANGLES; - gpuShader: WebGLGPUShader | null = null; - rs: GFXRasterizerState = new GFXRasterizerState; - dss: GFXDepthStencilState = new GFXDepthStencilState; - bs: GFXBlendState = new GFXBlendState; - gpuLayout: WebGLGPUPipelineLayout | null = null; - gpuRenderPass: WebGLGPURenderPass | null = null; + public glPrimitive: GLenum = WebGLRenderingContext.TRIANGLES; + public gpuShader: WebGLGPUShader | null = null; + public rs: GFXRasterizerState = new GFXRasterizerState(); + public dss: GFXDepthStencilState = new GFXDepthStencilState(); + public bs: GFXBlendState = new GFXBlendState(); + public gpuLayout: WebGLGPUPipelineLayout | null = null; + public gpuRenderPass: WebGLGPURenderPass | null = null; - constructor() { + constructor () { super(WebGLGPUObjectType.PIPELINE_STATE); } -}; +} export class WebGLGPUBinding { - binding: number = 0; - type: GFXBindingType = GFXBindingType.UNKNOWN; - name: string = ""; - gpuBuffer: WebGLGPUBuffer | null = null; - gpuTexView: WebGLGPUTextureView | null = null; - gpuSampler: WebGLGPUSampler | null = null; -}; + public binding: number = 0; + public type: GFXBindingType = GFXBindingType.UNKNOWN; + public name: string = ''; + public gpuBuffer: WebGLGPUBuffer | null = null; + public gpuTexView: WebGLGPUTextureView | null = null; + public gpuSampler: WebGLGPUSampler | null = null; +} export class WebGLGPUBindingLayout extends WebGLGPUObject { - gpuBindings: WebGLGPUBinding[] = []; + public gpuBindings: WebGLGPUBinding[] = []; - constructor() { + constructor () { super(WebGLGPUObjectType.BINDING_LAYOUT); } -}; +} export class WebGLAttrib { - name: string = ""; - glBuffer: WebGLBuffer = 0; - glType: GLenum = 0; - size: number = 0; - count: number = 0; - stride: number = 0; - componentCount: number = 1; - isNormalized: boolean = false; - isInstanced: boolean = false; - offset: number = 0; -}; + public name: string = ''; + public glBuffer: WebGLBuffer = 0; + public glType: GLenum = 0; + public size: number = 0; + public count: number = 0; + public stride: number = 0; + public componentCount: number = 1; + public isNormalized: boolean = false; + public isInstanced: boolean = false; + public offset: number = 0; +} export class WebGLGPUInputAssembler extends WebGLGPUObject { - attributes: GFXInputAttribute[] = []; - gpuVertexBuffers: WebGLGPUBuffer[] = []; - gpuIndexBuffer: WebGLGPUBuffer | null = null; + public attributes: IGFXInputAttribute[] = []; + public gpuVertexBuffers: WebGLGPUBuffer[] = []; + public gpuIndexBuffer: WebGLGPUBuffer | null = null; - glAttribs: WebGLAttrib[] = []; - glIndexType: GLenum = 0; - glVAO: WebGLVertexArrayObjectOES = 0; + public glAttribs: WebGLAttrib[] = []; + public glIndexType: GLenum = 0; + public glVAO: WebGLVertexArrayObjectOES = 0; - constructor() { + constructor () { super(WebGLGPUObjectType.INPUT_ASSEMBLER); } -}; +} diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index b6d47c1fa1..8973d9d33c 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -1,29 +1,39 @@ import { GFXDevice } from '../device'; -import { GFXInputAssembler, GFXInputAssemblerInfo } from '../input-assembler'; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUInputAssembler } from './webgl-gpu-objects'; export class WebGLGFXInputAssembler extends GFXInputAssembler { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuInputAssembler (): WebGLGPUInputAssembler { + return this._gpuInputAssembler as WebGLGPUInputAssembler; + } + + private _gpuInputAssembler: WebGLGPUInputAssembler | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXInputAssemblerInfo): boolean { - - if(info.vertexBuffers.length === 0) { - console.error("GFXInputAssemblerInfo.vertexBuffers is null."); + public initialize (info: IGFXInputAssemblerInfo): boolean { + + if (info.vertexBuffers.length === 0) { + console.error('GFXInputAssemblerInfo.vertexBuffers is null.'); return false; } this._attributes = info.attributes; this._vertexBuffers = info.vertexBuffers; - + if (info.indexBuffer !== undefined) { this._indexBuffer = info.indexBuffer; this._indexCount = this._indexBuffer.size / this._indexBuffer.stride; } else { - let vertBuff = this._vertexBuffers[0]; + const vertBuff = this._vertexBuffers[0]; this._vertexCount = vertBuff.size / vertBuff.stride; } @@ -36,20 +46,10 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { return true; } - public destroy() { + public destroy () { if (this._gpuInputAssembler) { this.webGLDevice.emitCmdDestroyGPUInputAssembler(this._gpuInputAssembler); this._gpuInputAssembler = null; } } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuInputAssembler(): WebGLGPUInputAssembler { - return this._gpuInputAssembler; - } - - private _gpuInputAssembler: WebGLGPUInputAssembler | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts index 75aeb0f5de..c085052818 100644 --- a/cocos/gfx/webgl/webgl-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -1,35 +1,35 @@ import { GFXDevice } from '../device'; +import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../pipeline-layout'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUPipelineLayout } from './webgl-gpu-objects'; -import { GFXPipelineLayout, GFXPipelineLayoutInfo } from '../pipeline-layout'; export class WebGLGFXPipelineLayout extends GFXPipelineLayout { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuPipelineLayout (): WebGLGPUPipelineLayout { + return this._gpuPipelineLayout as WebGLGPUPipelineLayout; + } + + private _gpuPipelineLayout: WebGLGPUPipelineLayout | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXPipelineLayoutInfo): boolean { + public initialize (info: IGFXPipelineLayoutInfo): boolean { this._layouts = info.layouts; - if(info.pushConstantsRanges !== undefined) { + if (info.pushConstantsRanges !== undefined) { this._pushConstantsRanges = info.pushConstantsRanges; } return true; } - public destroy() { + public destroy () { } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuPipelineLayout(): WebGLGPUPipelineLayout { - return this._gpuPipelineLayout; - } - - private _gpuPipelineLayout: WebGLGPUPipelineLayout | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts index f53d765f20..b9072080c5 100644 --- a/cocos/gfx/webgl/webgl-pipeline-state.ts +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -1,15 +1,25 @@ import { GFXDevice } from '../device'; -import { GFXPipelineState, GFXPipelineStateInfo } from '../pipeline-state'; +import { GFXPipelineState, IGFXPipelineStateInfo } from '../pipeline-state'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUPipelineState } from './webgl-gpu-objects'; export class WebGLGFXPipelineState extends GFXPipelineState { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuPipelineState (): WebGLGPUPipelineState { + return this._gpuPipelineState as WebGLGPUPipelineState; + } + + private _gpuPipelineState: WebGLGPUPipelineState | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXPipelineStateInfo): boolean { + public initialize (info: IGFXPipelineStateInfo): boolean { this._primitive = info.primitive; this._shader = info.shader; @@ -25,20 +35,10 @@ export class WebGLGFXPipelineState extends GFXPipelineState { return true; } - public destroy() { + public destroy () { if (this._gpuPipelineState) { this.webGLDevice.emitCmdDestroyGPUPipelineState(this._gpuPipelineState); this._gpuPipelineState = null; } } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuPipelineState(): WebGLGPUPipelineState { - return this._gpuPipelineState; - } - - private _gpuPipelineState: WebGLGPUPipelineState | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-queue.ts b/cocos/gfx/webgl/webgl-queue.ts index a6122ec847..f9d2463943 100644 --- a/cocos/gfx/webgl/webgl-queue.ts +++ b/cocos/gfx/webgl/webgl-queue.ts @@ -1,37 +1,36 @@ -import { GFXDevice } from '../device'; -import { GFXQueueInfo, GFXQueue } from '../queue'; import { GFXCommandBuffer } from '../command-buffer'; +import { GFXDevice } from '../device'; +import { GFXQueue, IGFXQueueInfo } from '../queue'; import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; import { WebGLCmdFuncExecuteCmds } from './webgl-commands'; import { WebGLGFXDevice } from './webgl-device'; export class WebGLGFXQueue extends GFXQueue { - constructor(device: GFXDevice) { + private _isAsync: boolean = false; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXQueueInfo): boolean { + public initialize (info: IGFXQueueInfo): boolean { this._type = info.type; return true; } - public destroy() { + public destroy () { } - public submit(cmdBuffs: GFXCommandBuffer[], fence?) { + public submit (cmdBuffs: GFXCommandBuffer[], fence?) { // TODO: Async if (!this._isAsync) { - for (let i = 0; i < cmdBuffs.length; ++i) { - let cmdBuff = cmdBuffs[i]; - WebGLCmdFuncExecuteCmds(this._device, cmdBuff.cmdPackage); + for (const cmdBuff of cmdBuffs) { + WebGLCmdFuncExecuteCmds( this._device as WebGLGFXDevice, (cmdBuff as WebGLGFXCommandBuffer).cmdPackage); } } } - - private _isAsync: boolean = false; -}; +} diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts index 90d778ae39..4fd5224035 100644 --- a/cocos/gfx/webgl/webgl-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -1,15 +1,25 @@ import { GFXDevice } from '../device'; -import { WebGLGPURenderPass } from './webgl-gpu-objects'; +import { GFXRenderPass, IGFXRenderPassInfo } from '../render-pass'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXRenderPass, GFXRenderPassInfo } from '../render-pass'; +import { WebGLGPURenderPass } from './webgl-gpu-objects'; export class WebGLGFXRenderPass extends GFXRenderPass { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuRenderPass (): WebGLGPURenderPass { + return this._gpuRenderPass as WebGLGPURenderPass; + } + + private _gpuRenderPass: WebGLGPURenderPass | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXRenderPassInfo): boolean { + public initialize (info: IGFXRenderPassInfo): boolean { if (info.colorAttachments !== undefined) { this._colorInfos = info.colorAttachments; @@ -24,21 +34,11 @@ export class WebGLGFXRenderPass extends GFXRenderPass { return true; } - public destroy() { + public destroy () { if (this._gpuRenderPass) { this.webGLDevice.emitCmdDestroyGPURenderPass(this._gpuRenderPass); this._gpuRenderPass = null; } } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuRenderPass(): WebGLGPURenderPass { - return this._gpuRenderPass; - } - - private _gpuRenderPass: WebGLGPURenderPass | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts index 372dd84c42..4f6d375535 100644 --- a/cocos/gfx/webgl/webgl-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -1,67 +1,77 @@ import { GFXDevice } from '../device'; -import { GFXSampler, GFXSamplerInfo, GFXSamplerState } from '../sampler'; +import { GFXSampler, GFXSamplerState, IGFXSamplerInfo } from '../sampler'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUSampler } from './webgl-gpu-objects'; export class WebGLGFXSampler extends GFXSampler { - constructor(device : GFXDevice) { - super(device); - - this._state = new GFXSamplerState; + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; } - public initialize(info : GFXSamplerInfo) : boolean { + public get gpuSampler (): WebGLGPUSampler { + return this._gpuSampler as WebGLGPUSampler; + } - if(info.name !== undefined) { + private _gpuSampler: WebGLGPUSampler | null = null; + + constructor (device: GFXDevice) { + super(device); + + this._state = new GFXSamplerState(); + } + + public initialize (info: IGFXSamplerInfo): boolean { + + if (info.name !== undefined) { this._state.name = info.name; } - if(info.minFilter !== undefined) { + if (info.minFilter !== undefined) { this._state.minFilter = info.minFilter; } - if(info.magFilter !== undefined) { + if (info.magFilter !== undefined) { this._state.magFilter = info.magFilter; } - if(info.mipFilter !== undefined) { + if (info.mipFilter !== undefined) { this._state.mipFilter = info.mipFilter; } - if(info.addressU !== undefined) { + if (info.addressU !== undefined) { this._state.addressU = info.addressU; } - if(info.addressV !== undefined) { + if (info.addressV !== undefined) { this._state.addressV = info.addressV; } - if(info.addressW !== undefined) { + if (info.addressW !== undefined) { this._state.addressW = info.addressW; } - if(info.maxAnisotropy !== undefined) { + if (info.maxAnisotropy !== undefined) { this._state.maxAnisotropy = info.maxAnisotropy; } - if(info.cmpFunc !== undefined) { + if (info.cmpFunc !== undefined) { this._state.cmpFunc = info.cmpFunc; } - if(info.borderColor !== undefined) { + if (info.borderColor !== undefined) { this._state.borderColor = info.borderColor; } - if(info.minLOD !== undefined) { + if (info.minLOD !== undefined) { this._state.minLOD = info.minLOD; } - if(info.maxLOD !== undefined) { + if (info.maxLOD !== undefined) { this._state.maxLOD = info.maxLOD; } - if(info.mipLODBias !== undefined) { + if (info.mipLODBias !== undefined) { this._state.mipLODBias = info.mipLODBias; } @@ -70,20 +80,10 @@ export class WebGLGFXSampler extends GFXSampler { return true; } - public destroy() { - if(this._gpuSampler) { + public destroy () { + if (this._gpuSampler) { this.webGLDevice.emitCmdDestroyGPUSampler(this._gpuSampler); this._gpuSampler = null; } } - - public get webGLDevice() : WebGLGFXDevice { - return this._device; - } - - public get gpuSampler() : WebGLGPUSampler { - return this._gpuSampler; - } - - private _gpuSampler : WebGLGPUSampler | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts index 2f5119686a..3aefb658b7 100644 --- a/cocos/gfx/webgl/webgl-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -1,24 +1,34 @@ import { GFXDevice } from '../device'; +import { GFXShader, IGFXShaderInfo } from '../shader'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXShader, GFXShaderInfo } from '../shader'; import { WebGLGPUShader } from './webgl-gpu-objects'; export class WebGLGFXShader extends GFXShader { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuShader (): WebGLGPUShader { + return this._gpuShader as WebGLGPUShader; + } + + private _gpuShader: WebGLGPUShader | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXShaderInfo): boolean { + public initialize (info: IGFXShaderInfo): boolean { this._name = info.name; this._stages = info.stages; - if(info.blocks !== undefined) { + if (info.blocks !== undefined) { this._blocks = info.blocks; } - if(info.samplers !== undefined) { + if (info.samplers !== undefined) { this._samplers = info.samplers; } @@ -27,20 +37,10 @@ export class WebGLGFXShader extends GFXShader { return true; } - public destroy() { + public destroy () { if (this._gpuShader) { this.webGLDevice.emitCmdDestroyGPUShader(this._gpuShader); this._gpuShader = null; } } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuShader(): WebGLGPUShader { - return this._gpuShader; - } - - private _gpuShader: WebGLGPUShader | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index f8a7476758..61cbfd1aff 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -1,61 +1,60 @@ -import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES, GFXViewport, GFXRect } from "../define"; -import { GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../pipeline-state"; +import { GFX_MAX_TEXTURE_UNITS, GFX_MAX_VERTEX_ATTRIBUTES, IGFXRect, IGFXViewport } from '../define'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../pipeline-state'; -export interface WebGLTexUnit -{ - glTexture : WebGLTexture; - minFilter : GLenum; - magFilter : GLenum; - wrapS : GLenum; - wrapT : GLenum; - wrapR : GLenum; - baseLevel : number; - maxLevel : number; -}; +export interface IWebGLTexUnit { + glTexture: WebGLTexture; + minFilter: GLenum; + magFilter: GLenum; + wrapS: GLenum; + wrapT: GLenum; + wrapR: GLenum; + baseLevel: number; + maxLevel: number; +} export class WebGLStateCache { - glArrayBuffer : WebGLBuffer = 0; - glElementArrayBuffer : WebGLBuffer = 0; - texUnit : number = 0; - glTex2DUnits : WebGLTexUnit[]; - glTexCubeUnits : WebGLTexUnit[]; - glFramebuffer : WebGLFramebuffer = 0; - viewport : GFXViewport; - scissorRect : GFXRect; - rs : GFXRasterizerState; - dss : GFXDepthStencilState; - bs : GFXBlendState; - glProgram : WebGLProgram = 0; - glEnabledAttribLocs : boolean[]; - glCurrentAttribLocs : boolean[]; + public glArrayBuffer: WebGLBuffer = 0; + public glElementArrayBuffer: WebGLBuffer = 0; + public texUnit: number = 0; + public glTex2DUnits: IWebGLTexUnit[]; + public glTexCubeUnits: IWebGLTexUnit[]; + public glFramebuffer: WebGLFramebuffer = 0; + public viewport: IGFXViewport; + public scissorRect: IGFXRect; + public rs: GFXRasterizerState; + public dss: GFXDepthStencilState; + public bs: GFXBlendState; + public glProgram: WebGLProgram = 0; + public glEnabledAttribLocs: boolean[]; + public glCurrentAttribLocs: boolean[]; - constructor() { - this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); - this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); - this.viewport = { left: 0.0, top: 0.0, width: 0.0, height: 0.0, minDepth: 0.0, maxDepth: 0.0}; - this.scissorRect = { x: 0.0, y: 0.0, width: 0.0, height: 0.0}; - this.rs = new GFXRasterizerState; - this.dss = new GFXDepthStencilState; - this.bs = new GFXBlendState; + constructor () { + this.glTex2DUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.glTexCubeUnits = new Array(GFX_MAX_TEXTURE_UNITS); + this.viewport = { left: 0.0, top: 0.0, width: 0.0, height: 0.0, minDepth: 0.0, maxDepth: 0.0 }; + this.scissorRect = { x: 0.0, y: 0.0, width: 0.0, height: 0.0 }; + this.rs = new GFXRasterizerState(); + this.dss = new GFXDepthStencilState(); + this.bs = new GFXBlendState(); this.glEnabledAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); this.glCurrentAttribLocs = new Array(GFX_MAX_VERTEX_ATTRIBUTES); - for(let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { + for (let i = 0; i < GFX_MAX_TEXTURE_UNITS; ++i) { this.glTex2DUnits[i] = { - glTexture : 0, - minFilter : WebGLRenderingContext.NONE, - magFilter : WebGLRenderingContext.NONE, - wrapS : WebGLRenderingContext.NONE, - wrapT : WebGLRenderingContext.NONE, - wrapR : WebGLRenderingContext.NONE, - baseLevel : 0, - maxLevel : 1000, - } + glTexture: 0, + minFilter: WebGLRenderingContext.NONE, + magFilter: WebGLRenderingContext.NONE, + wrapS: WebGLRenderingContext.NONE, + wrapT: WebGLRenderingContext.NONE, + wrapR: WebGLRenderingContext.NONE, + baseLevel: 0, + maxLevel: 1000, + }; } - for(let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { + for (let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { this.glEnabledAttribLocs[i] = false; this.glCurrentAttribLocs[i] = false; } } -}; +} diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts index 920169270a..64cc9d3214 100644 --- a/cocos/gfx/webgl/webgl-texture-view.ts +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -1,15 +1,25 @@ import { GFXDevice } from '../device'; -import { GFXTextureView, GFXTextureViewInfo } from '../texture-view'; -import { WebGLGPUTextureView } from './webgl-gpu-objects'; +import { GFXTextureView, IGFXTextureViewInfo } from '../texture-view'; import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUTextureView } from './webgl-gpu-objects'; export class WebGLGFXTextureView extends GFXTextureView { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuTextureView (): WebGLGPUTextureView { + return this._gpuTextureView as WebGLGPUTextureView; + } + + private _gpuTextureView: WebGLGPUTextureView | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXTextureViewInfo): boolean { + public initialize (info: IGFXTextureViewInfo): boolean { this._texture = info.texture; this._type = info.type; @@ -37,21 +47,11 @@ export class WebGLGFXTextureView extends GFXTextureView { return true; } - public destroy() { + public destroy () { if (this._gpuTextureView) { this.webGLDevice.emitCmdDestroyGPUTextureView(this._gpuTextureView); this._gpuTextureView = null; } this._texture = null; } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuTextureView(): WebGLGPUTextureView { - return this._gpuTextureView; - } - - private _gpuTextureView: WebGLGPUTextureView | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index fbef91e69d..61f056399b 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -1,16 +1,26 @@ -import { GFXDevice } from '../device'; -import { WebGLGPUTexture } from './webgl-gpu-objects'; -import { WebGLGFXDevice } from './webgl-device'; -import { GFXTexture, GFXTextureInfo } from '../texture'; import { GFXFormatSurfaceSize, GFXTextureFlagBit } from '../define'; +import { GFXDevice } from '../device'; +import { GFXTexture, IGFXTextureInfo } from '../texture'; +import { WebGLGFXDevice } from './webgl-device'; +import { WebGLGPUTexture } from './webgl-gpu-objects'; export class WebGLGFXTexture extends GFXTexture { - constructor(device: GFXDevice) { + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; + } + + public get gpuTexture (): WebGLGPUTexture { + return this._gpuTexture as WebGLGPUTexture; + } + + private _gpuTexture: WebGLGPUTexture | null = null; + + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXTextureInfo): boolean { + public initialize (info: IGFXTextureInfo): boolean { this._type = info.type; this._usage = info.usage; @@ -45,21 +55,11 @@ export class WebGLGFXTexture extends GFXTexture { return true; } - public destroy() { + public destroy () { if (this._gpuTexture) { this.webGLDevice.emitCmdDestroyGPUTexture(this._gpuTexture); this._gpuTexture = null; } } - - public get webGLDevice(): WebGLGFXDevice { - return this._device; - } - - public get gpuTexture(): WebGLGPUTexture { - return this._gpuTexture; - } - - private _gpuTexture: WebGLGPUTexture | null = null; -}; +} diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index 15fec7b617..e88a379998 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -1,25 +1,25 @@ +import { GFXFormat, GFXLoadOp, GFXStoreOp, GFXTextureFlagBit, GFXTextureLayout, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../define'; import { GFXDevice } from '../device'; +import { GFXWindow, IGFXWindowInfo } from '../window'; import { WebGLGFXDevice } from './webgl-device'; -import { GFXWindow, GFXWindowInfo } from '../window'; -import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXTextureLayout, GFXLoadOp, GFXStoreOp } from '../define'; export class WebGLGFXWindow extends GFXWindow { - constructor(device: GFXDevice) { + constructor (device: GFXDevice) { super(device); } - public initialize(info: GFXWindowInfo): boolean { + public initialize (info: IGFXWindowInfo): boolean { - if(info.title !== undefined) { + if (info.title !== undefined) { this._title = info.title; } - if(info.left !== undefined) { + if (info.left !== undefined) { this._left = info.left; } - if(info.top !== undefined) { + if (info.top !== undefined) { this._top = info.top; } @@ -49,7 +49,7 @@ export class WebGLGFXWindow extends GFXWindow { }, }); - if(!this._renderPass) { + if (!this._renderPass) { this.destroy(); return false; } @@ -119,15 +119,15 @@ export class WebGLGFXWindow extends GFXWindow { return false; } */ - + this._framebuffer = this._device.createFramebuffer({ renderPass: this._renderPass, - //colorViews: [this._colorTexView], - //depthStencilView: this._depthStencilTexView, + // colorViews: [this._colorTexView], + // depthStencilView: this._depthStencilTexView, isOffscreen: false, }); - if(!this._framebuffer) { + if (!this._framebuffer) { this.destroy(); return false; } @@ -135,7 +135,7 @@ export class WebGLGFXWindow extends GFXWindow { return true; } - public destroy() { + public destroy () { /* if(this._depthStencilTexView) { this._depthStencilTexView.destroy(); @@ -157,20 +157,20 @@ export class WebGLGFXWindow extends GFXWindow { this._colorTex = null; } */ - - if(this._framebuffer) { + + if (this._framebuffer) { this._framebuffer.destroy(); this._framebuffer = null; } - if(this._renderPass) { + if (this._renderPass) { this._renderPass.destroy(); this._renderPass = null; } } - public get webGLDevice(): WebGLGFXDevice { - return this._device; + public get webGLDevice (): WebGLGFXDevice { + return this._device as WebGLGFXDevice; } -}; +} diff --git a/cocos/gfx/window.ts b/cocos/gfx/window.ts index 81b9681634..b4d8b2ea60 100644 --- a/cocos/gfx/window.ts +++ b/cocos/gfx/window.ts @@ -1,11 +1,9 @@ +import { GFXFormat } from './define'; import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; -import { GFXTexture } from './texture'; -import { GFXTextureView } from './texture-view'; -import { GFXFormat } from './define'; import { GFXRenderPass } from './render-pass'; -export interface GFXWindowInfo { +export interface IGFXWindowInfo { title?: string; left?: number; top?: number; @@ -13,43 +11,36 @@ export interface GFXWindowInfo { height: number; colorFmt: GFXFormat; depthStencilFmt: GFXFormat; -}; +} export abstract class GFXWindow { - constructor(device: GFXDevice) { - this._device = device; - } - - public abstract initialize(info: GFXWindowInfo): boolean; - public abstract destroy(): void; - - public get width(): number { + public get width (): number { return this._width; } - public get height(): number { + public get height (): number { return this._height; } - public get colorFormat(): GFXFormat | null { + public get colorFormat (): GFXFormat | null { return this._colorFmt; } - public get detphStencilFormat(): GFXFormat | null { + public get detphStencilFormat (): GFXFormat | null { return this._depthStencilFmt; } - public get renderPass(): GFXRenderPass | null { + public get renderPass (): GFXRenderPass | null { return this._renderPass; } - public get framebuffer(): GFXFramebuffer | null { + public get framebuffer (): GFXFramebuffer | null { return this._framebuffer; } protected _device: GFXDevice; - protected _title: string = ""; + protected _title: string = ''; protected _left: number = 0; protected _top: number = 0; protected _width: number = 0; @@ -57,9 +48,16 @@ export abstract class GFXWindow { protected _colorFmt: GFXFormat = GFXFormat.UNKNOWN; protected _depthStencilFmt: GFXFormat = GFXFormat.UNKNOWN; protected _renderPass: GFXRenderPass | null = null; - //protected _colorTex: GFXTexture | null = null; - //protected _colorTexView: GFXTextureView | null = null; - //protected _depthStencilTex: GFXTexture | null = null; - //protected _depthStencilTexView: GFXTextureView | null = null; + // protected _colorTex: GFXTexture | null = null; + // protected _colorTexView: GFXTextureView | null = null; + // protected _depthStencilTex: GFXTexture | null = null; + // protected _depthStencilTexView: GFXTextureView | null = null; protected _framebuffer: GFXFramebuffer | null = null; -}; + + constructor (device: GFXDevice) { + this._device = device; + } + + public abstract initialize (info: IGFXWindowInfo): boolean; + public abstract destroy (): void; +} diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 860acf41b4..24328dda5e 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -34,21 +34,19 @@ export class ForwardFlow extends RenderFlow { }); /* */ - /* */ + /* this.createStage(TestMaterialStage, { name: 'TestMaterialStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ + */ - /* * this.createStage(TestStage, { name: 'TestStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ return true; } diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 1c8aec9925..0d115daa94 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -1,19 +1,19 @@ -import { RenderStage, RenderStageInfo } from "../render-stage"; -import { RenderFlow } from "../render-flow"; -import { GFXCommandBuffer } from "../../gfx/command-buffer"; -import { RenderView } from "../render-view"; -import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType, GFXShaderType, GFXPrimitiveMode, GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureFlagBit, GFXTextureViewType, GFXBufferUsageBit, GFXMemoryUsageBit, GFXTextureLayout, GFXBufferTextureCopy, GFXAddress, GFXFilter, GFXBindingType, GFXType, GFXCullMode } from "../../gfx/define"; -import { GFXPipelineState, GFXInputState, GFXRasterizerState, GFXDepthStencilState, GFXBlendState } from "../../gfx/pipeline-state"; -import { GFXShader } from "../../gfx/shader"; -import { GFXRenderPass } from "../../gfx/render-pass"; -import { GFXPipelineLayout } from "../../gfx/pipeline-layout"; -import { GFXBindingLayout } from "../../gfx/binding-layout"; -import { GFXTexture } from "../../gfx/texture"; -import { GFXTextureView } from "../../gfx/texture-view"; -import { GFXSampler } from "../../gfx/sampler"; -import { GFXBuffer } from "../../gfx/buffer"; -import { UBOGlobal } from "../render-pipeline"; +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 { RenderFlow } from '../render-flow'; +import { UBOGlobal } from '../render-pipeline'; +import { RenderStage, RenderStageInfo } from '../render-stage'; +import { RenderView } from '../render-view'; /* declare module '*.png' { @@ -21,10 +21,10 @@ declare module '*.png' { export = value; } */ -//declare function require(string): string; -//const image = require('../../../playground/cocos2d-x.png'); +// declare function require(string): string; +// const image = require('../../../playground/cocos2d-x.png'); -let _shader_vs = `#version 100 +const _shader_vs = `#version 100 attribute vec2 a_position; attribute vec2 a_texCoord; @@ -38,7 +38,7 @@ void main() { v_texCoord = a_texCoord; }`; -let _shader_fs = `#version 100 +const _shader_fs = `#version 100 precision highp float; varying vec2 v_texCoord; @@ -54,11 +54,25 @@ void main() { export class TestStage extends RenderStage { - constructor(flow: RenderFlow) { + 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: RenderStageInfo): boolean { + public initialize (info: RenderStageInfo): boolean { if (info.name !== undefined) { this._name = info.name; @@ -76,27 +90,27 @@ export class TestStage extends RenderStage { }); // create shader - let vsStage = { + const vsStage = { type: GFXShaderType.VERTEX, source: _shader_vs, }; - let fsStage = { + const fsStage = { type: GFXShaderType.FRAGMENT, source: _shader_fs, }; this._shader = this._device.createShader({ - name: "test", + name: 'test', stages: [vsStage, fsStage], blocks: [UBOGlobal.BLOCK, { - binding: 5, name: "UBO", members: [ - { name: "u_color", type: GFXType.FLOAT4, count: 1 }, - ] + binding: 5, name: 'UBO', members: [ + { name: 'u_color', type: GFXType.FLOAT4, count: 1 }, + ], }], samplers: [ - { binding: 10, name: "u_sampler", type: GFXType.SAMPLER2D, count: 1 } - ] + { binding: 10, name: 'u_sampler', type: GFXType.SAMPLER2D, count: 1 }, + ], }); if (!this._shader) { return false; @@ -104,9 +118,9 @@ export class TestStage extends RenderStage { this._bindingLayout = this._device.createBindingLayout({ bindings: [ - { binding: 0, type: GFXBindingType.UNIFORM_BUFFER, name: "Global" }, - { binding: 5, type: GFXBindingType.UNIFORM_BUFFER, name: "UBO" }, - { binding: 10, type: GFXBindingType.SAMPLER, name: "u_sampler" }, + { 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) { @@ -114,7 +128,7 @@ export class TestStage extends RenderStage { } this._pipelineLayout = this._device.createPipelineLayout({ - layouts: [this._bindingLayout] + layouts: [this._bindingLayout], }); if (!this._pipelineLayout) { return false; @@ -124,24 +138,24 @@ export class TestStage extends RenderStage { return false; } - let is: GFXInputState = { attributes: this._pipeline.quadIA.attributes }; + 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: is, + is, rs: this._rs, dss: this._dss, bs: this._bs, layout: this._pipelineLayout, - renderPass: this._framebuffer.renderPass, + renderPass: this._framebuffer.renderPass as GFXRenderPass, }); // create ubo - let color = [1.0, 0.3, 0.3, 1.0]; - let uboStride = color.length * 4; + 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, @@ -153,7 +167,7 @@ export class TestStage extends RenderStage { return false; } - let uboView = new Float32Array(4); + const uboView = new Float32Array(4); uboView[0] = 1.0; uboView[1] = 0.3; uboView[2] = 0.3; @@ -161,22 +175,22 @@ export class TestStage extends RenderStage { this._ubo.update(uboView); // load texture - let imgElms = this._device.canvas.getElementsByTagName("img"); + const imgElms = this._device.canvas.getElementsByTagName('img'); if (imgElms.length) { - if (!this.loadTexture(imgElms[0])) { - console.error("Load texture failed."); + 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."); + console.error('Not found image, load texture failed.'); } return true; } - public destroy() { + public destroy () { if (this._shader) { this._shader.destroy(); @@ -219,15 +233,15 @@ export class TestStage extends RenderStage { } } - public render(view: RenderView) { - let cmdBuff = this._cmdBuff; + public render (view: RenderView) { + const cmdBuff = this._cmdBuff as GFXCommandBuffer; this._renderArea.width = view.width; this._renderArea.height = view.height; cmdBuff.begin(); - cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); - cmdBuff.bindPipelineState(this._pipelineState); - cmdBuff.bindBindingLayout(this._bindingLayout); + 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(); @@ -236,8 +250,8 @@ export class TestStage extends RenderStage { this._device.queue.submit([cmdBuff]); } - private loadTexture(image: HTMLImageElement): boolean { - //let canvas2d = this._device.canvas.getContext("2d"); + private loadTexture (image: HTMLImageElement): boolean { + // let canvas2d = this._device.canvas.getContext("2d"); /* let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); @@ -276,7 +290,7 @@ export class TestStage extends RenderStage { return false; } - let region: GFXBufferTextureCopy = { + const region: GFXBufferTextureCopy = { buffOffset: 0, buffStride: 0, buffTexHeight: 0, @@ -286,7 +300,7 @@ export class TestStage extends RenderStage { }; this._device.copyImageSourceToTexture(image, this._texture, [region]); - //this._device.copyBufferToTexture(imgBuffer, this._texture, [region]); + // this._device.copyBufferToTexture(imgBuffer, this._texture, [region]); this._sampler = this._device.createSampler({ minFilter: GFXFilter.LINEAR, @@ -299,32 +313,18 @@ export class TestStage extends RenderStage { return true; } - private bindBindings(): boolean { + private bindBindings (): boolean { if (!this._bindingLayout) { return false; } this._bindingLayout.bindBuffer(0, this.pipeline.globalUBO); - this._bindingLayout.bindBuffer(5, this._ubo); - this._bindingLayout.bindTextureView(10, this._texView); - this._bindingLayout.bindSampler(10, this._sampler); + 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; } - - 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; -}; +} diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index d8bd058c91..27e03c2603 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,19 +1,19 @@ +import { intersect } from '../3d/geom-utils'; import { Root } from '../core/root'; +import { vec3 } from '../core/vmath'; import mat4 from '../core/vmath/mat4'; import { GFXBuffer } from '../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXType } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; -import { GFXInputAssembler, GFXInputAttribute } from '../gfx/input-assembler'; +import { GFXInputAssembler, IGFXInputAttribute } from '../gfx/input-assembler'; import { GFXRenderPass } from '../gfx/render-pass'; +import { GFXUniformBlock } from '../gfx/shader'; import { GFXTexture } from '../gfx/texture'; import { GFXTextureView } from '../gfx/texture-view'; import { Camera } from '../renderer/scene/camera'; import { RenderFlow, RenderFlowInfo } from './render-flow'; -import { RenderView } from './render-view'; -import { vec3 } from '../core/vmath'; import { RenderQueue } from './render-queue'; -import { intersect } from '../3d/geom-utils'; -import { GFXUniformBlock } from '../gfx/shader'; +import { RenderView } from './render-view'; export enum RenderPassStage { DEFAULT = 100, @@ -34,18 +34,18 @@ export class UBOGlobal { public static SIZE: number = UBOGlobal.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 0, name: "Global", members: [ - { name: "u_time", type: GFXType.FLOAT4, count: 1 }, - { name: "u_screenSize", type: GFXType.FLOAT4, count: 1 }, - { name: "u_screenScale", type: GFXType.FLOAT4, count: 1 }, - { name: "u_matView", type: GFXType.MAT4, count: 1 }, - { name: "u_matViewInv", type: GFXType.MAT4, count: 1 }, - { name: "u_matProj", type: GFXType.MAT4, count: 1 }, - { name: "u_matProjInv", type: GFXType.MAT4, count: 1 }, - { name: "u_matViewProj", type: GFXType.MAT4, count: 1 }, - { name: "u_matViewProjInv", type: GFXType.MAT4, count: 1 }, - { name: "u_cameraPos", type: GFXType.FLOAT4, count: 1 }, - ] + binding: 0, name: 'Global', members: [ + { name: 'u_time', type: GFXType.FLOAT4, count: 1 }, + { name: 'u_screenSize', type: GFXType.FLOAT4, count: 1 }, + { name: 'u_screenScale', type: GFXType.FLOAT4, count: 1 }, + { name: 'u_matView', type: GFXType.MAT4, count: 1 }, + { name: 'u_matViewInv', type: GFXType.MAT4, count: 1 }, + { name: 'u_matProj', type: GFXType.MAT4, count: 1 }, + { name: 'u_matProjInv', type: GFXType.MAT4, count: 1 }, + { name: 'u_matViewProj', type: GFXType.MAT4, count: 1 }, + { name: 'u_matViewProjInv', type: GFXType.MAT4, count: 1 }, + { name: 'u_cameraPos', type: GFXType.FLOAT4, count: 1 }, + ], }; public view: Float32Array = new Float32Array(UBOGlobal.COUNT); @@ -60,12 +60,12 @@ export class UBOLocal { public static SIZE: number = UBOLocal.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 1, name: "Local", members: [ - { name: "u_matWorld", type: GFXType.MAT4, count: 1 }, - { name: "u_matWorldView", type: GFXType.MAT4, count: 1 }, - { name: "u_matWorldViewProj", type: GFXType.MAT4, count: 1 }, - { name: "u_worldPos", type: GFXType.FLOAT4, count: 1 }, - ] + binding: 1, name: 'Local', members: [ + { name: 'u_matWorld', type: GFXType.MAT4, count: 1 }, + { name: 'u_matWorldView', type: GFXType.MAT4, count: 1 }, + { name: 'u_matWorldViewProj', type: GFXType.MAT4, count: 1 }, + { name: 'u_worldPos', type: GFXType.FLOAT4, count: 1 }, + ], }; public view: Float32Array = new Float32Array(UBOLocal.COUNT); @@ -73,39 +73,39 @@ export class UBOLocal { const _vec4Array = new Float32Array(4); const _mat4Array = new Float32Array(16); -const _outMat = new mat4; +const _outMat = new mat4(); export abstract class RenderPipeline { - public get root(): Root { + public get root (): Root { return this._root; } - public get device(): GFXDevice { + public get device (): GFXDevice { return this._device; } - public get queue(): RenderQueue { + public get queue (): RenderQueue { return this._queue; } - public get flows(): RenderFlow[] { + public get flows (): RenderFlow[] { return this._flows; } - public get quadIA(): GFXInputAssembler { + public get quadIA (): GFXInputAssembler { return this._quadIA as GFXInputAssembler; } - public get uboGlobal(): UBOGlobal { + public get uboGlobal (): UBOGlobal { return this._uboGlobal; } - public get globalUBO(): GFXBuffer { + public get globalUBO (): GFXBuffer { return this._globalUBO as GFXBuffer; } - public get defaultTexture(): GFXTexture { + public get defaultTexture (): GFXTexture { return this._defaultTex as GFXTexture; } @@ -122,15 +122,15 @@ export abstract class RenderPipeline { protected _defaultTex: GFXTexture | null = null; protected _defaultTexView: GFXTextureView | null = null; - constructor(root: Root) { + constructor (root: Root) { this._root = root; this._device = root.device; } - public abstract initialize(): boolean; - public abstract destroy(); + public abstract initialize (): boolean; + public abstract destroy (); - public render(view: RenderView) { + public render (view: RenderView) { view.camera.update(); @@ -138,18 +138,18 @@ export abstract class RenderPipeline { this.updateUBOs(view); - for (let i = 0; i < this._flows.length; ++i) { - this._flows[i].render(view); + for (const flow of this._flows) { + flow.render(view); } } - public addRenderPass(stage: number, renderPass: GFXRenderPass) { + public addRenderPass (stage: number, renderPass: GFXRenderPass) { if (renderPass) { this._renderPasses.set(stage, renderPass); } } - public getRenderPass(stage: number): GFXRenderPass | null { + public getRenderPass (stage: number): GFXRenderPass | null { const renderPass = this._renderPasses.get(stage); if (renderPass) { return renderPass; @@ -158,15 +158,15 @@ export abstract class RenderPipeline { } } - public removeRenderPass(stage: number) { + public removeRenderPass (stage: number) { this._renderPasses.delete(stage); } - public clearRenderPasses() { + public clearRenderPasses () { this._renderPasses.clear(); } - public createFlow(clazz: new (pipeline: RenderPipeline) => T, info: RenderFlowInfo): RenderFlow | null { + public createFlow (clazz: new (pipeline: RenderPipeline) => T, info: RenderFlowInfo): RenderFlow | null { const flow: RenderFlow = new clazz(this); if (flow.initialize(info)) { this._flows.push(flow); @@ -180,14 +180,14 @@ export abstract class RenderPipeline { } } - public destroyFlows() { + public destroyFlows () { for (const flow of this._flows) { flow.destroy(); } this._flows = []; } - protected createQuadInputAssembler(): boolean { + protected createQuadInputAssembler (): boolean { // create vertex buffer @@ -237,7 +237,7 @@ export abstract class RenderPipeline { // create input assembler - const attributes: GFXInputAttribute[] = [ + const attributes: IGFXInputAttribute[] = [ { name: 'a_position', format: GFXFormat.RG32F }, { name: 'a_texCoord', format: GFXFormat.RG32F }, ]; @@ -251,7 +251,7 @@ export abstract class RenderPipeline { return true; } - protected destroyQuadInputAssembler() { + protected destroyQuadInputAssembler () { if (this._quadVB) { this._quadVB.destroy(); this._quadVB = null; @@ -268,7 +268,7 @@ export abstract class RenderPipeline { } } - protected createUBOs(): boolean { + protected createUBOs (): boolean { this._globalUBO = this._root.device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST, @@ -282,14 +282,14 @@ export abstract class RenderPipeline { return true; } - protected destroyUBOs() { + protected destroyUBOs () { if (this._globalUBO) { this._globalUBO.destroy(); this._globalUBO = null; } } - protected updateUBOs(view: RenderView) { + protected updateUBOs (view: RenderView) { const camera = view.camera as Camera; camera.update(); @@ -340,12 +340,12 @@ export abstract class RenderPipeline { (this._globalUBO as GFXBuffer).update(this._uboGlobal.view); } - protected sceneCulling(view: RenderView) { + protected sceneCulling (view: RenderView) { - let scene = view.scene; - let camera = view.camera; + const scene = view.scene; + const camera = view.camera; - for (let model of scene.models) { + for (const model of scene.models) { // filter model by view visibility if (view.visibility > 0 && model._viewID !== view.visibility) { diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index 102eb54468..b2d2ba2106 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -5,7 +5,7 @@ import { GFXCommandBuffer } from "../gfx/command-buffer"; import { RenderFlow } from "./render-flow"; import { GFXDevice } from "../gfx/device"; import { RenderPipeline } from "./render-pipeline"; -import { GFXColor, GFXRect } from "../gfx/define"; +import { IGFXColor, IGFXRect } from "../gfx/define"; export interface RenderStageInfo { name?: string; @@ -33,7 +33,7 @@ export abstract class RenderStage { public abstract destroy(); public abstract render(view: RenderView); - public setClearColor(color: GFXColor) { + public setClearColor(color: IGFXColor) { if (this._clearColors.length > 0) { this._clearColors[0] = color; } else { @@ -41,7 +41,7 @@ export abstract class RenderStage { } } - public setClearColors(colors: GFXColor[]) { + public setClearColors(colors: IGFXColor[]) { this._clearColors = colors; } @@ -81,8 +81,8 @@ export abstract class RenderStage { protected _priority: number = 0; protected _framebuffer: GFXFramebuffer | null = null; protected _cmdBuff: GFXCommandBuffer | null = null; - protected _clearColors: GFXColor[]; + protected _clearColors: IGFXColor[]; protected _clearDepth: number = 1.0; protected _clearStencil: number = 0; - protected _renderArea: GFXRect; + protected _renderArea: IGFXRect; }; diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 7e5840880a..3cffb6da03 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { aabb } from '../../3d/geom-utils'; -import { GFXInputAttribute, GFXInputAssembler } from '../../gfx/input-assembler'; +import { IGFXInputAttribute, GFXInputAssembler } from '../../gfx/input-assembler'; import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit, GFXCommandBufferType } from '../../gfx/define'; import { RenderScene } from './render-scene'; import { vec3 } from '../../core/vmath'; diff --git a/tslint.json b/tslint.json index c301dca5b8..5d13d3afe5 100644 --- a/tslint.json +++ b/tslint.json @@ -5,14 +5,19 @@ ], "jsRules": {}, "rules": { - "quotemark": [ true, "single" ], + "quotemark": [ + true, + "single" + ], "no-console": false, "space-before-function-paren": true, "max-classes-per-file": false, "variable-name": false, "object-literal-sort-keys": false, "ban-types": false, - "no-bitwise": false + "no-bitwise": false, + "max-line-length": false, + "no-empty": false }, "rulesDirectory": [] -} +} \ No newline at end of file From 0ff6e0fa04a78fd077cd8fbaae0a7bc968f4696d Mon Sep 17 00:00:00 2001 From: Leslie Date: Wed, 9 Jan 2019 17:11:18 +0800 Subject: [PATCH 070/267] fix tex size error --- cocos/3d/assets/texture-cube.ts | 36 ++++------ cocos/assets/texture-2d.ts | 32 +++------ cocos/assets/texture-base.ts | 43 ++++++------ cocos/pipeline/forward/test-material-stage.ts | 65 +++++++++++-------- 4 files changed, 82 insertions(+), 94 deletions(-) diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 9a9ce7ccb3..43f5f423db 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -28,6 +28,7 @@ import ImageAsset from '../../assets/image-asset'; import TextureBase from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; +import { GFXDevice } from '../../gfx/device'; interface ITextureCubeMipmap { front: ImageAsset; @@ -53,7 +54,14 @@ export default class TextureCube extends TextureBase { */ set mipmaps (value) { this._mipmaps = value; + this._potientialWidth = value.length === 0 ? 0 : value[0].front.width; + this._potientialHeight = value.length === 0 ? 0 : value[0].front.height; this._recreateTexture(); + this._mipmaps.forEach((mipmap, level) => { + _forEachFace(mipmap, (face, faceIndex) => { + this._assignImage(face, level, faceIndex); + }); + }); } /** @@ -163,45 +171,25 @@ export default class TextureCube extends TextureBase { } } - protected _createTexture () { - if (this._mipmaps.length === 0) { - return; - } - - const gfxDevice = this._getGlobalDevice(); - if (!gfxDevice) { - return; - } - + protected _createTextureImpl (gfxDevice: GFXDevice) { this._texture = gfxDevice.createTexture({ type: GFXTextureType.TEX2D, /* tslint:disable:no-bitwise */ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, /* tslint:enable:no-bitwise */ format: this._getGfxFormat(), - width: this.width, - height: this.height, + width: this._potientialWidth, + height: this._potientialHeight, mipLevel: this._mipmaps.length, arrayLayer: 6, }); - - this._mipmaps.forEach((mipmap, level) => { - _forEachFace(mipmap, (face, faceIndex) => { - this._assignImage(face, level, faceIndex); - }); - }); } - protected _createTextureView () { + protected _createTextureViewImpl (gfxDevice: GFXDevice) { if (!this._texture) { return; } - const gfxDevice = this._getGlobalDevice(); - if (!gfxDevice) { - return; - } - this._textureView = gfxDevice.createTextureView({ texture: this._texture, type: GFXTextureViewType.TV2D_ARRAY, diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index faf0eff38d..4cc7b76b9c 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -26,6 +26,7 @@ // @ts-check import { ccclass, property } from '../core/data/class-decorator'; import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; +import { GFXDevice } from '../gfx/device'; import ImageAsset from './image-asset'; import TextureBase from './texture-base'; @@ -47,7 +48,12 @@ export default class Texture2D extends TextureBase { */ set mipmaps (value) { this._mipmaps = value; + this._potientialWidth = value.length === 0 ? 0 : value[0].width; + this._potientialHeight = value.length === 0 ? 0 : value[0].height; this._recreateTexture(); + this._mipmaps.forEach((mipmap, level) => { + this._assignImage(mipmap, level); + }); } /** @@ -175,42 +181,24 @@ export default class Texture2D extends TextureBase { } } - protected _createTexture () { - if (this._mipmaps.length === 0) { - return; - } - - const gfxDevice = this._getGlobalDevice(); - if (!gfxDevice) { - return; - } - + protected _createTextureImpl (gfxDevice: GFXDevice) { this._texture = gfxDevice.createTexture({ type: GFXTextureType.TEX2D, /* tslint:disable:no-bitwise */ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, /* tslint:enable:no-bitwise */ format: this._getGfxFormat(), - width: this.width, - height: this.height, + width: this._potientialWidth, + height: this._potientialHeight, mipLevel: this._mipmaps.length, }); - - this._mipmaps.forEach((mipmap, level) => { - this._assignImage(mipmap, level); - }); } - protected _createTextureView () { + protected _createTextureViewImpl (gfxDevice: GFXDevice) { if (!this._texture) { return; } - const gfxDevice = this._getGlobalDevice(); - if (!gfxDevice) { - return; - } - this._textureView = gfxDevice.createTextureView({ texture: this._texture, type: GFXTextureViewType.TV2D, diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index fb0a4cdf93..2b4ab8881b 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -63,11 +63,11 @@ export enum PixelFormat { /** * 24-bit texture: RGB888 */ - RGB888 = GFXFormat.RGB8UI, + RGB888 = GFXFormat.RGB8, /** * 32-bit texture: RGBA8888 */ - RGBA8888 = GFXFormat.RGBA8UI, + RGBA8888 = GFXFormat.RGBA8, /** * 32-bit float texture: RGBA32F */ @@ -75,15 +75,15 @@ export enum PixelFormat { /** * 8-bit textures used as masks */ - A8 = GFXFormat.R8UI, + A8 = GFXFormat.A8, /** * 8-bit intensity texture */ - I8 = GFXFormat.R8UI, + I8 = GFXFormat.L8, /** * 16-bit textures used as masks */ - AI8 = GFXFormat.RG8UI, + AI8 = GFXFormat.LA8, /** * rgb 2 bpp pvrtc */ @@ -165,11 +165,9 @@ export default class TextureBase extends Asset { * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width. * !#zh * 贴图像素宽度 - * @property width - * @type {Number} */ public get width (): number { - return this._width; + return this._texture ? this._texture.width : 0; } /** @@ -179,11 +177,9 @@ export default class TextureBase extends Asset { * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height. * !#zh * 贴图像素高度 - * @property height - * @type {Number} */ public get height (): number { - return this._height; + return this._texture ? this._texture.height : 0; } public static PixelFormat = PixelFormat; @@ -204,6 +200,10 @@ export default class TextureBase extends Asset { protected _textureView: GFXTextureView | null = null; + protected _potientialWidth: number = 0; + + protected _potientialHeight: number = 0; + @property private _genMipmap = false; @@ -234,10 +234,6 @@ export default class TextureBase extends Asset { @property private _anisotropy = 1; - private _width: number = 0; - - private _height: number = 0; - private _sampler: GFXSampler | null = null; private _id: string; @@ -549,19 +545,22 @@ export default class TextureBase extends Asset { protected _recreateTexture () { this._destroyTexture(); - this._createTexture(); - if (this._texture) { - this._width = this._texture.width; - this._height = this._texture.height; + + const gfxDevice = this._getGlobalDevice(); + if (!gfxDevice) { + return; } - this._createTextureView(); + + this._createTextureImpl(gfxDevice); + + this._createTextureViewImpl(gfxDevice); } - protected _createTexture () { + protected _createTextureImpl (gfxDevice: GFXDevice) { return; } - protected _createTextureView () { + protected _createTextureViewImpl (gfxDevice: GFXDevice) { return; } diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index 56f99511df..68b22e0a0a 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -9,6 +9,8 @@ import { GFXTextureView } from '../../gfx/texture-view'; import { RenderFlow } from '../render-flow'; import { RenderStage, RenderStageInfo } from '../render-stage'; import { RenderView } from '../render-view'; +import Texture2D from '../../assets/texture-2d'; +import ImageAsset from '../../assets/image-asset'; export class TestMaterialStage extends RenderStage { @@ -113,40 +115,51 @@ export class TestMaterialStage extends RenderStage { } private loadTexture (image: HTMLImageElement): boolean { - 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, - }); + // 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]); + + const textureAsset = new Texture2D(); + textureAsset.image = new ImageAsset(image); + this._texture = textureAsset.getGFXTexture(); if (!this._texture) { return false; } - - this._texView = this._device.createTextureView({ - texture: this._texture, - type: GFXTextureViewType.TV2D, - format: GFXFormat.RGBA8, - }); - + this._texView = textureAsset.getGFXTextureView(); 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]); - return true; } } From cfa1fd03aa6cb986092f3364f9004e2ace981a75 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 9 Jan 2019 17:34:49 +0800 Subject: [PATCH 071/267] optimize shader uniform update, reduce no-active uniform loop --- cocos/gfx/webgl/webgl-commands.ts | 393 ++++++++++++++------------- cocos/gfx/webgl/webgl-gpu-objects.ts | 1 + 2 files changed, 202 insertions(+), 192 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 81dc054a79..8f29fe8ecd 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -897,6 +897,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web name: block.name, size: 0, glUniforms: new Array(block.members.length), + glActiveUniforms: [], isUniformPackage: true, buffer: null, }; @@ -1001,6 +1002,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } } + glBlock.glActiveUniforms.push(glUniform); + break; } } @@ -1538,202 +1541,208 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (glBlock && gpuBinding.gpuBuffer.viewF32) { const vf32 = gpuBinding.gpuBuffer.viewF32; - for (const glUniform of glBlock.glUniforms) { - if (glUniform.glLoc && glUniform.view) { + for (const glUniform of glBlock.glActiveUniforms) { + let offset = glUniform.offset / 4; - let offset = glUniform.offset / 4; - - switch (glUniform.glType) { - case WebGLRenderingContext.BOOL: - case WebGLRenderingContext.INT: { - for (let m = 0; m < glUniform.count; ++m, ++offset) { - if (vf32[offset] !== glUniform.view[m]) { - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); - gl.uniform1iv(glUniform.glLoc, glUniform.view as Int32Array); - glUniform.view[m] = vf32[offset]; - break; - } + switch (glUniform.glType) { + case WebGLRenderingContext.BOOL: + case WebGLRenderingContext.INT: { + const view = glUniform.view as Int32Array; + for (let m = 0; m < glUniform.count; ++m, ++offset) { + if (vf32[offset] !== view[m]) { + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + glUniform.count)); + gl.uniform1iv(glUniform.glLoc, view); + break; } - break; } - case WebGLRenderingContext.BOOL_VEC2: - case WebGLRenderingContext.INT_VEC2: { - for (let m = 0; m < glUniform.count; ++m, offset += 2) { - const idx = 2 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1]) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); - gl.uniform2iv(glUniform.glLoc, glUniform.view as Int32Array); - break; - } - } - break; - } - case WebGLRenderingContext.BOOL_VEC3: - case WebGLRenderingContext.INT_VEC3: { - for (let m = 0; m < glUniform.count; ++m, offset += 3) { - const idx = 3 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2]) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); - gl.uniform3iv(glUniform.glLoc, glUniform.view as Int32Array); - break; - } - } - break; - } - case WebGLRenderingContext.BOOL_VEC4: - case WebGLRenderingContext.INT_VEC4: { - for (let m = 0; m < glUniform.count; ++m, offset += 4) { - const idx = 4 * m; - if (vf32[offset] !== glUniform.view[idx] || - vf32[offset + 1] !== glUniform.view[idx + 1] || - vf32[offset + 2] !== glUniform.view[idx + 2] || - vf32[offset + 3] !== glUniform.view[idx + 3]) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniform4iv(glUniform.glLoc, glUniform.view as Int32Array); - break; - } - } - break; - } - case WebGLRenderingContext.FLOAT: { - for (let m = 0; m < glUniform.count; ++m, ++offset) { - const c: number = 0; - - if (CmpF32NotEuqal(vf32[offset], glUniform.view[m])) { - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + glUniform.count)); - gl.uniform1fv(glUniform.glLoc, glUniform.view as Float32Array); - break; - } - } - break; - } - case WebGLRenderingContext.FLOAT_VEC2: { - for (let m = 0; m < glUniform.count; ++m, offset += 2) { - const idx = 2 * m; - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1])) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); - gl.uniform2fv(glUniform.glLoc, glUniform.view as Float32Array); - break; - } - } - break; - } - case WebGLRenderingContext.FLOAT_VEC3: { - for (let m = 0; m < glUniform.count; ++m, offset += 3) { - const idx = 3 * m; - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2])) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); - gl.uniform3fv(glUniform.glLoc, glUniform.view as Float32Array); - break; - } - - } - break; - } - case WebGLRenderingContext.FLOAT_VEC4: { - for (let m = 0; m < glUniform.count; ++m, offset += 4) { - const idx = 4 * m; - - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3])) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniform4fv(glUniform.glLoc, glUniform.view as Float32Array); - break; - } - } - break; - } - case WebGLRenderingContext.FLOAT_MAT2: { - for (let m = 0; m < glUniform.count; ++m, offset += 4) { - const idx = 4 * m; - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3])) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.view as Float32Array); - break; - } - } - break; - } - case WebGLRenderingContext.FLOAT_MAT3: { - for (let m = 0; m < glUniform.count; ++m, offset += 9) { - const idx = 9 * m; - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3]) || - CmpF32NotEuqal(vf32[offset + 4], glUniform.view[idx + 4]) || - CmpF32NotEuqal(vf32[offset + 5], glUniform.view[idx + 5]) || - CmpF32NotEuqal(vf32[offset + 6], glUniform.view[idx + 6]) || - CmpF32NotEuqal(vf32[offset + 7], glUniform.view[idx + 7]) || - CmpF32NotEuqal(vf32[offset + 8], glUniform.view[idx + 8])) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 9 * glUniform.count)); - gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.view as Float32Array); - break; - } - } - break; - } - case WebGLRenderingContext.FLOAT_MAT4: { - for (let m = 0; m < glUniform.count; ++m, offset += 16) { - const idx = 16 * m; - - if (CmpF32NotEuqal(vf32[offset], glUniform.view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], glUniform.view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], glUniform.view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], glUniform.view[idx + 3]) || - CmpF32NotEuqal(vf32[offset + 4], glUniform.view[idx + 4]) || - CmpF32NotEuqal(vf32[offset + 5], glUniform.view[idx + 5]) || - CmpF32NotEuqal(vf32[offset + 6], glUniform.view[idx + 6]) || - CmpF32NotEuqal(vf32[offset + 7], glUniform.view[idx + 7]) || - CmpF32NotEuqal(vf32[offset + 8], glUniform.view[idx + 8]) || - CmpF32NotEuqal(vf32[offset + 9], glUniform.view[idx + 9]) || - CmpF32NotEuqal(vf32[offset + 10], glUniform.view[idx + 10]) || - CmpF32NotEuqal(vf32[offset + 11], glUniform.view[idx + 11]) || - CmpF32NotEuqal(vf32[offset + 12], glUniform.view[idx + 12]) || - CmpF32NotEuqal(vf32[offset + 13], glUniform.view[idx + 13]) || - CmpF32NotEuqal(vf32[offset + 14], glUniform.view[idx + 14]) || - CmpF32NotEuqal(vf32[offset + 15], glUniform.view[idx + 15])) { - - const begin = glUniform.offset / 4; - glUniform.view.set(vf32.subarray(begin, begin + 16 * glUniform.count)); - gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.view as Float32Array); - break; - } - } - break; - } - default: + break; } - } // if + case WebGLRenderingContext.BOOL_VEC2: + case WebGLRenderingContext.INT_VEC2: { + const view = glUniform.view as Int32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 2) { + const idx = 2 * m; + if (vf32[offset] !== view[idx] || + vf32[offset + 1] !== view[idx + 1]) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); + gl.uniform2iv(glUniform.glLoc, view); + break; + } + } + break; + } + case WebGLRenderingContext.BOOL_VEC3: + case WebGLRenderingContext.INT_VEC3: { + const view = glUniform.view as Int32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 3) { + const idx = 3 * m; + if (vf32[offset] !== view[idx] || + vf32[offset + 1] !== view[idx + 1] || + vf32[offset + 2] !== view[idx + 2]) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); + gl.uniform3iv(glUniform.glLoc, view); + break; + } + } + break; + } + case WebGLRenderingContext.BOOL_VEC4: + case WebGLRenderingContext.INT_VEC4: { + const view = glUniform.view as Int32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 4) { + const idx = 4 * m; + if (vf32[offset] !== view[idx] || + vf32[offset + 1] !== view[idx + 1] || + vf32[offset + 2] !== view[idx + 2] || + vf32[offset + 3] !== view[idx + 3]) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); + gl.uniform4iv(glUniform.glLoc, view); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, ++offset) { + + if (CmpF32NotEuqal(vf32[offset], view[m])) { + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + glUniform.count)); + gl.uniform1fv(glUniform.glLoc, view); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_VEC2: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 2) { + const idx = 2 * m; + if (CmpF32NotEuqal(vf32[offset], view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], view[idx + 1])) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); + gl.uniform2fv(glUniform.glLoc, view); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_VEC3: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 3) { + const idx = 3 * m; + if (CmpF32NotEuqal(vf32[offset], view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], view[idx + 2])) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); + gl.uniform3fv(glUniform.glLoc, view); + break; + } + + } + break; + } + case WebGLRenderingContext.FLOAT_VEC4: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 4) { + const idx = 4 * m; + + if (CmpF32NotEuqal(vf32[offset], view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], view[idx + 3])) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); + gl.uniform4fv(glUniform.glLoc, view); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_MAT2: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 4) { + const idx = 4 * m; + if (CmpF32NotEuqal(vf32[offset], view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], view[idx + 3])) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); + gl.uniformMatrix2fv(glUniform.glLoc, false, view); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_MAT3: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 9) { + const idx = 9 * m; + if (CmpF32NotEuqal(vf32[offset], view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], view[idx + 3]) || + CmpF32NotEuqal(vf32[offset + 4], view[idx + 4]) || + CmpF32NotEuqal(vf32[offset + 5], view[idx + 5]) || + CmpF32NotEuqal(vf32[offset + 6], view[idx + 6]) || + CmpF32NotEuqal(vf32[offset + 7], view[idx + 7]) || + CmpF32NotEuqal(vf32[offset + 8], view[idx + 8])) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 9 * glUniform.count)); + gl.uniformMatrix3fv(glUniform.glLoc, false, view); + break; + } + } + break; + } + case WebGLRenderingContext.FLOAT_MAT4: { + const view = glUniform.view as Float32Array; + for (let m = 0; m < glUniform.count; ++m, offset += 16) { + const idx = 16 * m; + + if (CmpF32NotEuqal(vf32[offset], view[idx]) || + CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || + CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || + CmpF32NotEuqal(vf32[offset + 3], view[idx + 3]) || + CmpF32NotEuqal(vf32[offset + 4], view[idx + 4]) || + CmpF32NotEuqal(vf32[offset + 5], view[idx + 5]) || + CmpF32NotEuqal(vf32[offset + 6], view[idx + 6]) || + CmpF32NotEuqal(vf32[offset + 7], view[idx + 7]) || + CmpF32NotEuqal(vf32[offset + 8], view[idx + 8]) || + CmpF32NotEuqal(vf32[offset + 9], view[idx + 9]) || + CmpF32NotEuqal(vf32[offset + 10], view[idx + 10]) || + CmpF32NotEuqal(vf32[offset + 11], view[idx + 11]) || + CmpF32NotEuqal(vf32[offset + 12], view[idx + 12]) || + CmpF32NotEuqal(vf32[offset + 13], view[idx + 13]) || + CmpF32NotEuqal(vf32[offset + 14], view[idx + 14]) || + CmpF32NotEuqal(vf32[offset + 15], view[idx + 15])) { + + const begin = glUniform.offset / 4; + view.set(vf32.subarray(begin, begin + 16 * glUniform.count)); + gl.uniformMatrix4fv(glUniform.glLoc, false, view); + break; + } + } + break; + } + default: + } } } } // if diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 68dcec205a..ef868b0b02 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -151,6 +151,7 @@ export class WebGLGPUUniformBlock { public name: string = ''; public size: number = 0; public glUniforms: WebGLGPUUniform[] = []; + public glActiveUniforms: WebGLGPUUniform[] = []; public isUniformPackage: boolean = false; // Is a single uniform package? public buffer: ArrayBuffer | null = null; // for cache From dcb1045a516539c30ed1f9c9a28e8435aeccbd86 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 9 Jan 2019 17:30:36 +0800 Subject: [PATCH 072/267] pass properties --- cocos/3d/assets/effect-asset.ts | 33 ++-- cocos/3d/builtin/effects.js | 92 ++++------ cocos/3d/builtin/init.js | 12 +- cocos/pipeline/forward/forward-flow.ts | 8 +- cocos/pipeline/forward/test-material-stage.ts | 92 +++------- cocos/renderer/core/effect.ts | 160 +++++------------- cocos/renderer/core/pass.ts | 44 ++--- 7 files changed, 156 insertions(+), 285 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index b7f50345f8..8b5194fdd2 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -1,20 +1,32 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; -import { IPassInfoBase } from '../../renderer/core/pass'; +import { GFXPrimitiveMode } from '../../gfx/define'; +import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; +import { RenderPassStage } from '../../pipeline/render-pipeline'; -export interface ITechniqueInfo { - passes: IPassInfoBase[]; - queue?: number; - priority?: number; - lod?: number; -} export interface IPropertyInfo { - type?: number; - value?: number | number[] | null; + type: number; // auto-extracted if not specified + value?: number[] | string; displayName?: string; tech?: number; pass?: number; } +export interface IPassInfo { + program: string; + // effect-writer part + primitive?: GFXPrimitiveMode; + stage?: RenderPassStage; + rasterizerState?: GFXRasterizerState; + depthStencilState?: GFXDepthStencilState; + blendState?: GFXBlendState; + properties?: Record; +} +export interface ITechniqueInfo { + passes: IPassInfo[]; + queue?: number; + priority?: number; + lod?: number; +} export interface IBlockMember { name: string; @@ -81,9 +93,6 @@ export class EffectAsset extends Asset { @property public techniques: ITechniqueInfo[] = []; - @property - public properties: Record = {}; - @property public shaders: IShaderInfo[] = []; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 1a372d2949..6f0d83c216 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,29 +1,42 @@ export default [ + { + "name": "builtin-effect-unlit", + "techniques": [{"queue": "opaque", "lod": 100, "passes": [{"properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": "grey"}}, "program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}]}], + "shaders": [ + { + "name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c", + "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_texCoord1;\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;\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_texCoord1 * 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": []}, + {"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]}, + {"name": "USE_COLOR", "type": "boolean", "defines": []} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ + {"name": "mainTiling", "type": 14, "count": 1, "size": 8}, + {"name": "mainOffset", "type": 14, "count": 1, "size": 8} + ]}, + {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [ + {"name": "color", "type": 16, "count": 1, "size": 16} + ]} + ], + "samplers": [ + {"name": "mainTexture", "type": 29, "count": 1, "defines": ["USE_TEXTURE"], "binding": 2} + ], + "dependencies": {} + } + ] + }, { "name": "test", - "techniques": [{"queue": 0, "lod": 500, "passes": [{"stage": 100, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}], "priority": 0}], - "properties": {"u_color": {"type": 17, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": null}}, + "techniques": [{"queue": "opaque", "lod": 500, "passes": [{"stage": 100, "properties": {"u_color": {"type": 17, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": "grey"}}, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}]}], "shaders": [ { "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", - "vert": ` -attribute vec2 a_position; -attribute vec2 a_texCoord; -varying vec2 v_texCoord; -void main() { - gl_Position = vec4(a_position, 0.0, 1.0); - v_texCoord = a_texCoord; -} - `, - "frag": ` -varying vec2 v_texCoord; -uniform vec4 u_color; -uniform sampler2D u_sampler; -void main() { - gl_FragColor = texture2D(u_sampler, v_texCoord); - gl_FragColor.r = u_color.r; -} - `, + "vert": "\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n varying vec2 v_texCoord;\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n", + "frag": "\n varying vec2 v_texCoord;\n uniform vec4 u_color;\n uniform sampler2D u_sampler;\n void main() {\n \n gl_FragColor = texture2D(u_sampler, v_texCoord);\n gl_FragColor.r = u_color.r;\n }\n", "defines": [], "blocks": [ {"name": "Constants", "size": 16, "defines": [], "binding": 0, "members": [ @@ -37,41 +50,9 @@ void main() { } ] }, - { - "name": "builtin-effect-unlit", - "techniques": [{"queue": 0, "lod": 100, "passes": [{"program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}], "priority": 0}], - "properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": null}}, - "shaders": [ - { - "name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c", - "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_texCoord1;\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;\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_texCoord1 * 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": []}, - {"name": "CC_USE_JOINTS_TEXTURE", "type": "boolean", "defines": ["CC_USE_SKINNING"]}, - {"name": "USE_COLOR", "type": "boolean", "defines": []} - ], - "blocks": [ - {"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "size": 16, "members": [ - {"name": "mainTiling", "type": 14, "count": 1}, - {"name": "mainOffset", "type": 14, "count": 1} - ]}, - {"name": "Constant", "defines": ["USE_COLOR"], "binding": 1, "size": 16, "members": [ - {"name": "color", "type": 16, "count": 1} - ]} - ], - "samplers": [ - {"name": "mainTexture", "type": 29, "count": 1, "defines": ["USE_TEXTURE"], "binding": 2} - ], - "dependencies": {} - } - ] - }, { "name": "builtin-effect-skybox", - "techniques": [{"queue": 0, "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "program": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d"}], "priority": -1000}], - "properties": {"cubeMap": {"type": 32, "value": null}}, + "techniques": [{"queue": "opaque-1000", "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "properties": {"cubeMap": {"type": 32, "value": "greyCube"}}, "program": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d"}]}], "shaders": [ { "name": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d", @@ -90,8 +71,7 @@ void main() { }, { "name": "builtin-effect-sprite", - "techniques": [{"queue": 2, "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "program": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6"}], "priority": 0}], - "properties": {"mainTexture": {"type": 29, "value": null}}, + "techniques": [{"queue": "overlay", "passes": [{"depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 4, "blendDstAlpha": 4}]}, "properties": {"mainTexture": {"type": 29, "value": "grey"}}, "program": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6"}]}], "shaders": [ { "name": "a86b95b64dc75bf2cc5b528318547813f86f5cd9e03ee48ca69556f6", @@ -105,5 +85,5 @@ void main() { "dependencies": {} } ] - } + }, ]; diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index 409f143d2f..f131953a21 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -78,18 +78,18 @@ let builtinResMgr = { }); // default material - // let defaultMtl = new Material(); - // defaultMtl._uuid = 'default-material'; - // defaultMtl._defines['USE_COLOR'] = true; - // defaultMtl.effectAsset = efxs[0]; - // defaultMtl.setProperty('color', cc.color('#FF00FF')); + let defaultMtl = new Material(); + defaultMtl._uuid = 'default-material'; + defaultMtl.setDefines({ USE_COLOR: true }); + defaultMtl.effectAsset = efxs[0]; + defaultMtl.setProperty('color', cc.color('#FF00FF')); let builtins = { // [defaultTexture._uuid]: defaultTexture, // [defaultTextureCube._uuid]: defaultTextureCube, // [blackTexture._uuid]: blackTexture, // [whiteTexture._uuid]: whiteTexture, - // [defaultMtl._uuid]: defaultMtl + [defaultMtl._uuid]: defaultMtl }; return Object.assign(builtinResMgr, builtins); }, diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 24328dda5e..8db0effcf6 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -32,21 +32,19 @@ export class ForwardFlow extends RenderFlow { priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ - - /* + /* * this.createStage(TestMaterialStage, { name: 'TestMaterialStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - */ - + /* */ this.createStage(TestStage, { name: 'TestStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); + /* */ return true; } diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index 68b22e0a0a..4f908f7666 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -1,21 +1,17 @@ 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 { GFXBufferTextureCopy, GFXCommandBufferType, GFXFormat, - GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; +import { GFXCommandBufferType } from '../../gfx/define'; import { GFXFramebuffer } from '../../gfx/framebuffer'; import { GFXInputAssembler } from '../../gfx/input-assembler'; -import { GFXTexture } from '../../gfx/texture'; -import { GFXTextureView } from '../../gfx/texture-view'; import { RenderFlow } from '../render-flow'; import { RenderStage, RenderStageInfo } from '../render-stage'; import { RenderView } from '../render-view'; -import Texture2D from '../../assets/texture-2d'; -import ImageAsset from '../../assets/image-asset'; export class TestMaterialStage extends RenderStage { - private _texture: GFXTexture | null = null; - private _texView: GFXTextureView | null = null; + private _textureAsset: Texture2D | null = null; private _material: Material = new Material(); constructor (flow: RenderFlow) { @@ -54,17 +50,10 @@ export class TestMaterialStage extends RenderStage { } public destroy () { - - if (this._texView) { - this._texView.destroy(); - this._texView = null; + if (this._textureAsset) { + this._textureAsset.destroy(); + this._textureAsset = null; } - - if (this._texture) { - this._texture.destroy(); - this._texture = null; - } - if (this._cmdBuff) { this._cmdBuff.destroy(); this._cmdBuff = null; @@ -78,18 +67,18 @@ export class TestMaterialStage extends RenderStage { // 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'); - pass.bindTextureView(texBinding, this._texView as GFXTextureView); + 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')); - /* */ - mtl.setProperty('u_sampler', { - tv: this._texView, - getGFXTextureView () { return this.tv; }, - }); - mtl.setProperty('u_color', 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; @@ -115,50 +104,13 @@ export class TestMaterialStage extends RenderStage { } private loadTexture (image: HTMLImageElement): boolean { - // 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]); - - const textureAsset = new Texture2D(); + const textureAsset = this._textureAsset = new Texture2D(); textureAsset.image = new ImageAsset(image); - this._texture = textureAsset.getGFXTexture(); - if (!this._texture) { - return false; - } - this._texView = textureAsset.getGFXTextureView(); - if (!this._texView) { - return false; - } + + const texture = textureAsset.getGFXTexture(); + if (!texture) { return false; } + const texView = textureAsset.getGFXTextureView(); + if (!texView) { return false; } return true; } diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 724032e052..8dd033de8b 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -1,13 +1,13 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { EffectAsset, IBlockMember, IPropertyInfo, ISamplerInfo, IShaderInfo } from '../../3d/assets/effect-asset'; +import { EffectAsset, IShaderInfo } from '../../3d/assets/effect-asset'; import { CCObject } from '../../core/data'; import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; import { GFXType } from '../../gfx/define'; import { RenderPassStage } from '../../pipeline/render-pipeline'; import Texture2D from '../gfx/texture-2d'; import TextureCube from '../gfx/texture-cube'; -import { IPassInfo, Pass } from './pass'; +import { IPassInfoFull, Pass } from './pass'; const _typeMap = { [GFXType.INT]: 'Number', @@ -35,7 +35,7 @@ export interface IEffectInfo { defines?: IDefineMap; } -type DefaultValue = number | boolean | number[] | null; +type DefaultValue = number | boolean | number[] | string; const _ctorMap = { Boolean: (v?: DefaultValue) => v || false, Number: (v?: DefaultValue) => v || 0, @@ -55,140 +55,66 @@ const _ctorMap = { [CCObject]: () => null, }; const getInstanceCtor = (t: number | string) => _ctorMap[getInstanceType(t)]; - -const getInvolvedPrograms = (effect: EffectAsset, techIdx?: number) => { - const programs: Record = {}; - const lib = cc.game._programLib; - if (techIdx) { - effect.techniques[techIdx].passes.forEach((pass) => { - programs[pass.program] = lib.getTemplate(pass.program); - }); - } else { - effect.techniques.forEach((tech) => { - tech.passes.forEach((pass) => { - programs[pass.program] = lib.getTemplate(pass.program); - }); - }); - } - return programs; -}; - -interface IExtractedPropInfo { - type: number; - instanceType: object | string; - value: number | boolean | object; - defines: string[]; - displayName?: string; - tech: number; - pass: number; -} -const parseProperties = (() => { - interface IUniformInfo { type: number; defines: string[]; } - function genPropInfo (propInfo: IPropertyInfo, uniformInfo: IUniformInfo, tech: number, pass: number) - : IExtractedPropInfo { - const type = propInfo.type || uniformInfo.type; - return { - defines: uniformInfo.defines, - displayName: propInfo.displayName, - instanceType: getInstanceType(type), - pass, tech, type, - value: getInstanceCtor(type)(propInfo.value), - }; - } - function findUniformInfo (program: IShaderInfo, name: string) { - for (const b of program.blocks) { - const i = b.members.find((u) => u.name === name); - if (i) { return Object.assign({ defines: b.defines }, i); } - } - return program.samplers.find((u) => u.name === name); - } - function findPassIdx (effect: EffectAsset, programName: string) { // just a heuristic - effect.techniques.forEach((tech, i) => { - tech.passes.forEach((pass, j) => { - if (pass.program === programName) { - return [ i, j ]; - } - }); - }); - return [ 0, 0 ]; - } - return (effect: EffectAsset, programs: Record) => { - const props: Record = {}; - for (const prop of Object.keys(effect.properties)) { - const propInfo = effect.properties[prop]; - let uniformInfo: IUniformInfo | undefined; - let techIdx = 0; - let passIdx = 0; - // always try getting the type from shaders first - if (propInfo.tech !== undefined && propInfo.pass !== undefined) { - const p = effect.techniques[propInfo.tech].passes[propInfo.pass].program; - uniformInfo = findUniformInfo(programs[p], prop); - techIdx = propInfo.tech; passIdx = propInfo.pass; - } else { - for (const p of Object.keys(programs)) { - uniformInfo = findUniformInfo(programs[p], prop); - if (uniformInfo) { [techIdx, passIdx] = findPassIdx(effect, p); break; } - } - } - // the property is not defined in all the shaders used in techs - if (!uniformInfo) { - console.warn(`illegal property: ${prop}`); - continue; - } - props[prop] = genPropInfo(propInfo, uniformInfo, techIdx, passIdx); - } - return props; - }; -})(); - -const traverseUniforms = (shaderInfo: IShaderInfo, fn: (u: IBlockMember | ISamplerInfo) => any) => { - shaderInfo.blocks.forEach((b) => b.members.forEach(fn)); - shaderInfo.samplers.forEach(fn); +const getProgram = (name: string): IShaderInfo => cc.game._programLib.getTemplate(name); +const getDefines = (name: string, prog: IShaderInfo) => { + const block = prog.blocks.find((b) => b.members.find((u) => u.name === name) !== undefined); + if (block) { return block.defines; } + const s = prog.samplers.find((u) => u.name === name); + if (s) { return s.defines; } }; export class Effect { public static parseEffect (effect: EffectAsset, info?: IEffectInfo) { // techniques const { techIdx, defines } = info || {} as IEffectInfo; - const programs = getInvolvedPrograms(effect, techIdx || 0); const tech = effect.techniques[techIdx || 0]; const passNum = tech.passes.length; const passes: Pass[] = new Array(passNum); - const props = parseProperties(effect, programs); for (let k = 0; k < passNum; ++k) { - const passInfo = tech.passes[k] as IPassInfo; - const uniforms: IPropertyMap = passInfo.uniforms = {}; - traverseUniforms(programs[passInfo.program], (u) => { - const prop = props[u.name]; - uniforms[u.name] = { // property overloads are shared among passes here - type: prop ? prop.type : u.type, - value: prop ? prop.value : getInstanceCtor(u.type)(), - }; - }); + const passInfo = tech.passes[k] as IPassInfoFull; + const prog = getProgram(passInfo.program); passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines || {}); passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); - passInfo.blocks = programs[passInfo.program].blocks; - passInfo.samplers = programs[passInfo.program].samplers; + passInfo.blocks = prog.blocks; + passInfo.samplers = prog.samplers; const pass = new Pass(cc.game._gfxDevice); pass.initialize(passInfo); passes[k] = pass; } return passes; } + public static parseForInspector (effect: EffectAsset) { - const programs = getInvolvedPrograms(effect); - const props = parseProperties(effect, programs); - const defines: Record = {}; - for (const pn of Object.keys(programs)) { - programs[pn].defines.forEach((define) => { - defines[define.name] = { - defines: define.defines, - instanceType: getInstanceType(define.type), - value: getInstanceCtor(define.type)(), - }; - }); + const res: object[] = []; + for (const tech of effect.techniques) { + const props: Array> = []; + const defines: Record = {}; + for (const pass of tech.passes) { + const prog = getProgram(pass.program); + prog.defines.forEach((define) => { + defines[define.name] = { + defines: define.defines, + instanceType: getInstanceType(define.type), + value: getInstanceCtor(define.type)(), + }; + }); + const list: Record = {}; + props.push(list); + if (!pass.properties) { continue; } + for (const p of Object.keys(pass.properties)) { + const prop = pass.properties[p]; + const defs = getDefines(p, prog); + if (!defs) { continue; } + list[p] = { + defines: defs, + instanceType: getInstanceType(prop.type), + value: getInstanceCtor(prop.type)(), + }; + } + } + res.push({ props, defines }); } - return { props, defines }; + return res; } } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index b0216bc470..52c6d904b2 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { IBlockInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; +import { IBlockInfo, IPassInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; @@ -14,24 +14,13 @@ import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; import { RenderPassStage } from '../../pipeline/render-pipeline'; -import { IPropertyMap } from './effect'; -export interface IPassInfoBase { - program: string; - // effect-writer part - primitive?: GFXPrimitiveMode; - stage?: RenderPassStage; - rasterizerState?: GFXRasterizerState; - depthStencilState?: GFXDepthStencilState; - blendState?: GFXBlendState; -} -export interface IPassInfo extends IPassInfoBase { +export interface IPassInfoFull extends IPassInfo { // generated part blocks: IBlockInfo[]; samplers: ISamplerInfo[]; shader: GFXShader; renderPass: GFXRenderPass; - uniforms: IPropertyMap; } const _type2fn = { @@ -49,6 +38,21 @@ const _type2fn = { [GFXType.MAT4]: (a: Float32Array, v: any) => mat4.array(a, v), }; +const _type2default = { + [GFXType.INT]: 0, + [GFXType.INT2]: [0, 0], + [GFXType.INT3]: [0, 0, 0], + [GFXType.INT4]: [0, 0, 0, 0], + [GFXType.FLOAT]: 0, + [GFXType.FLOAT2]: [0, 0], + [GFXType.FLOAT3]: [0, 0, 0], + [GFXType.FLOAT4]: [0, 0, 0, 0], + [GFXType.COLOR4]: [0, 0, 0, 1], + [GFXType.MAT2]: [1, 0, 0, 1], + [GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1], + [GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], +}; + const btMask = 0xf0000000; // 4 bits, 16 slots const typeMask = 0x0fc00000; // 6 bits, 64 slots const bindingMask = 0x003ff800; // 11 bits, 2048 slots @@ -93,7 +97,7 @@ export class Pass { this._device = device; } - public initialize (info: IPassInfo) { + public initialize (info: IPassInfoFull) { this._programName = info.program; // pipeline state const device = this._device; @@ -136,9 +140,11 @@ export class Pass { const view = new Float32Array(block.buffer, acc, cur.size / Float32Array.BYTES_PER_ELEMENT); block.views.push(view); // store handle map, type and initial value - const inf = info.uniforms[cur.name]; - this._handleMap[cur.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, inf.type, u.binding, idx); - _type2fn[inf.type](view, inf.value); + const inf = info.properties && info.properties[cur.name]; + const type = inf && inf.type || cur.type; // property overloads + const value = inf && inf.value; + view.set(value ? value as number[] : _type2default[type]); + this._handleMap[cur.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, type, u.binding, idx); // proceed the counter return acc + cur.size; }, 0); // === u.size @@ -193,7 +199,7 @@ export class Pass { } } - public setStates (info: IPassInfoBase) { + public setStates (info: IPassInfo) { if (this._pipelineState) { this._pipelineState.destroy(); } this.createPipelineState(info); } @@ -221,7 +227,7 @@ export class Pass { } } - protected createPipelineState (info: IPassInfoBase) { + protected createPipelineState (info: IPassInfo) { if (info.primitive) { this._primitive = info.primitive; } if (info.stage) { this._stage = info.stage; } From d95de6a478044995427d223255aeb0c4406a9adf Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 9 Jan 2019 17:57:20 +0800 Subject: [PATCH 073/267] commit modified files --- cocos/pipeline/render-flow.ts | 79 +++++++++++----------- cocos/pipeline/render-pipeline.ts | 4 +- cocos/pipeline/render-queue.ts | 80 +++++++++++----------- cocos/renderer/scene/model.ts | 108 +++++++++++++++--------------- 4 files changed, 136 insertions(+), 135 deletions(-) diff --git a/cocos/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts index 67fb3c161d..5870f5ce93 100644 --- a/cocos/pipeline/render-flow.ts +++ b/cocos/pipeline/render-flow.ts @@ -1,67 +1,66 @@ -import { RenderStage, RenderStageInfo } from "./render-stage"; -import { RenderView } from "./render-view"; -import { RenderPipeline } from "./render-pipeline"; -import { GFXRenderPass } from "../gfx/render-pass"; -import { GFXDevice } from "../gfx/device"; +import { GFXDevice } from '../gfx/device'; +import { RenderPipeline } from './render-pipeline'; +import { RenderStage, RenderStageInfo } from './render-stage'; +import { RenderView } from './render-view'; -export interface RenderFlowInfo { +export interface IRenderFlowInfo { name?: string; priority: number; -}; +} export abstract class RenderFlow { - constructor(pipeline: RenderPipeline) { + public get device (): GFXDevice { + return this._device; + } + + public get pipeline (): RenderPipeline { + return this._pipeline; + } + + public get priority (): number { + return this._priority; + } + + protected _device: GFXDevice; + protected _pipeline: RenderPipeline; + protected _name: string = ''; + protected _priority: number = 0; + protected _stages: RenderStage[] = []; + protected _material: null = null; // TODO + + constructor (pipeline: RenderPipeline) { this._device = pipeline.device; this._pipeline = pipeline; } - public abstract initialize(info: RenderFlowInfo): boolean; - public abstract destroy(); + public abstract initialize (info: IRenderFlowInfo): boolean; + public abstract destroy (); - public render(view: RenderView) { - for(let i = 0; i < this._stages.length; ++i) { - this._stages[i].render(view); + public render (view: RenderView) { + for (const stage of this._stages) { + stage.render(view); } } - public createStage(clazz: new(flow: RenderFlow) => T, info : RenderStageInfo): RenderStage | null { - let stage: RenderStage = new clazz(this); - if(stage.initialize(info)) { + public createStage (clazz: new(flow: RenderFlow) => T, info: RenderStageInfo): RenderStage | null { + const stage: RenderStage = new clazz(this); + if (stage.initialize(info)) { this._stages.push(stage); this._stages.sort((a, b) => { return a.priority - b.priority; }); - + return stage; } else { return null; } } - public destroyStages() { - for(let i = 0; i < this._stages.length; ++i) { - this._stages[i].destroy(); + public destroyStages () { + for (const stage of this._stages) { + stage.destroy(); } this._stages = []; } - - public get device(): GFXDevice { - return this._device; - } - - public get pipeline(): RenderPipeline { - return this._pipeline; - } - - public get priority(): number { - return this._priority; - } - - protected _device: GFXDevice; - protected _pipeline: RenderPipeline; - protected _name: string = ""; - protected _priority: number = 0; - protected _stages: RenderStage[] = []; - protected _material: null = null; // TODO -}; +} diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 27e03c2603..982e28a788 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -11,7 +11,7 @@ import { GFXUniformBlock } from '../gfx/shader'; import { GFXTexture } from '../gfx/texture'; import { GFXTextureView } from '../gfx/texture-view'; import { Camera } from '../renderer/scene/camera'; -import { RenderFlow, RenderFlowInfo } from './render-flow'; +import { IRenderFlowInfo, RenderFlow } from './render-flow'; import { RenderQueue } from './render-queue'; import { RenderView } from './render-view'; @@ -166,7 +166,7 @@ export abstract class RenderPipeline { this._renderPasses.clear(); } - public createFlow (clazz: new (pipeline: RenderPipeline) => T, info: RenderFlowInfo): RenderFlow | null { + public createFlow (clazz: new (pipeline: RenderPipeline) => T, info: IRenderFlowInfo): RenderFlow | null { const flow: RenderFlow = new clazz(this); if (flow.initialize(info)) { this._flows.push(flow); diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index efb8e7002d..8fce3122b6 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -1,56 +1,60 @@ -import { Pass } from "../renderer/core/pass"; -import Model from "../renderer/scene/model"; +import { GFXCommandBuffer } from '../gfx/command-buffer'; +import { Pass } from '../renderer/core/pass'; +import Model from '../renderer/scene/model'; export class RenderItem { - hash: number; - model: Model; - pass: Pass; + public hash: number; + public model: Model; + public pass: Pass; + public cmdBuff: GFXCommandBuffer; - constructor(hash: number, model: Model, pass: Pass) { + constructor (hash: number, model: Model, pass: Pass, cmdBuff: GFXCommandBuffer) { this.hash = hash; this.model = model; this.pass = pass; + this.cmdBuff = cmdBuff; } -}; +} export class RenderQueue { - constructor() { - } - - public add(model: Model) { - - for(let i = 0; i < model.passes.length; ++i) { - let pass = model.passes[i]; - - let pso = pass.pipelineState; - - let isTransparent = pso.blendState.targets[0].blend; - - let hash: number = 0; - - if(!isTransparent) { - // Opaque objects are sorted by depth front to back, then by shader id. - hash = (0 << 63) | (pso.shader.id << 13); - - this._opaques.push({hash, model, pass}); - } else { - // Transparent objects are sorted by depth back to front, then by by shader id. - hash = (1 << 63) | (pso.shader.id << 13); - - this._transparents.push({hash, model, pass}); - } - } - } - - public get opaques(): RenderItem[] { + public get opaques (): RenderItem[] { return this._opaques; } - public get transparents(): RenderItem[] { + public get transparents (): RenderItem[] { return this._transparents; } private _opaques: RenderItem[] = []; private _transparents: RenderItem[] = []; -}; + + constructor () { + } + + public add (model: Model) { + + for (let i = 0; i < model.passes.length; ++i) { + const pass = model.passes[i]; + const cmdBuff = model.commandBuffers[i]; + + const pso = pass.pipelineState; + + const isTransparent = pso.blendState.targets[0].blend; + + let hash: number = 0; + + if (!isTransparent) { + // Opaque objects are sorted by depth front to back, then by shader id. + hash = (0 << 63) | (pso.shader.id << 13); + + this._opaques.push({hash, model, pass, cmdBuff}); + } else { + // Transparent objects are sorted by depth back to front, then by by shader id. + hash = (1 << 63) | (pso.shader.id << 13); + + this._transparents.push({hash, model, pass, cmdBuff}); + } + } + } +} diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 3cffb6da03..b36952660f 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,46 +1,43 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import { Material } from '../../3d/assets/material'; import { aabb } from '../../3d/geom-utils'; -import { IGFXInputAttribute, GFXInputAssembler } from '../../gfx/input-assembler'; -import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit, GFXCommandBufferType } from '../../gfx/define'; -import { RenderScene } from './render-scene'; -import { vec3 } from '../../core/vmath'; import { Vec3 } from '../../core/value-types'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXInputAssembler } from '../../gfx/input-assembler'; import { Node } from '../../scene-graph'; -import InputAssembler from '../core/input-assembler'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; -import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { Material } from '../../3d/assets/material'; -import { RenderItem } from '../../pipeline/render-queue'; +import { RenderScene } from './render-scene'; /** * A representation of a model */ export default class Model { - _scene: RenderScene | null; - _id: number; - _enable: boolean; - _type: string; - _poolID: number; - _isEnable: boolean; - _node: Node; - _inputAssembler: GFXInputAssembler | null; - _effect: Effect | null; - _defines: Object; - _dependencies: Object; - _viewID: number; - _cameraID: number; - _userKey: number; - _castShadow: boolean; - _boundingShape: aabb; - _bsModelSpace: aabb; - _material: Material | null; - _cmdBuffers: GFXCommandBuffer[]; + public _scene: RenderScene | null; + public _id: number; + public _enable: boolean; + public _type: string; + public _poolID: number; + public _isEnable: boolean; + public _node: Node; + public _inputAssembler: GFXInputAssembler | null; + public _effect: Effect | null; + public _defines: Object; + public _dependencies: Object; + public _viewID: number; + public _cameraID: number; + public _userKey: number; + public _castShadow: boolean; + public _boundingShape: aabb; + public _bsModelSpace: aabb; + public _material: Material | null; + public _cmdBuffers: GFXCommandBuffer[]; /** * Setup a default empty model */ - constructor() { + constructor () { this._scene = null; this._id = 0; this._enable = false; @@ -62,7 +59,7 @@ export default class Model { this._cmdBuffers = new Array(); } - set scene(scene: RenderScene | null) { + set scene (scene: RenderScene | null) { this._scene = scene; if (this._scene) { @@ -70,16 +67,16 @@ export default class Model { } } - get scene(): RenderScene | null { + get scene (): RenderScene | null { return this._scene; } - get id(): number { + get id (): number { return this._id; } - _updateTransform() { - if (!this._node._hasChanged || !this._boundingShape) return; + public _updateTransform () { + if (!this._node._hasChanged || !this._boundingShape) { return; } this._node.updateWorldTransformFull(); this._bsModelSpace.transform(this._node._mat, this._node._pos, this._node._rot, this._node._scale, this._boundingShape); @@ -90,17 +87,17 @@ export default class Model { * @param {vec3} minPos the min position of the model * @param {vec3} maxPos the max position of the model */ - createBoundingShape(minPos: Vec3, maxPos: Vec3) { - if (!minPos || !maxPos) return; + public createBoundingShape (minPos: Vec3, maxPos: Vec3) { + if (!minPos || !maxPos) { return; } this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); this._boundingShape = aabb.clone(this._bsModelSpace); } - enable(isEnable: boolean) { + public enable (isEnable: boolean) { this._isEnable = isEnable; } - isEnable(): boolean { + public isEnable (): boolean { return this._isEnable; } @@ -108,7 +105,7 @@ export default class Model { * Get the hosting node of this camera * @returns {Node} the hosting node */ - get node(): Node { + get node (): Node { return this._node; } @@ -116,7 +113,7 @@ export default class Model { * Set the hosting node of this model * @param {Node} node the hosting node */ - set node(node: Node) { + set node (node: Node) { this._node = node; } @@ -124,7 +121,7 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - set inputAssembler(ia: GFXInputAssembler) { + set inputAssembler (ia: GFXInputAssembler) { this._inputAssembler = ia; } @@ -132,7 +129,7 @@ export default class Model { * Set the model effect * @param {?Effect} effect the effect to use */ - setEffect(effect: Effect) { + public setEffect (effect: Effect) { if (effect) { this._effect = effect; // this._defines = effect.extractDefines(Object.create(null)); @@ -144,32 +141,33 @@ export default class Model { } } - set material(material: Material) { + set material (material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { this.recordCommandBuffer(i); } for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { - let cmdBuff = this._cmdBuffers.pop(); - if(cmdBuff) { + const cmdBuff = this._cmdBuffers.pop(); + if (cmdBuff) { cmdBuff.destroy(); } } } - recordCommandBuffer(index: number) { - let pass = (this._material).passes[index]; - let cmdBufferInfo = { + public recordCommandBuffer (index: number) { + const pass = ( this._material as Material).passes[index]; + const cmdBufferInfo = { allocator: cc.director.root.device.commandAllocator, type: GFXCommandBufferType.SECONDARY, }; - if (this._cmdBuffers[index] == null) + if (this._cmdBuffers[index] == null) { this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); + } this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); - this._cmdBuffers[index].bindInputAssembler(this._inputAssembler); - this._cmdBuffers[index].draw(this._inputAssembler); + this._cmdBuffers[index].bindInputAssembler( this._inputAssembler as GFXInputAssembler); + this._cmdBuffers[index].draw( this._inputAssembler as GFXInputAssembler); this._cmdBuffers[index].end(); } @@ -177,15 +175,15 @@ export default class Model { * Set the user key * @param {number} key */ - set userKey(key: number) { + set userKey (key: number) { this._userKey = key; } - get passes(): Pass[] { - return (this._material).passes; + get passes (): Pass[] { + return ( this._material as Material).passes; } - get commandBuffers(): GFXCommandBuffer[] { + get commandBuffers (): GFXCommandBuffer[] { return this._cmdBuffers; } @@ -193,7 +191,7 @@ export default class Model { * Extract a drawing item * @param {Object} out the receiving item */ - extractDrawItem(out) { + public extractDrawItem (out) { out.model = this; out.node = this._node; out.ia = this._inputAssembler; From 4e53783927dc8071c8fa0e1d54e6b1d3916946fa Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 9 Jan 2019 18:33:10 +0800 Subject: [PATCH 074/267] fix texture-cube texture loading --- cocos/3d/assets/texture-cube.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 43f5f423db..02468a164b 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -27,7 +27,7 @@ import { Texture2D } from '../../assets'; import ImageAsset from '../../assets/image-asset'; import TextureBase from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; -import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define'; +import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType, GFXTextureFlagBit } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; interface ITextureCubeMipmap { @@ -182,6 +182,7 @@ export default class TextureCube extends TextureBase { height: this._potientialHeight, mipLevel: this._mipmaps.length, arrayLayer: 6, + flags: GFXTextureFlagBit.CUBEMAP, }); } @@ -192,8 +193,9 @@ export default class TextureCube extends TextureBase { this._textureView = gfxDevice.createTextureView({ texture: this._texture, - type: GFXTextureViewType.TV2D_ARRAY, + type: GFXTextureViewType.CUBE, format: this._getGfxFormat(), + layerCount: 6, }); } } From 391e7c65ab7ee492a4755219e2eb60b867ea370d Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 9 Jan 2019 19:51:08 +0800 Subject: [PATCH 075/267] add model local buffer --- cocos/3d/builtin/effects.js | 40 +++++++ cocos/gfx/binding-layout.ts | 9 +- cocos/pipeline/forward/forward-flow.ts | 27 +++-- cocos/pipeline/forward/test-model-stage.ts | 131 +++++++++++++++++++++ cocos/pipeline/render-pipeline.ts | 20 ++-- cocos/renderer/core/program-lib.ts | 34 +++++- cocos/renderer/scene/model.ts | 75 ++++++++---- cocos/renderer/scene/render-scene.ts | 1 + 8 files changed, 287 insertions(+), 50 deletions(-) create mode 100644 cocos/pipeline/forward/test-model-stage.ts diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 6f0d83c216..1ef5140250 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,4 +1,44 @@ export default [ + { + "name": "test", + "techniques": [{"queue": 0, "lod": 500, "passes": [{"stage": 100, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}], "priority": 0}], + "properties": {"u_color": {"type": 17, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": null}}, + "shaders": [ + { + "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", + "vert": ` + attribute vec3 a_position; + attribute vec2 a_texCoord; + uniform mat4 cc_matWorld; + varying vec2 v_texCoord; + void main() { + gl_Position = cc_matWorld*vec4(a_position, 1.0); + v_texCoord = a_texCoord; + } +`, + "frag": ` + varying vec2 v_texCoord; + uniform vec4 u_color; + uniform sampler2D u_sampler; + void main() { + + gl_FragColor = texture2D(u_sampler, v_texCoord); + gl_FragColor.r = u_color.r; + } +`, + "defines": [], + "blocks": [ + {"name": "Constants", "size": 16, "defines": [], "binding": 0, "members": [ + {"name": "u_color", "type": 16, "count": 1, "size": 16} + ]} + ], + "samplers": [ + {"name": "u_sampler", "type": 29, "count": 1, "defines": [], "binding": 1} + ], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-unlit", "techniques": [{"queue": "opaque", "lod": 100, "passes": [{"properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": "grey"}}, "program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}]}], diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index 33156a860e..d3cc2f180f 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -75,7 +75,12 @@ export abstract class GFXBindingLayout { } } - public getBindingUnit (binding: number): GFXBindingUnit { - return this._bindingUnits[binding]; + public getBindingUnit(binding: number): GFXBindingUnit { + for (let i = 0; i < this._bindingUnits.length; i++) { + if (this._bindingUnits[i].binding === binding) { + return this._bindingUnits[i]; + } + } + return null; } } diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 8db0effcf6..7896202a2d 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,7 +1,9 @@ -import { RenderFlow, RenderFlowInfo } from '../render-flow'; -import { RenderPipeline } from '../render-pipeline'; -import { TestMaterialStage } from './test-material-stage'; -import { TestStage } from './test-stage'; +import { RenderFlow, RenderFlowInfo } from "../render-flow"; +import { RenderPipeline } from "../render-pipeline"; +// import { TestStage } from "./test-stage"; +import { TestMaterialStage } from "./test-material-stage"; +import { TestStage } from "./test-stage"; +import { TestModelStage } from "./test-model-stage"; export enum ForwardStagePriority { FORWARD = 0, @@ -32,18 +34,19 @@ export class ForwardFlow extends RenderFlow { priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* * - this.createStage(TestMaterialStage, { - name: 'TestMaterialStage', + /* */ + + this.createStage(TestModelStage, { + name: "TestModelStage", priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); /* */ - this.createStage(TestStage, { - name: 'TestStage', - priority: ForwardStagePriority.FORWARD, - framebuffer: mainWindow.framebuffer, - }); + // this.createStage(TestStage, { + // name: 'TestStage', + // priority: ForwardStagePriority.FORWARD, + // framebuffer: mainWindow.framebuffer, + // }); /* */ return true; diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts new file mode 100644 index 0000000000..bb4e0d3e10 --- /dev/null +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -0,0 +1,131 @@ +import { Material } from '../../3d/assets/material'; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { + GFXBufferTextureCopy, GFXCommandBufferType, GFXFormat, + GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType, GFXType +} from '../../gfx/define'; +import { GFXFramebuffer } from '../../gfx/framebuffer'; +import { GFXInputAssembler } from '../../gfx/input-assembler'; +import { GFXTexture } from '../../gfx/texture'; +import { GFXTextureView } from '../../gfx/texture-view'; +import { RenderFlow } from '../render-flow'; +import { RenderStage, RenderStageInfo } from '../render-stage'; +import { RenderView } from '../render-view'; +import Model from '../../renderer/scene/model'; +import { Scene } from '../../scene-graph'; +import { EffectAsset } from '../../3d/assets/effect-asset'; +import { UBOLocal } from '../render-pipeline'; +import Texture2D from '../../assets/texture-2d'; +import ImageAsset from '../../assets/image-asset'; + +export class TestModelStage extends RenderStage { + + private _material: Material = new Material(); + private _model: Model; + private _scene: Scene; + private _init: boolean = false; + private _textureAsset: Texture2D | null = null; + + constructor(flow: RenderFlow) { + super(flow); + } + + public initialize(info: RenderStageInfo): 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])) { + 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('#ff0000')); + this._material.inited = true; + + this._scene = new Scene(); + this._scene._scene = this._scene; + let modelCom = this._scene.addComponent('cc.ModelComponent'); + modelCom.material = this._material; + modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + this._model = modelCom._models[0]; + this._scene.setRotationFromEuler(45, 45, 45); + this._scene._rot = this._scene._lrot; + this._init = true; + } + + const cmdBuff = this._cmdBuff; + this._renderArea.width = view.width; + this._renderArea.height = view.height; + this._model._updateTransform(); + this._model.updateRenderData(); + cmdBuff.begin(); + cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, + this._clearDepth, this._clearStencil); + + cmdBuff.execute(this._model.commandBuffers); + 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/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 982e28a788..7d3c5ba42e 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -19,6 +19,8 @@ export enum RenderPassStage { DEFAULT = 100, } + + export class UBOGlobal { public static TIME_OFFSET: number = 0; public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; @@ -34,7 +36,7 @@ export class UBOGlobal { public static SIZE: number = UBOGlobal.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 0, name: 'Global', members: [ + binding: 30, name: 'Global', members: [ { name: 'u_time', type: GFXType.FLOAT4, count: 1 }, { name: 'u_screenSize', type: GFXType.FLOAT4, count: 1 }, { name: 'u_screenScale', type: GFXType.FLOAT4, count: 1 }, @@ -53,19 +55,15 @@ export class UBOGlobal { export class UBOLocal { public static MAT_WORLD_OFFSET: number = 0; - public static MAT_WORLD_VIEW_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16; - public static MAT_WORLD_VIEW_PROJ_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_OFFSET + 16; - public static WORLD_POS_OFFSET: number = UBOLocal.MAT_WORLD_VIEW_PROJ_OFFSET + 16; - public static COUNT: number = UBOLocal.WORLD_POS_OFFSET + 4; + public static MAT_WORLD_IT_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16; + public static COUNT: number = UBOLocal.MAT_WORLD_IT_OFFSET + 16; public static SIZE: number = UBOLocal.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 1, name: 'Local', members: [ - { name: 'u_matWorld', type: GFXType.MAT4, count: 1 }, - { name: 'u_matWorldView', type: GFXType.MAT4, count: 1 }, - { name: 'u_matWorldViewProj', type: GFXType.MAT4, count: 1 }, - { name: 'u_worldPos', type: GFXType.FLOAT4, count: 1 }, - ], + binding: 31, name: "CCLocal", members: [ + { name: "cc_matWorld", type: GFXType.MAT4, count: 1 }, + { name: "cc_matWorldIT", type: GFXType.MAT4, count: 1 } + ] }; public view: Float32Array = new Float32Array(UBOLocal.COUNT); diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 15fb5cff82..470fdb4e33 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -1,10 +1,11 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { IDefineInfo, IShaderInfo } from '../../3d/assets/effect-asset'; -import { GFXShaderType } from '../../gfx/define'; +import { IDefineInfo, IShaderInfo, IBlockInfo, IBlockMember } from '../../3d/assets/effect-asset'; +import { GFXShaderType, GFXGetTypeSize } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; -import { GFXShader } from '../../gfx/shader'; +import { GFXShader, GFXUniformBlock, GFXUniform } from '../../gfx/shader'; import { IDefineMap } from './effect'; +import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; function _generateDefines( device: GFXDevice, @@ -125,6 +126,8 @@ export class ProgramLib { const vert = customDef + tmpl.vert; const frag = customDef + tmpl.frag; + tmpl.blocks = tmpl.blocks.concat(convertToBlockInfo(UBOGlobal.BLOCK), convertToBlockInfo(UBOLocal.BLOCK)); + program = this._device.createShader({ name, blocks: tmpl.blocks, @@ -138,3 +141,28 @@ export class ProgramLib { return program; } } + +function convertToUniformInfo(uniform: GFXUniform): IBlockMember { + return { + name: uniform.name, + type: uniform.type, + count: uniform.count, + size: GFXGetTypeSize(uniform.type) * uniform.count + } +} + +function convertToBlockInfo(block: GFXUniformBlock): IBlockInfo { + let members: IBlockMember[] = []; + let size: number = 0; + for (let i = 0; i < block.members.length; i++) { + members.push(convertToUniformInfo(block.members[i])); + size += members[i].size; + } + return { + name: block.name, + binding: block.binding, + defines: [], + members: members, + size: size + }; +} diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index b36952660f..ecc36b2b6f 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,39 +1,47 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { Material } from '../../3d/assets/material'; import { aabb } from '../../3d/geom-utils'; +import { IGFXInputAttribute, GFXInputAssembler } from '../../gfx/input-assembler'; +import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit, GFXCommandBufferType } from '../../gfx/define'; +import { RenderScene } from './render-scene'; +import { vec3, mat4 } from '../../core/vmath'; import { Vec3 } from '../../core/value-types'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; -import { GFXInputAssembler } from '../../gfx/input-assembler'; import { Node } from '../../scene-graph'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; -import { RenderScene } from './render-scene'; +import { UBOLocal } from '../../pipeline/render-pipeline'; +import { GFXBuffer } from '../../gfx/buffer'; + +let _temp_floatx16 = new Float32Array(16); +let _temp_mat4 = mat4.create(); /** * A representation of a model */ export default class Model { - public _scene: RenderScene | null; - public _id: number; - public _enable: boolean; - public _type: string; - public _poolID: number; - public _isEnable: boolean; - public _node: Node; - public _inputAssembler: GFXInputAssembler | null; - public _effect: Effect | null; - public _defines: Object; - public _dependencies: Object; - public _viewID: number; - public _cameraID: number; - public _userKey: number; - public _castShadow: boolean; - public _boundingShape: aabb; - public _bsModelSpace: aabb; - public _material: Material | null; - public _cmdBuffers: GFXCommandBuffer[]; + private _scene: RenderScene | null; + private _id: number; + private _enable: boolean; + private _type: string; + private _poolID: number; + private _isEnable: boolean; + private _node: Node; + private _inputAssembler: GFXInputAssembler | null; + private _effect: Effect | null; + private _defines: Object; + private _dependencies: Object; + private _viewID: number; + private _cameraID: number; + private _userKey: number; + private _castShadow: boolean; + private _boundingShape: aabb; + private _bsModelSpace: aabb; + private _material: Material | null; + private _cmdBuffers: GFXCommandBuffer[]; + private _localUniforms: UBOLocal | null; + private _localUBO: GFXBuffer; /** * Setup a default empty model */ @@ -57,6 +65,18 @@ export default class Model { this._boundingShape = null; this._material = null; this._cmdBuffers = new Array(); + this._localUniforms = null; + } + + initialize() { + this._localUniforms = new UBOLocal(); + this._localUBO = cc.director.root.device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOLocal.SIZE, + stride: UBOLocal.SIZE, + }); + this._localUBO.update(this._localUniforms.view); } set scene (scene: RenderScene | null) { @@ -82,6 +102,15 @@ export default class Model { this._node._rot, this._node._scale, this._boundingShape); } + updateRenderData() { + mat4.array(_temp_floatx16, this._node._mat); + this._node._mat.invert(_temp_mat4); + this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); + mat4.array(_temp_floatx16, _temp_mat4); + this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); + this._localUBO.update(this._localUniforms.view); + } + /** * Create the bounding shape of this model * @param {vec3} minPos the min position of the model @@ -163,6 +192,8 @@ export default class Model { if (this._cmdBuffers[index] == null) { this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); } + pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO); + pass.bindingLayout.update(); this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 044286e592..52a0135342 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -119,6 +119,7 @@ export class RenderScene { public createModel(clazz: new () => T): Model { let model = new clazz; + model.initialize(); model.scene = this; this._models.push(model); return model; From 3f63a11019f0a05a36856ecc2ee0bf205c985b54 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 9 Jan 2019 19:52:55 +0800 Subject: [PATCH 076/267] commit modified files --- cocos/pipeline/forward/forward-flow.ts | 10 +- cocos/pipeline/forward/forward-pipeline.ts | 32 ++--- cocos/pipeline/render-pipeline.ts | 2 +- cocos/pipeline/render-queue.ts | 24 +++- cocos/renderer/scene/camera.ts | 139 ++++++++++----------- 5 files changed, 110 insertions(+), 97 deletions(-) diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 8db0effcf6..bcb552f123 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,4 +1,4 @@ -import { RenderFlow, RenderFlowInfo } from '../render-flow'; +import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { RenderPipeline } from '../render-pipeline'; import { TestMaterialStage } from './test-material-stage'; import { TestStage } from './test-stage'; @@ -13,7 +13,7 @@ export class ForwardFlow extends RenderFlow { super(pipeline); } - public initialize (info: RenderFlowInfo): boolean { + public initialize (info: IRenderFlowInfo): boolean { if (info.name !== undefined) { this._name = info.name; @@ -32,19 +32,19 @@ export class ForwardFlow extends RenderFlow { priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* * + */ this.createStage(TestMaterialStage, { name: 'TestMaterialStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ + /* this.createStage(TestStage, { name: 'TestStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ + */ return true; } diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index 815c0b9c37..3470871a70 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -1,39 +1,39 @@ -import { RenderPipeline, RenderPassStage, UBOGlobal } from "../render-pipeline"; import { Root } from "../../core/root"; -import { ForwardFlow } from "./forward-flow"; -import { GFXRenderPass } from "../../gfx/render-pass"; import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../../gfx/define"; +import { GFXRenderPass } from "../../gfx/render-pass"; +import { RenderPassStage, RenderPipeline, UBOGlobal } from "../render-pipeline"; import { RenderQueue } from "../render-queue"; +import { ForwardFlow } from "./forward-flow"; export enum ForwardFlowPriority { FORWARD = 0, -}; +} export class ForwardPipeline extends RenderPipeline { - constructor(root: Root) { + constructor (root: Root) { super(root); } - public initialize(): boolean { - - if(!this.createQuadInputAssembler()) { + public initialize (): boolean { + + if (!this.createQuadInputAssembler()) { return false; } - if(!this.createUBOs()) { + if (!this.createUBOs()) { return false; } - let mainWindow = this._root.mainWindow; + const mainWindow = this._root.mainWindow; let windowPass: GFXRenderPass | null = null; - if(mainWindow) { + if (mainWindow) { windowPass = mainWindow.renderPass; } - if(!windowPass) { - console.error("RenderPass of main window is null."); + if (!windowPass) { + console.error('RenderPass of main window is null.'); return false; } @@ -48,18 +48,18 @@ export class ForwardPipeline extends RenderPipeline { // create flows this.createFlow(ForwardFlow, { - name: "ForwardFlow", + name: 'ForwardFlow', priority: ForwardFlowPriority.FORWARD, }); return true; } - public destroy() { + public destroy () { this.destroyFlows(); this.clearRenderPasses(); this.destroyUBOs(); this.destroyQuadInputAssembler(); } -}; +} diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 982e28a788..2bfa1b3a09 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -363,7 +363,7 @@ export abstract class RenderPipeline { } // add model pass to render queue - this._queue.add(model); + this._queue.add(model, camera); } } } diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index 8fce3122b6..ccc14153d8 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -1,7 +1,11 @@ +import { vec3 } from '../core/vmath'; import { GFXCommandBuffer } from '../gfx/command-buffer'; import { Pass } from '../renderer/core/pass'; +import { Camera } from '../renderer/scene/camera'; import Model from '../renderer/scene/model'; +const _pos: vec3 = vec3.create(); + export class RenderItem { public hash: number; public model: Model; @@ -28,30 +32,40 @@ export class RenderQueue { private _opaques: RenderItem[] = []; private _transparents: RenderItem[] = []; + private _buffer: ArrayBuffer; + private _f32View: Float32Array; + private _ui32View: Uint32Array; constructor () { + this._buffer = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT); + this._f32View = new Float32Array(this._buffer); + this._ui32View = new Uint32Array(this._buffer); } - public add (model: Model) { + public add (model: Model, camera: Camera) { + + model.node.getPosition(_pos); + this._f32View[0] = vec3.distance(camera.position, _pos); + let x = this._ui32View[0]; for (let i = 0; i < model.passes.length; ++i) { const pass = model.passes[i]; const cmdBuff = model.commandBuffers[i]; + model.node.getWorldPosition(); + const pso = pass.pipelineState; const isTransparent = pso.blendState.targets[0].blend; - let hash: number = 0; - if (!isTransparent) { // Opaque objects are sorted by depth front to back, then by shader id. - hash = (0 << 63) | (pso.shader.id << 13); + const hash = (0 << 63) | (pso.shader.id << 13); this._opaques.push({hash, model, pass, cmdBuff}); } else { // Transparent objects are sorted by depth back to front, then by by shader id. - hash = (1 << 63) | (pso.shader.id << 13); + const hash = (1 << 63) | (pso.shader.id << 13); this._transparents.push({hash, model, pass, cmdBuff}); } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 760c0a2e4c..7218696242 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,19 +1,18 @@ -import { RenderScene } from "./render-scene"; -import Node from "../../scene-graph/node"; -import { vec3, mat4, quat } from "../../core/vmath"; -import { frustum } from "../../3d/geom-utils/frustum"; +import { frustum } from '../../3d/geom-utils/frustum'; +import { mat4, quat, vec3 } from '../../core/vmath'; +import Node from '../../scene-graph/node'; +import { RenderScene } from './render-scene'; -export enum NodeSpace -{ - LOCAL, - PARENT, - WORLD, -}; +export enum NodeSpace { + LOCAL, + PARENT, + WORLD, +} export enum CameraProjection { PERSPECTIVE, ORTHO, -}; +} export class Camera { @@ -27,22 +26,22 @@ export class Camera { private _fov: number; private _nearClip: number; private _farClip: number; - private _matView: mat4 = new mat4; - private _matProj: mat4 = new mat4; - private _matViewProj: mat4 = new mat4; - private _matViewProjInv: mat4 = new mat4; - private _position: vec3 = new vec3; - private _rotation: quat = new quat; - private _direction: vec3 = new vec3; - private _frustum: frustum = new frustum; + private _matView: mat4 = new mat4(); + private _matProj: mat4 = new mat4(); + private _matViewProj: mat4 = new mat4(); + private _matViewProjInv: mat4 = new mat4(); + private _position: vec3 = new vec3(); + private _rotation: quat = new quat(); + private _direction: vec3 = new vec3(); + private _frustum: frustum = new frustum(); - constructor(scene: RenderScene, name: string) { + constructor (scene: RenderScene, name: string) { this._scene = scene; this._name = name; - this._node = scene.createNode({ name: name + "Node", isStatic: false }); + this._node = scene.createNode({ name: name + 'Node', isStatic: false }); this._proj = CameraProjection.PERSPECTIVE; - let window = scene.root.mainWindow; + const window = scene.root.mainWindow; if (window) { this._width = window.width; this._height = window.height; @@ -57,13 +56,13 @@ export class Camera { this._farClip = 10000.0; } - public resize(width: number, height: number) { + public resize (width: number, height: number) { this._width = width; this._height = height; this._aspect = this._width / this._height; } - public update() { + public update () { // view matrix this._node.getWorldRT(this._matView); mat4.invert(this._matView, this._matView); @@ -72,8 +71,8 @@ export class Camera { if (this._proj === CameraProjection.PERSPECTIVE) { mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip); } else { - let x = this._width; - let y = this._height; + const x = this._width; + const y = this._height; mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip); } @@ -84,110 +83,110 @@ export class Camera { this._frustum.update(this._matViewProj, this._matViewProjInv); } - public set fov(fov: number) { + public set fov (fov: number) { this._fov = fov; } - public set nearClip(nearClip: number) { + public set nearClip (nearClip: number) { this._nearClip = nearClip; } - public set farClip(farClip: number) { + public set farClip (farClip: number) { this._farClip = farClip; } - public get scene(): RenderScene { + public get scene (): RenderScene { return this._scene; } - public get name(): string { + public get name (): string { return this._name; } - public get node(): Node { + public get node (): Node { return this._node; } - public get width(): number { + public get width (): number { return this._width; } - public get height(): number { + public get height (): number { return this._height; } - public get aspect(): number { + public get aspect (): number { return this._aspect; } - public get fov(): number { + public get fov (): number { return this._fov; } - public get nearClip(): number { + public get nearClip (): number { return this._nearClip; } - public get farClip(): number { + public get farClip (): number { return this._farClip; } - public get matView(): mat4 { + public get matView (): mat4 { return this._matView; } - public get matProj(): mat4 { + public get matProj (): mat4 { return this._matProj; } - public get matViewProj(): mat4 { + public get matViewProj (): mat4 { return this._matViewProj; } - public get matViewProjInv(): mat4 { + public get matViewProjInv (): mat4 { return this._matViewProjInv; } - public get frustum(): frustum { + public get frustum (): frustum { return this._frustum; } - public get position(): vec3 { - this._node.getWorldPosition(this._position); + public get position (): vec3 { + this._node.getPosition(this._position); return this._position; } - public rotate(rot: quat, ns?: NodeSpace) { - let space = (ns !== undefined? ns : NodeSpace.LOCAL); - if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + public rotate (rot: quat, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.rotate(rot); } else if (space === NodeSpace.WORLD) { this._node.rotateWorld(rot); } } - public rotateFromAxisAngle(axis: vec3, rad: number, ns?: NodeSpace) { + public rotateFromAxisAngle (axis: vec3, rad: number, ns?: NodeSpace) { quat.fromAxisAngle(this._rotation, axis, rad); - let space = (ns !== undefined? ns : NodeSpace.LOCAL); - if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.rotate(this._rotation); } else if (space === NodeSpace.WORLD) { this._node.rotateWorld(this._rotation); } } - public setRotation(rot: quat, ns?: NodeSpace) { - let space = (ns !== undefined? ns : NodeSpace.LOCAL); - if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + public setRotation (rot: quat, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.setRotation(rot); } else if (space === NodeSpace.WORLD) { this._node.setWorldRotation(rot); } } - public pitch(rad: number, ns?: NodeSpace) { - let space = (ns !== undefined? ns : NodeSpace.LOCAL); - if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + public pitch (rad: number, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.getRotation(this._rotation); quat.toAxisX(this._direction, this._rotation); this.rotateFromAxisAngle(this._direction, rad, ns); @@ -198,9 +197,9 @@ export class Camera { } } - public yaw(rad: number, ns?: NodeSpace) { - let space = (ns !== undefined? ns : NodeSpace.LOCAL); - if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + public yaw (rad: number, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.getRotation(this._rotation); quat.toAxisY(this._direction, this._rotation); this.rotateFromAxisAngle(this._direction, rad, ns); @@ -208,12 +207,12 @@ export class Camera { this._node.getWorldRotation(this._rotation); quat.toAxisY(this._direction, this._rotation); this.rotateFromAxisAngle(this._direction, rad, ns); - } + } } - public roll(rad: number, ns?: NodeSpace) { - let space = (ns !== undefined? ns : NodeSpace.LOCAL); - if(space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { + public roll (rad: number, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { this._node.getRotation(this._rotation); quat.toAxisZ(this._direction, this._rotation); this.rotateFromAxisAngle(this._direction, rad, ns); @@ -221,25 +220,25 @@ export class Camera { this._node.getWorldRotation(this._rotation); quat.toAxisZ(this._direction, this._rotation); this.rotateFromAxisAngle(this._direction, rad, ns); - } + } } - public set target(target: vec3) { + public set target (target: vec3) { this._node.lookAt(target); } - public get direction(): vec3 { + public get direction (): vec3 { this._node.getRotation(this._rotation); vec3.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); return this._direction; } - public set position(pos: vec3) { + public set position (pos: vec3) { this._node.setWorldPosition(pos.x, pos.y, pos.z); } - public set direction(dir: vec3) { + public set direction (dir: vec3) { quat.rotationTo(this._rotation, vec3.UNIT_Z, dir); this._node.setRotation(this._rotation); } -}; +} From 7c6d60c60c172f6f4368c12b9d2f9630bc8461dc Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 9 Jan 2019 20:56:57 +0800 Subject: [PATCH 077/267] fix some defects --- cocos/3d/framework/camera-component.js | 4 +- cocos/3d/framework/light-component.js | 4 +- cocos/3d/framework/model-component.js | 6 +-- cocos/components/component.js | 4 +- cocos/renderer/scene/model.ts | 64 ++++++++++++++------------ cocos/scene-graph/scene.js | 4 +- 6 files changed, 47 insertions(+), 39 deletions(-) diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index c520e15a45..44059b77f3 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -306,7 +306,7 @@ export default class CameraComponent extends Component { } onLoad() { - this._camera = this._renderScene.createCamera(this.name); + this._camera = this.getRenderScene().createCamera(this.name); this.projection = this._projection; this.priority = this._priority; this.fov = this._fov; @@ -331,7 +331,7 @@ export default class CameraComponent extends Component { } onDestroy() { - this._renderScene.destroyCamera(this._camera); + this.getRenderScene().destroyCamera(this._camera); } /** diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js index 05cd5528c0..948e12cc8a 100644 --- a/cocos/3d/framework/light-component.js +++ b/cocos/3d/framework/light-component.js @@ -416,7 +416,7 @@ export default class LightComponent extends Component { } onLoad() { - this._light = this._renderScene.createLight(this.name); + this._light = this.getRenderScene().createLight(this.name); this._light.setNode(this.node); this.type = this._type; this.color = this._color; @@ -442,6 +442,6 @@ export default class LightComponent extends Component { } onDestroy() { - this._renderScene.destroyLight(this._light); + this.getRenderScene().destroyLight(this._light); } } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 27893eef00..e9c0f1c5e7 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -190,7 +190,7 @@ export default class ModelComponent extends RenderableComponent { onDestroy() { for (let i = 0; i < this._models.length; ++i) { - this._renderScene.destroyModel(this._models[i]); + this.getRenderScene().destroyModel(this._models[i]); } } @@ -208,12 +208,12 @@ export default class ModelComponent extends RenderableComponent { this._updateModelParams(); for (let i = 0; i < oldModels.length; ++i) { - this._renderScene.destroyModel(oldModels[i]); + this.getRenderScene().destroyModel(oldModels[i]); } } _createModel() { - return this._renderScene.createModel(Model); + return this.getRenderScene().createModel(Model); } _updateModelParams() { diff --git a/cocos/components/component.js b/cocos/components/component.js index af3bba71c3..a6ba88a08a 100644 --- a/cocos/components/component.js +++ b/cocos/components/component.js @@ -195,8 +195,8 @@ class Component extends CCObject { static system = null; - get _renderScene() { - return this.node._scene._renderScene; + getRenderScene(index = 0) { + return this.node._scene._renderScenes[index]; } constructor () { diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index ecc36b2b6f..8b6a072261 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -41,11 +41,11 @@ export default class Model { private _material: Material | null; private _cmdBuffers: GFXCommandBuffer[]; private _localUniforms: UBOLocal | null; - private _localUBO: GFXBuffer; + private _localUBO: GFXBuffer | null; /** * Setup a default empty model */ - constructor () { + constructor() { this._scene = null; this._id = 0; this._enable = false; @@ -62,10 +62,11 @@ export default class Model { this._cameraID = -1; this._userKey = -1; this._castShadow = false; - this._boundingShape = null; + this._boundingShape = aabb.create(0, 0, 0, 50, 50, 50); this._material = null; this._cmdBuffers = new Array(); this._localUniforms = null; + this._localUBO = null; } initialize() { @@ -76,10 +77,11 @@ export default class Model { size: UBOLocal.SIZE, stride: UBOLocal.SIZE, }); - this._localUBO.update(this._localUniforms.view); + if (this._localUBO) + this._localUBO.update(this._localUniforms.view); } - set scene (scene: RenderScene | null) { + set scene(scene: RenderScene | null) { this._scene = scene; if (this._scene) { @@ -87,15 +89,15 @@ export default class Model { } } - get scene (): RenderScene | null { + get scene(): RenderScene | null { return this._scene; } - get id (): number { + get id(): number { return this._id; } - public _updateTransform () { + public _updateTransform() { if (!this._node._hasChanged || !this._boundingShape) { return; } this._node.updateWorldTransformFull(); this._bsModelSpace.transform(this._node._mat, this._node._pos, @@ -105,10 +107,13 @@ export default class Model { updateRenderData() { mat4.array(_temp_floatx16, this._node._mat); this._node._mat.invert(_temp_mat4); - this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); + if (this._localUniforms) + this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); mat4.array(_temp_floatx16, _temp_mat4); - this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); - this._localUBO.update(this._localUniforms.view); + if (this._localUniforms) + this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); + if (this._localUBO) + this._localUBO.update(this._localUniforms.view); } /** @@ -116,17 +121,17 @@ export default class Model { * @param {vec3} minPos the min position of the model * @param {vec3} maxPos the max position of the model */ - public createBoundingShape (minPos: Vec3, maxPos: Vec3) { + public createBoundingShape(minPos: Vec3, maxPos: Vec3) { if (!minPos || !maxPos) { return; } this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); this._boundingShape = aabb.clone(this._bsModelSpace); } - public enable (isEnable: boolean) { + public enable(isEnable: boolean) { this._isEnable = isEnable; } - public isEnable (): boolean { + public isEnable(): boolean { return this._isEnable; } @@ -134,7 +139,7 @@ export default class Model { * Get the hosting node of this camera * @returns {Node} the hosting node */ - get node (): Node { + get node(): Node { return this._node; } @@ -142,7 +147,7 @@ export default class Model { * Set the hosting node of this model * @param {Node} node the hosting node */ - set node (node: Node) { + set node(node: Node) { this._node = node; } @@ -150,7 +155,7 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - set inputAssembler (ia: GFXInputAssembler) { + set inputAssembler(ia: GFXInputAssembler) { this._inputAssembler = ia; } @@ -158,7 +163,7 @@ export default class Model { * Set the model effect * @param {?Effect} effect the effect to use */ - public setEffect (effect: Effect) { + public setEffect(effect: Effect) { if (effect) { this._effect = effect; // this._defines = effect.extractDefines(Object.create(null)); @@ -170,7 +175,7 @@ export default class Model { } } - set material (material: Material) { + set material(material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { this.recordCommandBuffer(i); @@ -183,8 +188,8 @@ export default class Model { } } - public recordCommandBuffer (index: number) { - const pass = ( this._material as Material).passes[index]; + public recordCommandBuffer(index: number) { + const pass = (this._material as Material).passes[index]; const cmdBufferInfo = { allocator: cc.director.root.device.commandAllocator, type: GFXCommandBufferType.SECONDARY, @@ -192,13 +197,14 @@ export default class Model { if (this._cmdBuffers[index] == null) { this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); } - pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO); + if (this._localUBO) + pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO); pass.bindingLayout.update(); this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); - this._cmdBuffers[index].bindInputAssembler( this._inputAssembler as GFXInputAssembler); - this._cmdBuffers[index].draw( this._inputAssembler as GFXInputAssembler); + this._cmdBuffers[index].bindInputAssembler(this._inputAssembler as GFXInputAssembler); + this._cmdBuffers[index].draw(this._inputAssembler as GFXInputAssembler); this._cmdBuffers[index].end(); } @@ -206,15 +212,15 @@ export default class Model { * Set the user key * @param {number} key */ - set userKey (key: number) { + set userKey(key: number) { this._userKey = key; } - get passes (): Pass[] { - return ( this._material as Material).passes; + get passes(): Pass[] { + return (this._material as Material).passes; } - get commandBuffers (): GFXCommandBuffer[] { + get commandBuffers(): GFXCommandBuffer[] { return this._cmdBuffers; } @@ -222,7 +228,7 @@ export default class Model { * Extract a drawing item * @param {Object} out the receiving item */ - public extractDrawItem (out) { + public extractDrawItem(out) { out.model = this; out.node = this._node; out.ia = this._inputAssembler; diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index 9ff302b510..75838edfc7 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -41,7 +41,7 @@ import { RenderScene } from '../renderer/scene/render-scene'; @ccclass("cc.Scene") export default class Scene extends Node { - _renderScene = new RenderScene(); + _renderScenes = new Array(); constructor(name) { super(name); @@ -55,6 +55,8 @@ export default class Scene extends Node { // cache all depend assets for auto release this.dependAssets = null; + + this._renderScenes.push(new RenderScene()); } /** From def1ef4355fcd4ecfea3b3497b5f6c9303e86bb8 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 10 Jan 2019 09:51:15 +0800 Subject: [PATCH 078/267] render texture --- cocos/assets/render-texture.ts | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts index 72d001bcc6..30e1ba5699 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/assets/render-texture.ts @@ -8,17 +8,12 @@ import { RenderPassStage } from '../pipeline/render-pipeline'; import ImageAsset from './image-asset'; import Texture2D from './texture-2d'; -enum DepthStencilFormat { - D24S8 = GFXFormat.D24S8, - - S8 = GFXFormat.R8UI, - - D16 = GFXFormat.D16, -} - -function toGfxDepthStencilFormat (depthStencilFormat: DepthStencilFormat): GFXFormat { - return depthStencilFormat as unknown as GFXFormat; -} +type DSFormat = 'D24S8' | 'S8' | 'D16'; +const _formatMap = { + D24S8: GFXFormat.D24S8, + S8: GFXFormat.R8UI, + D16: GFXFormat.D16, +}; /** * Render textures are textures that can be rendered to. @@ -44,10 +39,10 @@ export default class RenderTexture extends Texture2D { * 初始化 render texture * @param [width] * @param [height] - * @param [depthStencilFormat] + * @param [string] * @method initWithSize */ - public initWithSize (width?: number, height?: number, depthStencilFormat?: DepthStencilFormat) { + public initWithSize (width?: number, height?: number, format?: DSFormat) { this.destroy(); const gfxDevice = this._getGlobalDevice(); @@ -81,11 +76,11 @@ export default class RenderTexture extends Texture2D { return; } - if (depthStencilFormat !== undefined) { + if (format !== undefined) { this._depthStencilTexture = gfxDevice.createTexture({ type: GFXTextureType.TEX2D, usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT, - format: toGfxDepthStencilFormat(depthStencilFormat), + format: _formatMap[format], width: w, height: h, }); @@ -95,7 +90,7 @@ export default class RenderTexture extends Texture2D { this._depthStencilTextureView = gfxDevice.createTextureView({ texture: this._depthStencilTexture, type: GFXTextureViewType.TV2D, - format: toGfxDepthStencilFormat(depthStencilFormat), + format: _formatMap[format], }); } From 430156af5f635cfdba8b46cd1cb596b869ce15a9 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 11:06:42 +0800 Subject: [PATCH 079/267] restructure primitive/box to support wireframed box --- cocos/3d/primitive/box.js | 130 ------------------------- cocos/3d/primitive/box.ts | 174 ++++++++++++++++++++++++++++++++++ cocos/3d/primitive/defines.ts | 76 +++++++++++++++ 3 files changed, 250 insertions(+), 130 deletions(-) delete mode 100644 cocos/3d/primitive/box.js create mode 100644 cocos/3d/primitive/box.ts create mode 100644 cocos/3d/primitive/defines.ts diff --git a/cocos/3d/primitive/box.js b/cocos/3d/primitive/box.js deleted file mode 100644 index e9aa1b0873..0000000000 --- a/cocos/3d/primitive/box.js +++ /dev/null @@ -1,130 +0,0 @@ -'use strict'; - -import { vec3 } from '../../core/vmath'; - -let temp1 = vec3.create(0, 0, 0); -let temp2 = vec3.create(0, 0, 0); -let temp3 = vec3.create(0, 0, 0); -let r = vec3.create(0, 0, 0); -let c0 = vec3.create(0, 0, 0); -let c1 = vec3.create(0, 0, 0); -let c2 = vec3.create(0, 0, 0); -let c3 = vec3.create(0, 0, 0); -let c4 = vec3.create(0, 0, 0); -let c5 = vec3.create(0, 0, 0); -let c6 = vec3.create(0, 0, 0); -let c7 = vec3.create(0, 0, 0); - -/** - * @param {Number} width - * @param {Number} height - * @param {Number} length - * @param {Object} opts - * @param {Number} opts.widthSegments - * @param {Number} opts.heightSegments - * @param {Number} opts.lengthSegments - */ -export default function (width = 1, height = 1, length = 1, opts = {}) { - let ws = opts.widthSegments !== undefined ? opts.widthSegments : 1; - let hs = opts.heightSegments !== undefined ? opts.heightSegments : 1; - let ls = opts.lengthSegments !== undefined ? opts.lengthSegments : 1; - let inv = opts.invWinding !== undefined ? opts.invWinding : false; - - let hw = width * 0.5; - let hh = height * 0.5; - let hl = length * 0.5; - - let corners = [ - vec3.set(c0, -hw, -hh, hl), - vec3.set(c1, hw, -hh, hl), - vec3.set(c2, hw, hh, hl), - vec3.set(c3, -hw, hh, hl), - vec3.set(c4, hw, -hh, -hl), - vec3.set(c5, -hw, -hh, -hl), - vec3.set(c6, -hw, hh, -hl), - vec3.set(c7, hw, hh, -hl), - ]; - - let faceAxes = [ - [ 2, 3, 1 ], // FRONT - [ 4, 5, 7 ], // BACK - [ 7, 6, 2 ], // TOP - [ 1, 0, 4 ], // BOTTOM - [ 1, 4, 2 ], // RIGHT - [ 5, 0, 6 ] // LEFT - ]; - - let faceNormals = [ - [ 0, 0, 1 ], // FRONT - [ 0, 0, -1 ], // BACK - [ 0, 1, 0 ], // TOP - [ 0, -1, 0 ], // BOTTOM - [ 1, 0, 0 ], // RIGHT - [ -1, 0, 0 ] // LEFT - ]; - - let positions = []; - let normals = []; - let uvs = []; - let indices = []; - let minPos = vec3.create(-hw, -hh, -hl); - let maxPos = vec3.create(hw, hh, hl); - let boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl); - - function _buildPlane (side, uSegments, vSegments) { - let u, v; - let ix, iy; - let offset = positions.length / 3; - let faceAxe = faceAxes[side]; - let faceNormal = faceNormals[side]; - - for (iy = 0; iy <= vSegments; iy++) { - for (ix = 0; ix <= uSegments; ix++) { - u = ix / uSegments; - v = iy / vSegments; - - vec3.lerp(temp1, corners[faceAxe[0]], corners[faceAxe[1]], u); - vec3.lerp(temp2, corners[faceAxe[0]], corners[faceAxe[2]], v); - vec3.sub(temp3, temp2, corners[faceAxe[0]]); - vec3.add(r, temp1, temp3); - - positions.push(r.x, r.y, r.z); - normals.push(faceNormal[0], faceNormal[1], faceNormal[2]); - uvs.push(u, v); - - if ((ix < uSegments) && (iy < vSegments)) { - let useg1 = uSegments + 1; - let a = ix + iy * useg1; - let b = ix + (iy + 1) * useg1; - let c = (ix + 1) + (iy + 1) * useg1; - let d = (ix + 1) + iy * useg1; - - if (inv) { - indices.push(offset + a, offset + b, offset + d); - indices.push(offset + d, offset + b, offset + c); - } else { - indices.push(offset + a, offset + d, offset + b); - indices.push(offset + b, offset + d, offset + c); - } - } - } - } - } - - _buildPlane(0, ws, hs); // FRONT - _buildPlane(4, ls, hs); // RIGHT - _buildPlane(1, ws, hs); // BACK - _buildPlane(5, ls, hs); // LEFT - _buildPlane(3, ws, ls); // BOTTOM - _buildPlane(2, ws, ls); // TOP - - return { - positions, - normals, - uvs, - indices, - minPos, - maxPos, - boundingRadius - }; -} diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts new file mode 100644 index 0000000000..0152d15079 --- /dev/null +++ b/cocos/3d/primitive/box.ts @@ -0,0 +1,174 @@ +import { GFXPrimitiveMode } from '../../gfx/define'; +import { IGeometry, IGeometryOptions, normalizeGeometryOptions, WindingOrder } from './defines'; + +interface IBoxOptions extends IGeometryOptions { + /** + * Box extent on X-axis. + */ + length: number; + + /** + * Box extent on Z-axis. + */ + width: number; + + /** + * Box extent on Y-axis. + */ + height: number; +} + +/** + * This function generates a box with specified extents and centered at origin, + * but may emplaced through `center` option). + * @param options Options. + */ +export default function box (options: IBoxOptions): IGeometry { + normalizeGeometryOptions(options); + + const right = options.length / 2; + const left = -right; + const top = options.height / 2; + const bottom = -top; + const near = options.width / 2; + const far = -near; + const center = options.center ? { + x: options.center.x || 0, + y: options.center.y || 0, + z: options.center.z || 0, + } : { + x: 0, + y: 0, + z: 0, + }; + + const vertices: number[] = []; + const addVertex = (x: number, y: number, z: number) => { + vertices.push(x + center.x, y + center.y, z + center.z); + }; + addVertex(left, top, near); + addVertex(left, bottom, near); + addVertex(right, bottom, near); + addVertex(right, top, near); + addVertex(left, top, far); + addVertex(left, bottom, far); + addVertex(right, bottom, far); + addVertex(right, top, far); + + let indices: number[] = []; + let normals: number[] | undefined; + let primitiveType: GFXPrimitiveMode = GFXPrimitiveMode.POINT_LIST; + if (options.wireframed) { + primitiveType = GFXPrimitiveMode.LINE_LIST; + indices = indices.concat([ + 0, 1, 1, 2, 2, 3, 3, 0, // Front quad + 4, 5, 5, 6, 6, 7, 7, 4, // Back quad + 0, 4, 1, 5, 2, 6, 3, 7, // Side lines + ]); + } else { + primitiveType = GFXPrimitiveMode.TRIANGLE_LIST; + type FaceNormal = [ number, number, number ]; + type FaceQuad = [ + number, // Left top + number, // Left bottom + number, // Right bottom + number // Right top + ]; + interface IFaceInfo { + quad: FaceQuad; + normal: FaceNormal; + } + interface IFaceInfos { + front: IFaceInfo; + right: IFaceInfo; + back: IFaceInfo; + left: IFaceInfo; + top: IFaceInfo; + bottom: IFaceInfo; + } + + const addTri = (i: number, j: number, k: number) => { + if (options.windingOrder === WindingOrder.CounterClockwise) { + indices.push(i, j, k); + } else { + indices.push(i, k, j); + } + }; + + const addQuad = (faceQuad: FaceQuad) => { + const lt = faceQuad[0]; + const lb = faceQuad[1]; + const rb = faceQuad[2]; + const rt = faceQuad[3]; + addTri(lt, lb, rb); + addTri(lt, rb, rt); + }; + + const addNormal = (faceNormal: FaceNormal) => { + const x = faceNormal[0]; + const y = faceNormal[1]; + const z = faceNormal[2]; + if (options.windingOrder === WindingOrder.CounterClockwise) { + normals!.push(x, y, z); + } else { + normals!.push(-x, -y, -z); + } + }; + + const addFace = (face: IFaceInfo) => { + addQuad(face.quad); + if (normals) { + addNormal(face.normal); + } + }; + + const faceInfos: IFaceInfos = { + front: { + quad: [0, 1, 2, 3], + normal: [0, 0, 1], + }, + right: { + quad: [3, 2, 6, 7], + normal: [1, 0, 0], + }, + back: { + quad: [7, 6, 5, 4], + normal: [0, 0, -1], + }, + left: { + quad: [4, 5, 1, 0], + normal: [-1, 0, 0], + }, + top: { + quad: [4, 0, 3, 7], + normal: [0, 1, 0], + }, + bottom: { + quad: [1, 5, 6, 2], + normal: [0, -1, 0], + }, + }; + + if (options.includeNormal) { + normals = []; + } + addFace(faceInfos.front); + addFace(faceInfos.right); + addFace(faceInfos.back); + addFace(faceInfos.left); + addFace(faceInfos.top); + addFace(faceInfos.bottom); + } + + const result: IGeometry = { + primitiveType, + vertices, + indices, + }; + + if (normals) { + result.normals = normals; + } + + return result; +} diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts new file mode 100644 index 0000000000..9a3edcd280 --- /dev/null +++ b/cocos/3d/primitive/defines.ts @@ -0,0 +1,76 @@ +import { GFXPrimitiveMode } from '../../gfx/define'; + +export enum WindingOrder { + /** + * Clockwise. + */ + Clockwise, + + /** + * Counter-clockwise. + */ + CounterClockwise, +} + +export interface IGeometryOptions { + /** + * Whether generated wireframed geometry. Default to false. + */ + wireframed?: boolean; + + /** + * The winding order. Default to counter-clockwise. + */ + windingOrder?: WindingOrder; + + /** + * Whether to include normal. Default to true. + */ + includeNormal?: boolean; + + /** + * The center of the geometry. Default to (0, 0, 0). + */ + center?: { + x?: number; + y?: number; + z?: number; + }; +} + +export function normalizeGeometryOptions (options: IGeometryOptions) { + options.wireframed = options.wireframed || false; + options.windingOrder = options.windingOrder === undefined ? + WindingOrder.CounterClockwise : options.windingOrder; + options.includeNormal = options.includeNormal === undefined ? + true : options.includeNormal; + if (!options.center) { + options.center = {}; + } + options.center.x = options.center.x || 0; + options.center.y = options.center.y || 0; + options.center.z = options.center.z || 0; + return options; +} + +export interface IGeometry { + /** + * Topology of the geometry vertices. + */ + primitiveType: GFXPrimitiveMode; + + /** + * Vertex positions. + */ + vertices: number[]; + + /** + * Gemetry indices, if one needs indexed-draw. + */ + indices?: number[]; + + /** + * Vertex normals. + */ + normals?: number[]; +} From d152fc871e9692687c266469feb50a53d7f16e8b Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 9 Jan 2019 18:58:56 +0800 Subject: [PATCH 080/267] linter fix --- cocos/components/component.d.ts | 2 ++ cocos/renderer/core/program-lib.ts | 26 ++++++++--------- cocos/renderer/scene/camera.ts | 43 ++++++++++++++-------------- cocos/renderer/scene/render-scene.ts | 2 +- playground/simple.html | 4 +-- 5 files changed, 40 insertions(+), 37 deletions(-) diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index 7e20bc95d2..1deb53422d 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -29,6 +29,7 @@ import { getClassName, value } from '../core/utils/js'; import IDGenerator from '../core/utils/id-generator'; import { ccclass, property } from '../core/data/class-decorator'; import Node from '../scene-graph/node'; +import { RenderScene } from '../renderer/scene/render-scene'; export class Component extends CCObject { node: Node; @@ -36,6 +37,7 @@ export class Component extends CCObject { enabled: boolean; enabledInHierarchy: boolean; + getRenderScene(index?: number): RenderScene | undefined; addComponent(typeOrClassName: Function | string): Component; getComponent(typeOrClassName: Function | string): Component; getComponents(typeOrClassName: Function | string): Component[]; diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 470fdb4e33..5541098bd1 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -7,11 +7,11 @@ import { GFXShader, GFXUniformBlock, GFXUniform } from '../../gfx/shader'; import { IDefineMap } from './effect'; import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; -function _generateDefines( +function _generateDefines ( device: GFXDevice, defs: IDefineMap, tDefs: IDefineInfo[], - deps: Record + deps: Record, ) { const defines: string[] = []; for (const { name } of tDefs) { @@ -28,21 +28,21 @@ function _generateDefines( } let _shdID = 0; -interface DefineRecord extends IDefineInfo { +interface IDefineRecord extends IDefineInfo { _map: (value: any) => number; _offset: number; } -interface ProgramInfo extends IShaderInfo { +interface IProgramInfo extends IShaderInfo { id: number; - defines: DefineRecord[]; + defines: IDefineRecord[]; } export class ProgramLib { protected _device: GFXDevice; protected _precision: string; - protected _templates: Record; + protected _templates: Record; protected _cache: Record; - constructor(device: GFXDevice) { + constructor (device: GFXDevice) { this._device = device; this._precision = `precision highp float;\n`; this._templates = {}; @@ -65,9 +65,9 @@ export class ProgramLib { * }; * programLib.define(program); */ - public define(prog: IShaderInfo) { + public define (prog: IShaderInfo) { if (this._templates[prog.name]) { return; } - const tmpl = Object.assign({ id: ++_shdID }, prog); + const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; tmpl.vert = this._precision + prog.vert; tmpl.frag = this._precision + prog.frag; @@ -89,18 +89,18 @@ export class ProgramLib { this._templates[prog.name] = tmpl; } - public getTemplate(name: string) { + public getTemplate (name: string) { return this._templates[name]; } /** * Does this library has the specified program? */ - public hasProgram(name: string) { + public hasProgram (name: string) { return this._templates[name] !== undefined; } - public getKey(name: string, defines: IDefineMap) { + public getKey (name: string, defines: IDefineMap) { const tmpl = this._templates[name]; let key = 0; for (const tmplDef of tmpl.defines) { @@ -113,7 +113,7 @@ export class ProgramLib { return key << 8 | (tmpl.id & 0xff); } - public getGFXShader(name: string, defines: IDefineMap = {}) { + public getGFXShader (name: string, defines: IDefineMap = {}) { const key = this.getKey(name, defines); let program = this._cache[key]; if (program !== undefined) { diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 7218696242..1b2e704dec 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -87,14 +87,26 @@ export class Camera { this._fov = fov; } + public get fov (): number { + return this._fov; + } + public set nearClip (nearClip: number) { this._nearClip = nearClip; } + public get nearClip (): number { + return this._nearClip; + } + public set farClip (farClip: number) { this._farClip = farClip; } + public get farClip (): number { + return this._farClip; + } + public get scene (): RenderScene { return this._scene; } @@ -119,18 +131,6 @@ export class Camera { return this._aspect; } - public get fov (): number { - return this._fov; - } - - public get nearClip (): number { - return this._nearClip; - } - - public get farClip (): number { - return this._farClip; - } - public get matView (): mat4 { return this._matView; } @@ -151,11 +151,6 @@ export class Camera { return this._frustum; } - public get position (): vec3 { - this._node.getPosition(this._position); - return this._position; - } - public rotate (rot: quat, ns?: NodeSpace) { const space = (ns !== undefined ? ns : NodeSpace.LOCAL); if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { @@ -227,18 +222,24 @@ export class Camera { this._node.lookAt(target); } - public get direction (): vec3 { - this._node.getRotation(this._rotation); - vec3.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); - return this._direction; + public get position (): vec3 { + this._node.getPosition(this._position); + return this._position; } public set position (pos: vec3) { this._node.setWorldPosition(pos.x, pos.y, pos.z); } + public get direction (): vec3 { + this._node.getRotation(this._rotation); + vec3.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); + return this._direction; + } + public set direction (dir: vec3) { quat.rotationTo(this._rotation, vec3.UNIT_Z, dir); this._node.setRotation(this._rotation); } + } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 52a0135342..be8180e5d1 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -128,7 +128,7 @@ export class RenderScene { public destroyModel(model: Model) { for (let i = 0; i < this._models.length; ++i) { if (this._models[i] === model) { - this._models.slice(i); + this._models.splice(i, 1); return; } } diff --git a/playground/simple.html b/playground/simple.html index 66149dabee..10f1d6270f 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -33,7 +33,7 @@ function onStart() { const $body = document.body; const bcr = $body.getBoundingClientRect(); - // cc.view.setCanvasSize(bcr.width, bcr.height); + cc.view.setCanvasSize(bcr.width, bcr.height); window.addEventListener('resize', () => { const bcr = $body.getBoundingClientRect(); cc.view.setCanvasSize(bcr.width, bcr.height); @@ -98,4 +98,4 @@ - \ No newline at end of file + From 324914df02b453e67ca73cc3bb463040213859f5 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Thu, 10 Jan 2019 14:32:10 +0800 Subject: [PATCH 081/267] fix model bug --- cocos/3d/builtin/effects.js | 6 +-- cocos/3d/framework/camera-component.js | 47 +++++++++++------- cocos/3d/framework/light-component.js | 56 +++++++++++++-------- cocos/3d/framework/model-component.js | 35 +++++++------ cocos/components/component.js | 4 +- cocos/pipeline/forward/test-model-stage.ts | 3 +- cocos/renderer/utils.js | 58 ++-------------------- cocos/scene-graph/scene.js | 5 +- 8 files changed, 95 insertions(+), 119 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 1ef5140250..a177314e50 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -2,18 +2,18 @@ export default [ { "name": "test", "techniques": [{"queue": 0, "lod": 500, "passes": [{"stage": 100, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}], "priority": 0}], - "properties": {"u_color": {"type": 17, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": null}}, + "properties": {"u_color": {"type": 16, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": null}}, "shaders": [ { "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", "vert": ` attribute vec3 a_position; - attribute vec2 a_texCoord; + attribute vec2 a_uv0; uniform mat4 cc_matWorld; varying vec2 v_texCoord; void main() { gl_Position = cc_matWorld*vec4(a_position, 1.0); - v_texCoord = a_texCoord; + v_texCoord = a_uv0; } `, "frag": ` diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index 44059b77f3..b556cb3904 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -134,7 +134,8 @@ export default class CameraComponent extends Component { if (this._projection === CameraProjection.Ortho) { type = renderer.PROJ_ORTHO; } - this._camera.setType(type); + if (this.enabled) + this._camera.setType(type); } /** @@ -150,7 +151,8 @@ export default class CameraComponent extends Component { set priority(val) { this._priority = val; - this._camera.setPriority(val); + if (this.enabled) + this._camera.setPriority(val); } /** @@ -166,7 +168,8 @@ export default class CameraComponent extends Component { set fov(val) { this._fov = val; - this._camera.setFov(toRadian(val)); + if (this.enabled) + this._camera.setFov(toRadian(val)); } /** @@ -182,7 +185,8 @@ export default class CameraComponent extends Component { set orthoHeight(val) { this._orthoHeight = val; - this._camera.setOrthoHeight(val); + if (this.enabled) + this._camera.setOrthoHeight(val); } /** @@ -198,7 +202,8 @@ export default class CameraComponent extends Component { set near(val) { this._near = val; - this._camera.setNear(val); + if (this.enabled) + this._camera.setNear(val); } /** @@ -214,7 +219,8 @@ export default class CameraComponent extends Component { set far(val) { this._far = val; - this._camera.setFar(val); + if (this.enabled) + this._camera.setFar(val); } /** @@ -230,7 +236,8 @@ export default class CameraComponent extends Component { set color(val) { this._color = val; - this._camera.setColor(val.r / 255, val.g / 255, val.b / 255, val.a / 255); + if (this.enabled) + this._camera.setColor(val.r / 255, val.g / 255, val.b / 255, val.a / 255); } /** @@ -246,7 +253,8 @@ export default class CameraComponent extends Component { set depth(val) { this._depth = val; - this._camera.setDepth(val); + if (this.enabled) + this._camera.setDepth(val); } /** @@ -262,7 +270,8 @@ export default class CameraComponent extends Component { set stencil(val) { this._stencil = val; - this._camera.setStencil(val); + if (this.enabled) + this._camera.setStencil(val); } /** @@ -280,7 +289,8 @@ export default class CameraComponent extends Component { set clearFlags(val) { this._clearFlags = val; - this._camera.setClearFlags(val); + if (this.enabled) + this._camera.setClearFlags(val); } /** @@ -296,7 +306,8 @@ export default class CameraComponent extends Component { set rect(val) { this._rect = val; - this._camera.setRect(val.x, val.y, val.width, val.height); + if (this.enabled) + this._camera.setRect(val.x, val.y, val.width, val.height); } static Projection = CameraProjection; @@ -306,7 +317,11 @@ export default class CameraComponent extends Component { } onLoad() { - this._camera = this.getRenderScene().createCamera(this.name); + + } + + onEnable() { + this._camera = this._getRenderScene().createCamera(this.name); this.projection = this._projection; this.priority = this._priority; this.fov = this._fov; @@ -322,16 +337,12 @@ export default class CameraComponent extends Component { this._camera.setNode(this.node); } - onEnable() { - this._camera._enable = this.enabled; - } - onDisable() { - this._camera._enable = this.enabled; + this._getRenderScene().destroyCamera(this._camera); } onDestroy() { - this.getRenderScene().destroyCamera(this._camera); + } /** diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js index 948e12cc8a..01493bba33 100644 --- a/cocos/3d/framework/light-component.js +++ b/cocos/3d/framework/light-component.js @@ -180,7 +180,8 @@ export default class LightComponent extends Component { } else if (this._type === LightType.Spot) { type = renderer.LIGHT_SPOT; } - this._light.setType(type); + if (this.enabled) + this._light.setType(type); } /** @@ -196,7 +197,8 @@ export default class LightComponent extends Component { set color(val) { this._color = val; - this._light.setColor(val.r / 255, val.g / 255, val.b / 255); + if (this.enabled) + this._light.setColor(val.r / 255, val.g / 255, val.b / 255); } /** @@ -212,7 +214,8 @@ export default class LightComponent extends Component { set intensity(val) { this._intensity = val; - this._light.setIntensity(val); + if (this.enabled) + this._light.setIntensity(val); } /** @@ -228,7 +231,8 @@ export default class LightComponent extends Component { set range(val) { this._range = val; - this._light.setRange(val); + if (this.enabled) + this._light.setRange(val); } /** @@ -244,7 +248,8 @@ export default class LightComponent extends Component { set spotAngle(val) { this._spotAngle = val; - this._light.setSpotAngle(toRadian(val)); + if (this.enabled) + this._light.setSpotAngle(toRadian(val)); } /** @@ -260,7 +265,8 @@ export default class LightComponent extends Component { set spotExp(val) { this._spotExp = val; - this._light.setSpotExp(val); + if (this.enabled) + this._light.setSpotExp(val); } /** @@ -285,7 +291,8 @@ export default class LightComponent extends Component { } else if (val === LightShadowType.Soft) { type = renderer.SHADOW_SOFT; } - this._light.setShadowType(type); + if (this.enabled) + this._light.setShadowType(type); } /** @@ -302,7 +309,8 @@ export default class LightComponent extends Component { set shadowResolution(val) { this._shadowResolution = val; - this._light.setShadowResolution(val); + if (this.enabled) + this._light.setShadowResolution(val); } /** @@ -319,7 +327,8 @@ export default class LightComponent extends Component { set shadowDarkness(val) { this._shadowDarkness = val; - this._light.setShadowDarkness(val); + if (this.enabled) + this._light.setShadowDarkness(val); } /** @@ -336,7 +345,8 @@ export default class LightComponent extends Component { set shadowMinDepth(val) { this._shadowMinDepth = val; - this._light.setShadowMinDepth(val); + if (this.enabled) + this._light.setShadowMinDepth(val); } /** @@ -353,7 +363,8 @@ export default class LightComponent extends Component { set shadowMaxDepth(val) { this._shadowMaxDepth = val; - this._light.setShadowMaxDepth(val); + if (this.enabled) + this._light.setShadowMaxDepth(val); } /** @@ -370,7 +381,8 @@ export default class LightComponent extends Component { set shadowDepthScale(val) { this._shadowDepthScale = val; - this._light.setShadowDepthScale(val); + if (this.enabled) + this._light.setShadowDepthScale(val); } /** @@ -387,7 +399,8 @@ export default class LightComponent extends Component { set shadowFrustumSize(val) { this._shadowFrustumSize = val; - this._light.setShadowFrustumSize(val); + if (this.enabled) + this._light.setShadowFrustumSize(val); } /** @@ -404,7 +417,8 @@ export default class LightComponent extends Component { set shadowBias(val) { this._shadowBias = val; - this._light.setShadowBias(val); + if (this.enabled) + this._light.setShadowBias(val); } static Type = LightType; @@ -416,7 +430,11 @@ export default class LightComponent extends Component { } onLoad() { - this._light = this.getRenderScene().createLight(this.name); + + } + + onEnable() { + this._light = this._getRenderScene().createLight(this.name); this._light.setNode(this.node); this.type = this._type; this.color = this._color; @@ -433,15 +451,11 @@ export default class LightComponent extends Component { this.shadowBias = this._shadowBias; } - onEnable() { - this._light._enable = this.enabled; - } - onDisable() { - this._light._enable = this.enabled; + this._getRenderScene().destroyLight(this._light); } onDestroy() { - this.getRenderScene().destroyLight(this._light); + } } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index e9c0f1c5e7..9b6807e7fa 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -171,49 +171,42 @@ export default class ModelComponent extends RenderableComponent { } onLoad() { + + } + + onEnable() { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); } - onEnable() { - for (let i = 0; i < this._models.length; ++i) { - this._models[i]._enable = this.enabled; - } - } - onDisable() { for (let i = 0; i < this._models.length; ++i) { - this._models[i]._enable = this.enabled; + this._getRenderScene().destroyModel(this._models[i]); } + this._models.splice(0); } onDestroy() { - for (let i = 0; i < this._models.length; ++i) { - this.getRenderScene().destroyModel(this._models[i]); - } + } _updateModels() { + if (!this.enabled) + return; let meshCount = this._mesh ? this._mesh.subMeshCount : 0; - let oldModels = this._models; - this._models = new Array(meshCount); for (let i = 0; i < meshCount; ++i) { let model = this._createModel(); model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); - this._models[i] = model; + this._models.push(model); } this._updateModelParams(); - - for (let i = 0; i < oldModels.length; ++i) { - this.getRenderScene().destroyModel(oldModels[i]); - } } _createModel() { - return this.getRenderScene().createModel(Model); + return this._getRenderScene().createModel(Model); } _updateModelParams() { @@ -247,10 +240,14 @@ export default class ModelComponent extends RenderableComponent { * @param {Material} material */ _updateModelMaterial(model, material) { + if (!this.enabled) + return; model.material = material ? material : this._getBuiltinMaterial(); } _updateCastShadow() { + if (!this.enabled) + return; if (this._shadowCastingMode === ModelShadowCastingMode.Off) { for (let i = 0; i < this._models.length; ++i) { let model = this._models[i]; @@ -267,6 +264,8 @@ export default class ModelComponent extends RenderableComponent { } _updateReceiveShadow() { + if (!this.enabled) + return; for (let i = 0; i < this._models.length; ++i) { let model = this._models[i]; if (model._defines['_USE_SHADOW_MAP'] != undefined) { diff --git a/cocos/components/component.js b/cocos/components/component.js index a6ba88a08a..6370572336 100644 --- a/cocos/components/component.js +++ b/cocos/components/component.js @@ -195,8 +195,8 @@ class Component extends CCObject { static system = null; - getRenderScene(index = 0) { - return this.node._scene._renderScenes[index]; + _getRenderScene() { + return this.node._scene._renderScene; } constructor () { diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts index bb4e0d3e10..406ba53e98 100644 --- a/cocos/pipeline/forward/test-model-stage.ts +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -87,8 +87,9 @@ export class TestModelStage extends RenderStage { 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('#ff0000')); + this._material.setProperty('u_color', cc.color('#ff1234')); this._material.inited = true; + this._material.passes[0].update(); this._scene = new Scene(); this._scene._scene = this._scene; diff --git a/cocos/renderer/utils.js b/cocos/renderer/utils.js index 8ec7b9c712..a3821a8693 100644 --- a/cocos/renderer/utils.js +++ b/cocos/renderer/utils.js @@ -32,15 +32,15 @@ export function createIA(device, data) { } let vfmt = []; - vfmt.push({ name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); + vfmt.push({ name: gfx.ATTR_POSITION, format: GFXFormat.RGB32F }); if (data.normals) { - vfmt.push({ name: gfx.ATTR_NORMAL, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); + vfmt.push({ name: gfx.ATTR_NORMAL, format: GFXFormat.RGB32F }); } if (data.uvs) { - vfmt.push({ name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }); + vfmt.push({ name: gfx.ATTR_UV0, format: GFXFormat.RG32F }); } if (data.colors) { - vfmt.push({ name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }); + vfmt.push({ name: gfx.ATTR_COLOR, format: GFXFormat.RGB32F }); } let vb = cc.director.root.device.createBuffer({ @@ -61,56 +61,8 @@ export function createIA(device, data) { ib.update(new Uint16Array(data.indices)); - let attributes = []; - - for (let i = 0; i < vfmt.length; i++) { - let gfxAttr = {}; - gfxAttr.name = vfmt[i].name; - let gfxFormat; - switch (vfmt[i].num) { - case 1: - gfxFormat = 'R'; - break; - case 2: - gfxFormat = 'RG'; - break; - case 3: - gfxFormat = 'RGB'; - break; - case 4: - gfxFormat = 'RGBA'; - break; - } - switch (vfmt[i].type) { - case gfx.ATTR_TYPE_INT8: - gfxFormat += '8I'; - break; - case gfx.ATTR_TYPE_UINT8: - gfxFormat += '8UI'; - break; - case gfx.ATTR_TYPE_INT16: - gfxFormat += '16I'; - break; - case gfx.ATTR_TYPE_UINT16: - gfxFormat += '16UI'; - break; - case gfx.ATTR_TYPE_INT32: - gfxFormat += '32I'; - break; - case gfx.ATTR_TYPE_UINT32: - gfxFormat += '32UI'; - break; - case gfx.ATTR_TYPE_FLOAT32: - gfxFormat += '32F'; - break; - } - gfxAttr.format = GFXFormat[gfxFormat]; - gfxAttr.normalize = vfmt[i].normalize; - attributes.push(gfxAttr); - } - return cc.director.root.device.createInputAssembler({ - attributes, + attributes: vfmt, vertexBuffers: [vb], indexBuffer: ib, }); diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index 75838edfc7..2e508061b5 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -41,8 +41,6 @@ import { RenderScene } from '../renderer/scene/render-scene'; @ccclass("cc.Scene") export default class Scene extends Node { - _renderScenes = new Array(); - constructor(name) { super(name); @@ -56,7 +54,7 @@ export default class Scene extends Node { // cache all depend assets for auto release this.dependAssets = null; - this._renderScenes.push(new RenderScene()); + this._renderScene = cc.director.root.createScene({}); } /** @@ -72,6 +70,7 @@ export default class Scene extends Node { destroy () { super.destroy(); + cc.director.root.destroyScene(this._renderScene); this._activeInHierarchy = false; } From 56cc674fdf5c897edc7429a0dd67e19b1c76e2c6 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 10 Jan 2019 14:49:21 +0800 Subject: [PATCH 082/267] camera utils --- cocos/renderer/scene/camera.ts | 122 +++++++++++++++++++++++++++++++-- cocos/scene-graph/node.js | 70 ++++--------------- 2 files changed, 128 insertions(+), 64 deletions(-) diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 1b2e704dec..d78252b389 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,5 +1,5 @@ -import { frustum } from '../../3d/geom-utils/frustum'; -import { mat4, quat, vec3 } from '../../core/vmath'; +import { frustum, ray } from '../../3d/geom-utils'; +import { lerp, mat4, quat, vec3 } from '../../core/vmath'; import Node from '../../scene-graph/node'; import { RenderScene } from './render-scene'; @@ -14,12 +14,24 @@ export enum CameraProjection { ORTHO, } +const q_a = cc.quat(); +const v_a = cc.v3(); +const v_b = cc.v3(); + +export interface INormalizedViewPort { + x: number; + y: number; + w: number; + h: number; +} + export class Camera { private _scene: RenderScene; private _name: string; private _node: Node; private _proj: CameraProjection; + private _viewport: INormalizedViewPort; private _width: number; private _height: number; private _aspect: number; @@ -40,6 +52,7 @@ export class Camera { this._name = name; this._node = scene.createNode({ name: name + 'Node', isStatic: false }); this._proj = CameraProjection.PERSPECTIVE; + this._viewport = { x: 0, y: 0, w: 1, h: 1 }; const window = scene.root.mainWindow; if (window) { @@ -83,6 +96,17 @@ export class Camera { this._frustum.update(this._matViewProj, this._matViewProjInv); } + public set viewport (v: Partial) { + this._viewport.x = v.x || 0; + this._viewport.y = v.y || 0; + this._viewport.w = v.w || 1; + this._viewport.h = v.h || 1; + } + + public get viewport () { + return this._viewport; + } + public set fov (fov: number) { this._fov = fov; } @@ -154,9 +178,11 @@ export class Camera { public rotate (rot: quat, ns?: NodeSpace) { const space = (ns !== undefined ? ns : NodeSpace.LOCAL); if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.rotate(rot); + this._node.getRotation(q_a); + this._node.setRotation(quat.multiply(q_a, q_a, rot)); } else if (space === NodeSpace.WORLD) { - this._node.rotateWorld(rot); + this._node.getWorldRotation(q_a); + this._node.setWorldRotation(quat.multiply(q_a, rot, q_a)); } } @@ -164,9 +190,11 @@ export class Camera { quat.fromAxisAngle(this._rotation, axis, rad); const space = (ns !== undefined ? ns : NodeSpace.LOCAL); if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.rotate(this._rotation); + this._node.getRotation(q_a); + this._node.setRotation(quat.multiply(q_a, q_a, this._rotation)); } else if (space === NodeSpace.WORLD) { - this._node.rotateWorld(this._rotation); + this._node.getWorldRotation(q_a); + this._node.setWorldRotation(quat.multiply(q_a, this._rotation, q_a)); } } @@ -242,4 +270,86 @@ export class Camera { this._node.setRotation(this._rotation); } + /** + * transform a screen position to a world space ray + */ + public screenPointToRay (x: number, y: number, out: ray): ray { + out = out || ray.create(); + this.update(); + + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.w * this._width; + const ch = this._viewport.h * this._height; + + // far plane intersection + vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); + vec3.transformMat4(v_a, v_a, this._matViewProjInv); + + if (this._proj === CameraProjection.PERSPECTIVE) { + // camera origin + this._node.getWorldPosition(v_b); + } else { + // near plane intersection + vec3.set(v_b, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); + vec3.transformMat4(v_b, v_b, this._matViewProjInv); + } + + return ray.fromPoints(out, v_b, v_a); + } + + /** + * transform a screen position to world space + */ + public screenToWorld (out: vec3, screenPos: vec3): vec3 { + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.w * this._width; + const ch = this._viewport.h * this._height; + + if (this._proj === CameraProjection.PERSPECTIVE) { + // calculate screen pos in far clip plane + vec3.set(out, + (screenPos.x - cx) / cw * 2 - 1, + (screenPos.y - cy) / ch * 2 - 1, + 1.0, + ); + + // transform to world + vec3.transformMat4(out, out, this._matViewProjInv); + + // lerp to depth z + this._node.getWorldPosition(v_a); + + vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z)); + } else { + vec3.set(out, + (screenPos.x - cx) / cw * 2 - 1, + (screenPos.y - cy) / ch * 2 - 1, + screenPos.z * 2 - 1, + ); + + // transform to world + vec3.transformMat4(out, out, this.matViewProjInv); + } + + return out; + } + + /** + * transform a world space position to screen space + */ + public worldToScreen (out: vec3, worldPos: vec3): vec3 { + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.w * this._width; + const ch = this._viewport.h * this._height; + + vec3.transformMat4(out, worldPos, this.matViewProjInv); + out.x = cx + (out.x + 1) * 0.5 * cw; + out.y = cy + (out.y + 1) * 0.5 * ch; + out.z = out.z * 0.5 + 0.5; + + return out; + } } diff --git a/cocos/scene-graph/node.js b/cocos/scene-graph/node.js index 429af2c35b..72461062ad 100644 --- a/cocos/scene-graph/node.js +++ b/cocos/scene-graph/node.js @@ -137,15 +137,15 @@ class Node extends BaseNode { invalidateChildren() { if (this._dirty && this._hasChanged) return; this._dirty = this._hasChanged = true; - - let len = this._children.length; - for (let i = 0; i < len; ++i) { - this._children[i].invalidateChildren(); + for (const child of this._children) { + child.invalidateChildren(); } } /** * update the world transform information if outdated + * here we assume all nodes are children of a scene node, + * which is always not dirty, has an identity transform and no parent. */ updateWorldTransform() { if (!this._dirty) return; @@ -154,7 +154,10 @@ class Node extends BaseNode { // top level node array_a[i++] = cur; cur = cur._parent; - if (!cur) break; + if (!cur || !cur._parent) { + cur = null; + break; + } } while (i) { child = array_a[--i]; @@ -194,6 +197,7 @@ class Node extends BaseNode { } else if (arguments.length === 3) { vec3.set(this._lpos, val, y, z); } + vec3.copy(this._pos, this._lpos); this.invalidateChildren(); this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); @@ -212,59 +216,6 @@ class Node extends BaseNode { } } - /** - * rotate in local space - * - * @param {quat|number} val the new local rotation, or the x component of it - * @param {number} [y] the y component of the new local rotation - * @param {number} [z] the z component of the new local rotation - * @param {number} [w] the w component of the new local rotation - */ - rotate(val, y, z, w) { - - if (arguments.length === 1) { - quat.normalize(q_a, val); - } else if (arguments.length === 4) { - quat.set(q_a, val, y, z, w); - quat.normalize(q_a, q_a); - } - - quat.multiply(this._lrot, this._lrot, q_a); - - this._eulerDirty = true; - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * rotate in world space - * - * @param {quat|number} val the new local rotation, or the x component of it - * @param {number} [y] the y component of the new local rotation - * @param {number} [z] the z component of the new local rotation - * @param {number} [w] the w component of the new local rotation - */ - rotateWorld(val, y, z, w) { - - if (arguments.length === 1) { - quat.normalize(q_a, val); - } else if (arguments.length === 4) { - quat.set(q_a, val, y, z, w); - quat.normalize(q_a, q_a); - } - - getWorldRotation(q_b); - quat.invert(q_b); - quat.multiply(q_a, q_a, q_b); - quat.multiply(this._lrot, this._lrot, q_a); - - this._eulerDirty = true; - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - /** * set local rotation * @param {quat|number} val the new local rotation, or the x component of it @@ -278,6 +229,7 @@ class Node extends BaseNode { } else if (arguments.length === 4) { quat.set(this._lrot, val, y, z, w); } + quat.copy(this._rot, this._lrot); this._eulerDirty = true; this.invalidateChildren(); @@ -294,6 +246,7 @@ class Node extends BaseNode { vec3.set(this._euler, x, y, z); this._eulerDirty = false; quat.fromEuler(this._lrot, x, y, z); + quat.copy(this._rot, this._lrot); this.invalidateChildren(); this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); @@ -324,6 +277,7 @@ class Node extends BaseNode { } else if (arguments.length === 3) { vec3.set(this._lscale, val, y, z); } + vec3.copy(this._scale, this._lscale); this.invalidateChildren(); this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); From 1dca42f7fb5c79c3533aece45b58493248e5b1d3 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 14:52:54 +0800 Subject: [PATCH 083/267] remove null return-value from GFXDevice.createXXX interfaces, add GFXStatus to GFXObject --- cocos/core/root.ts | 146 ++++++++++---------- cocos/gfx/binding-layout.ts | 5 +- cocos/gfx/buffer.ts | 5 +- cocos/gfx/command-allocator.ts | 4 +- cocos/gfx/command-buffer.ts | 5 +- cocos/gfx/define.ts | 43 ++++++ cocos/gfx/device.ts | 30 ++--- cocos/gfx/framebuffer.ts | 4 +- cocos/gfx/input-assembler.ts | 5 +- cocos/gfx/pipeline-layout.ts | 5 +- cocos/gfx/pipeline-state.ts | 5 +- cocos/gfx/queue.ts | 5 +- cocos/gfx/render-pass.ts | 5 +- cocos/gfx/sampler.ts | 5 +- cocos/gfx/shader.ts | 5 +- cocos/gfx/texture-view.ts | 5 +- cocos/gfx/texture.ts | 5 +- cocos/gfx/webgl/webgl-binding-layout.ts | 4 + cocos/gfx/webgl/webgl-buffer.ts | 4 +- cocos/gfx/webgl/webgl-command-allocator.ts | 4 +- cocos/gfx/webgl/webgl-command-buffer.ts | 4 +- cocos/gfx/webgl/webgl-device.ts | 150 +++++++-------------- cocos/gfx/webgl/webgl-framebuffer.ts | 3 + cocos/gfx/webgl/webgl-input-assembler.ts | 3 + cocos/gfx/webgl/webgl-pipeline-layout.ts | 3 + cocos/gfx/webgl/webgl-pipeline-state.ts | 3 + cocos/gfx/webgl/webgl-queue.ts | 4 +- cocos/gfx/webgl/webgl-render-pass.ts | 3 + cocos/gfx/webgl/webgl-sampler.ts | 3 + cocos/gfx/webgl/webgl-shader.ts | 3 + cocos/gfx/webgl/webgl-texture-view.ts | 3 + cocos/gfx/webgl/webgl-texture.ts | 5 +- cocos/gfx/webgl/webgl-window.ts | 5 +- cocos/gfx/window.ts | 17 +-- cocos/pipeline/forward/forward-flow.ts | 24 ++-- cocos/pipeline/forward/forward-pipeline.ts | 11 +- cocos/pipeline/forward/forward-stage.ts | 34 +++-- cocos/pipeline/forward/test-model-stage.ts | 3 +- cocos/pipeline/render-view.ts | 139 ++++++++++--------- cocos/renderer/scene/model.ts | 71 +++++----- cocos/renderer/scene/render-scene.ts | 149 ++++++++++---------- cocos/scene-graph/scene.js | 3 +- 42 files changed, 503 insertions(+), 439 deletions(-) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index c42b2019da..4bf75dd063 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,24 +1,65 @@ -import { GFXWindow, IGFXWindowInfo } from "../gfx/window"; -import { GFXDevice } from "../gfx/device"; -import { RenderView, RenderViewInfo } from "../pipeline/render-view"; -import { RenderPipeline } from "../pipeline/render-pipeline"; -import { ForwardPipeline } from "../pipeline/forward/forward-pipeline"; -import { RenderScene, RenderSceneInfo } from "../renderer/scene/render-scene"; +import { GFXDevice } from '../gfx/device'; +import { GFXWindow, IGFXWindowInfo } from '../gfx/window'; +import { ForwardPipeline } from '../pipeline/forward/forward-pipeline'; +import { RenderPipeline } from '../pipeline/render-pipeline'; +import { IRenderViewInfo, RenderView } from '../pipeline/render-view'; +import { IRenderSceneInfo, RenderScene } from '../renderer/scene/render-scene'; -export interface RootInfo { -}; +export let _createSceneFun; +export let _createViewFun; -export interface SceneInfo { +export interface IRootInfo { +} + +export interface ISceneInfo { name: string; -}; +} export class Root { - constructor(device: GFXDevice) { - this._device = device; + public get device (): GFXDevice { + return this._device; } - public initialize(info: RootInfo): boolean { + public get mainWindow (): GFXWindow | null { + return this._mainWindow; + } + + public get pipeline (): RenderPipeline | null { + return this._pipeline; + } + + public get scenes (): RenderScene[] { + return this._scenes; + } + + public get views (): RenderView[] { + return this._views; + } + + public get frameTime (): number { + return this._frameTime; + } + + public _createSceneFun; + public _createViewFun; + + private _device: GFXDevice; + private _windows: GFXWindow[] = []; + private _mainWindow: GFXWindow | null = null; + private _pipeline: RenderPipeline | null = null; + private _scenes: RenderScene[] = []; + private _views: RenderView[] = []; + private _frameTime: number = 0; + + constructor (device: GFXDevice) { + this._device = device; + + RenderScene.registerCreateFunc(this); + RenderView.registerCreateFunc(this); + } + + public initialize (info: IRootInfo): boolean { if (!this._device.mainWindow) { return false; @@ -26,7 +67,7 @@ export class Root { this._mainWindow = this._device.mainWindow; - let pipeline = new ForwardPipeline(this); + const pipeline = new ForwardPipeline(this); if (!pipeline.initialize()) { return false; } @@ -36,7 +77,7 @@ export class Root { return true; } - public destroy() { + public destroy () { this.destroyViews(); this.destroyScenes(); @@ -46,23 +87,22 @@ export class Root { } } - public frameMove(deltaTime: number) { + public frameMove (deltaTime: number) { this._frameTime = deltaTime; - for (let i = 0; i < this._views.length; ++i) { - let view = this._views[i]; + for (const view of this._views) { if (view.isEnable() && view.isAttached) { - (this._pipeline).render(view); + ( this._pipeline as RenderPipeline).render(view); } } - (this._device).present(); + ( this._device as GFXDevice).present(); } - public createWindow(info: IGFXWindowInfo): GFXWindow | null { + public createWindow (info: IGFXWindowInfo): GFXWindow | null { if (this._device) { - let window = this._device.createWindow(info); + const window = this._device.createWindow(info); if (window) { this._windows.push(window); return window; @@ -72,7 +112,7 @@ export class Root { return null; } - public destroyWindow(window: GFXWindow) { + public destroyWindow (window: GFXWindow) { for (let i = 0; i < this._windows.length; ++i) { if (this._windows[i] === window) { window.destroy(); @@ -82,15 +122,15 @@ export class Root { } } - public destroyWindows() { - for (let i = 0; i < this._windows.length; ++i) { - this._windows[i].destroy(); + public destroyWindows () { + for (const window of this._windows) { + window.destroy(); } this._windows = []; } - public createScene(info: RenderSceneInfo): RenderScene | null { - let scene = new RenderScene(this); + public createScene (info: IRenderSceneInfo): RenderScene | null { + const scene = this._createSceneFun(this); if (scene.initialize(info)) { this._scenes.push(scene); return scene; @@ -99,7 +139,7 @@ export class Root { } } - public destroyScene(scene: RenderScene) { + public destroyScene (scene: RenderScene) { for (let i = 0; i < this._scenes.length; ++i) { if (this._scenes[i] === scene) { scene.destroy(); @@ -109,15 +149,15 @@ export class Root { } } - public destroyScenes() { - for (let i = 0; i < this._scenes.length; ++i) { - this._scenes[i].destroy(); + public destroyScenes () { + for (const scene of this._scenes) { + scene.destroy(); } this._scenes = []; } - public createView(info: RenderViewInfo): RenderView | null { - let view = new RenderView; + public createView (info: IRenderViewInfo): RenderView | null { + const view = this._createViewFun(this); if (view.initialize(info)) { this._views.push(view); this._views.sort((a: RenderView, b: RenderView) => { @@ -129,7 +169,7 @@ export class Root { } } - public destroyView(view: RenderView) { + public destroyView (view: RenderView) { for (let i = 0; i < this._views.length; ++i) { if (this._views[i] === view) { this._views.splice(i); @@ -138,42 +178,10 @@ export class Root { } } - public destroyViews() { + public destroyViews () { for (let i = 0; i < this._views.length; ++i) { this._views[i].destroy(); } this._views = []; } - - public get device(): GFXDevice { - return this._device; - } - - public get mainWindow(): GFXWindow | null { - return this._mainWindow; - } - - public get pipeline(): RenderPipeline | null { - return this._pipeline; - } - - public get scenes(): RenderScene[] { - return this._scenes; - } - - public get views(): RenderView[] { - return this._views; - } - - public get frameTime(): number { - return this._frameTime; - } - - private _device: GFXDevice; - private _windows: GFXWindow[] = []; - private _mainWindow: GFXWindow | null = null; - private _pipeline: RenderPipeline | null = null; - private _scenes: RenderScene[] = []; - private _views: RenderView[] = []; - private _frameTime: number = 0; -}; +} diff --git a/cocos/gfx/binding-layout.ts b/cocos/gfx/binding-layout.ts index cb591daa98..d922b4fe2a 100644 --- a/cocos/gfx/binding-layout.ts +++ b/cocos/gfx/binding-layout.ts @@ -1,5 +1,5 @@ import { GFXBuffer } from './buffer'; -import { GFXBindingType } from './define'; +import { GFXBindingType, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; import { GFXSampler } from './sampler'; import { GFXTextureView } from './texture-view'; @@ -23,13 +23,14 @@ export class GFXBindingUnit { public sampler: GFXSampler | null = null; } -export abstract class GFXBindingLayout { +export abstract class GFXBindingLayout extends GFXObject { protected _device: GFXDevice; protected _bindingUnits: GFXBindingUnit[] = []; protected _isDirty = false; constructor (device: GFXDevice) { + super(GFXObjectType.BINDING_LAYOUT); this._device = device; } diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 58a9cb0518..957b756227 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -1,4 +1,4 @@ -import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit } from './define'; +import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; export interface IGFXBufferInfo { @@ -8,7 +8,7 @@ export interface IGFXBufferInfo { stride?: number; } -export abstract class GFXBuffer { +export abstract class GFXBuffer extends GFXObject { public get usage (): GFXBufferUsage { return this._usage; @@ -39,6 +39,7 @@ export abstract class GFXBuffer { protected _bufferView: Uint8Array | null = null; constructor (device: GFXDevice) { + super(GFXObjectType.BUFFER); this._device = device; } diff --git a/cocos/gfx/command-allocator.ts b/cocos/gfx/command-allocator.ts index 2fd580eed8..56a96506d3 100644 --- a/cocos/gfx/command-allocator.ts +++ b/cocos/gfx/command-allocator.ts @@ -1,13 +1,15 @@ +import { GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; export interface IGFXCommandAllocatorInfo { } -export abstract class GFXCommandAllocator { +export abstract class GFXCommandAllocator extends GFXObject { protected _device: GFXDevice; constructor (device: GFXDevice) { + super(GFXObjectType.COMMAND_ALLOCATOR); this._device = device; } diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index 142474ccbe..7f7f25276f 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -1,7 +1,7 @@ import { GFXBindingLayout } from './binding-layout'; import { GFXBuffer } from './buffer'; import { GFXCommandAllocator } from './command-allocator'; -import { GFXBufferTextureCopy, GFXCommandBufferType, GFXTextureLayout, IGFXColor, IGFXRect } from './define'; +import { GFXBufferTextureCopy, GFXCommandBufferType, GFXObject, GFXObjectType, GFXTextureLayout, IGFXColor, IGFXRect } from './define'; import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; import { GFXInputAssembler } from './input-assembler'; @@ -13,7 +13,7 @@ export interface IGFXCommandBufferInfo { type: GFXCommandBufferType; } -export abstract class GFXCommandBuffer { +export abstract class GFXCommandBuffer extends GFXObject { public get type (): number { return this._type; @@ -24,6 +24,7 @@ export abstract class GFXCommandBuffer { protected _type: GFXCommandBufferType = GFXCommandBufferType.PRIMARY; constructor (device: GFXDevice) { + super(GFXObjectType.COMMAND_BUFFER); this._device = device; } diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index edb48d1f32..d1b0317d0e 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -22,6 +22,49 @@ export const GFX_MAX_VERTEX_ATTRIBUTES: number = 16; export const GFX_MAX_TEXTURE_UNITS: number = 16; export const GFX_MAX_ATTACHMENTS: number = 4; +export enum GFXObjectType { + UNKNOWN, + BUFFER, + TEXTURE, + TEXTURE_VIEW, + RENDER_PASS, + FRAMEBUFFER, + SAMPLER, + SHADER, + PIPELINE_LAYOUT, + PIPELINE_STATE, + BINDING_LAYOUT, + INPUT_ASSEMBLER, + COMMAND_ALLOCATOR, + COMMAND_BUFFER, + QUEUE, + WINDOW, +} + +export enum GFXStatus { + UNREADY, + FAILED, + SUCCESS, +} + +export class GFXObject { + + public get gfxType (): GFXObjectType { + return this._gfxType; + } + + public get status (): GFXStatus { + return this._status; + } + + protected _gfxType = GFXObjectType.UNKNOWN; + protected _status = GFXStatus.UNREADY; + + constructor (gfxType: GFXObjectType) { + this._gfxType = gfxType; + } +} + export enum GFXType { UNKNOWN, BOOL, diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index 8d118b7d59..5b5de3bb6c 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -122,21 +122,21 @@ export abstract class GFXDevice { public abstract initialize (info: IGFXDeviceInfo): boolean; public abstract destroy (): void; - public abstract createBuffer (info: IGFXBufferInfo): GFXBuffer | null; - public abstract createTexture (info: IGFXTextureInfo): GFXTexture | null; - public abstract createTextureView (info: IGFXTextureViewInfo): GFXTextureView | null; - public abstract createSampler (info: IGFXSamplerInfo): GFXSampler | null; - public abstract createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout | null; - public abstract createShader (info: IGFXShaderInfo): GFXShader | null; - public abstract createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler | null; - public abstract createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass | null; - public abstract createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer | null; - public abstract createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout | null; - public abstract createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState | null; - public abstract createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator | null; - public abstract createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer | null; - public abstract createQueue (info: IGFXQueueInfo): GFXQueue | null; - public abstract createWindow (info: IGFXWindowInfo): GFXWindow | null; + public abstract createBuffer (info: IGFXBufferInfo): GFXBuffer; + public abstract createTexture (info: IGFXTextureInfo): GFXTexture; + public abstract createTextureView (info: IGFXTextureViewInfo): GFXTextureView; + public abstract createSampler (info: IGFXSamplerInfo): GFXSampler; + public abstract createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout; + public abstract createShader (info: IGFXShaderInfo): GFXShader; + public abstract createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler; + public abstract createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass; + public abstract createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer; + public abstract createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout; + public abstract createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState; + public abstract createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator; + public abstract createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer; + public abstract createQueue (info: IGFXQueueInfo): GFXQueue; + public abstract createWindow (info: IGFXWindowInfo): GFXWindow; public abstract present (); public abstract copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]); diff --git a/cocos/gfx/framebuffer.ts b/cocos/gfx/framebuffer.ts index e20a240b7a..f9a3729389 100644 --- a/cocos/gfx/framebuffer.ts +++ b/cocos/gfx/framebuffer.ts @@ -1,3 +1,4 @@ +import { GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; import { GFXRenderPass } from './render-pass'; import { GFXTextureView } from './texture-view'; @@ -9,7 +10,7 @@ export interface IGFXFramebufferInfo { isOffscreen?: boolean; } -export abstract class GFXFramebuffer { +export abstract class GFXFramebuffer extends GFXObject { public get renderPass (): GFXRenderPass | null { return this._renderPass; @@ -34,6 +35,7 @@ export abstract class GFXFramebuffer { protected _isOffscreen: boolean = true; constructor (device: GFXDevice) { + super(GFXObjectType.FRAMEBUFFER); this._device = device; } diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index b17caeb8c1..1baca3e5e0 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,5 +1,5 @@ import { GFXBuffer } from './buffer'; -import { GFXFormat } from './define'; +import { GFXFormat, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; export interface IGFXInputAttribute { @@ -18,7 +18,7 @@ export interface IGFXInputAssemblerInfo { isIndirect?: boolean; } -export abstract class GFXInputAssembler { +export abstract class GFXInputAssembler extends GFXObject { public get vertexBuffers (): GFXBuffer[] { return this._vertexBuffers; @@ -102,6 +102,7 @@ export abstract class GFXInputAssembler { protected _isIndirect: boolean = false; constructor (device: GFXDevice) { + super(GFXObjectType.INPUT_ASSEMBLER); this._device = device; } diff --git a/cocos/gfx/pipeline-layout.ts b/cocos/gfx/pipeline-layout.ts index 7137bced05..b1a26fefc1 100644 --- a/cocos/gfx/pipeline-layout.ts +++ b/cocos/gfx/pipeline-layout.ts @@ -1,5 +1,5 @@ import { GFXBindingLayout } from './binding-layout'; -import { GFXShaderType } from './define'; +import { GFXObject, GFXObjectType, GFXShaderType } from './define'; import { GFXDevice } from './device'; export interface IGFXPushConstantRange { @@ -13,13 +13,14 @@ export interface IGFXPipelineLayoutInfo { layouts: GFXBindingLayout[]; } -export abstract class GFXPipelineLayout { +export abstract class GFXPipelineLayout extends GFXObject { protected _device: GFXDevice; protected _pushConstantsRanges: IGFXPushConstantRange[] = []; protected _layouts: GFXBindingLayout[] = []; constructor (device: GFXDevice) { + super(GFXObjectType.PIPELINE_LAYOUT); this._device = device; } diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index c2d22276ce..b854d4b7e7 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -1,4 +1,4 @@ -import { GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXComparisonFunc, GFXCullMode, GFXPolygonMode, GFXPrimitiveMode, GFXShadeModel, GFXStencilOp } from './define'; +import { GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXComparisonFunc, GFXCullMode, GFXObject, GFXObjectType, GFXPolygonMode, GFXPrimitiveMode, GFXShadeModel, GFXStencilOp } from './define'; import { GFXDevice } from './device'; import { IGFXInputAttribute } from './input-assembler'; import { GFXPipelineLayout } from './pipeline-layout'; @@ -119,7 +119,7 @@ export interface IGFXPipelineStateInfo { renderPass: GFXRenderPass; } -export abstract class GFXPipelineState { +export abstract class GFXPipelineState extends GFXObject { public get shader (): GFXShader { return this._shader as GFXShader; @@ -160,6 +160,7 @@ export abstract class GFXPipelineState { protected _renderPass: GFXRenderPass | null = null; constructor (device: GFXDevice) { + super(GFXObjectType.PIPELINE_STATE); this._device = device; } diff --git a/cocos/gfx/queue.ts b/cocos/gfx/queue.ts index 0c11f60b2a..a13c31a3cd 100644 --- a/cocos/gfx/queue.ts +++ b/cocos/gfx/queue.ts @@ -1,12 +1,12 @@ import { GFXCommandBuffer } from './command-buffer'; -import { GFXQueueType } from './define'; +import { GFXObject, GFXObjectType, GFXQueueType } from './define'; import { GFXDevice } from './device'; export interface IGFXQueueInfo { type: GFXQueueType; } -export abstract class GFXQueue { +export abstract class GFXQueue extends GFXObject { public get type (): number { return this._type; @@ -16,6 +16,7 @@ export abstract class GFXQueue { protected _type: GFXQueueType = GFXQueueType.GRAPHICS; constructor (device: GFXDevice) { + super(GFXObjectType.QUEUE); this._device = device; } diff --git a/cocos/gfx/render-pass.ts b/cocos/gfx/render-pass.ts index 23250bb97e..548dc7e567 100644 --- a/cocos/gfx/render-pass.ts +++ b/cocos/gfx/render-pass.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXLoadOp, GFXPipelineBindPoint, GFXStoreOp, GFXTextureLayout } from './define'; +import { GFXFormat, GFXLoadOp, GFXObject, GFXObjectType, GFXPipelineBindPoint, GFXStoreOp, GFXTextureLayout } from './define'; import { GFXDevice } from './device'; export class GFXColorAttachment { @@ -36,13 +36,14 @@ export interface IGFXRenderPassInfo { // subPasses? : GFXSubPassInfo[]; } -export abstract class GFXRenderPass { +export abstract class GFXRenderPass extends GFXObject { protected _device: GFXDevice; protected _colorInfos: GFXColorAttachment[] = []; protected _depthStencilInfo: GFXDepthStencilAttachment | null = null; constructor (device: GFXDevice) { + super(GFXObjectType.RENDER_PASS); this._device = device; } diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index c1647abdf9..6d0afc5e89 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -1,4 +1,4 @@ -import { GFXAddress, GFXComparisonFunc, GFXFilter } from './define'; +import { GFXAddress, GFXComparisonFunc, GFXFilter, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; export interface IGFXSamplerInfo { @@ -48,7 +48,7 @@ export class GFXSamplerState { } } -export abstract class GFXSampler { +export abstract class GFXSampler extends GFXObject { public get state (): GFXSamplerState { return this._state; @@ -58,6 +58,7 @@ export abstract class GFXSampler { protected _state: GFXSamplerState = new GFXSamplerState(); constructor (device: GFXDevice) { + super(GFXObjectType.SAMPLER); this._device = device; } diff --git a/cocos/gfx/shader.ts b/cocos/gfx/shader.ts index 02e21132a0..4059d228b6 100644 --- a/cocos/gfx/shader.ts +++ b/cocos/gfx/shader.ts @@ -1,4 +1,4 @@ -import { GFXShaderType, GFXType } from './define'; +import { GFXObject, GFXObjectType, GFXShaderType, GFXType } from './define'; import { GFXDevice } from './device'; export interface IGFXShaderMacro { @@ -41,7 +41,7 @@ export interface IGFXShaderInfo { samplers?: GFXUniformSampler[]; } -export abstract class GFXShader { +export abstract class GFXShader extends GFXObject { public get id (): number { return this._id; @@ -56,6 +56,7 @@ export abstract class GFXShader { protected _samplers: GFXUniformSampler[] = []; constructor (device: GFXDevice) { + super(GFXObjectType.SHADER); this._device = device; this._id = device.genShaderId(); } diff --git a/cocos/gfx/texture-view.ts b/cocos/gfx/texture-view.ts index f6e026d82c..6b19137200 100644 --- a/cocos/gfx/texture-view.ts +++ b/cocos/gfx/texture-view.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXTextureViewType } from './define'; +import { GFXFormat, GFXObject, GFXObjectType, GFXTextureViewType } from './define'; import { GFXDevice } from './device'; import { GFXTexture } from './texture'; @@ -12,7 +12,7 @@ export interface IGFXTextureViewInfo { layerCount?: number; } -export abstract class GFXTextureView { +export abstract class GFXTextureView extends GFXObject { public get texture (): GFXTexture { return this._texture as GFXTexture; @@ -52,6 +52,7 @@ export abstract class GFXTextureView { protected _layerCount: number = 1; constructor (device: GFXDevice) { + super(GFXObjectType.TEXTURE_VIEW); this._device = device; } diff --git a/cocos/gfx/texture.ts b/cocos/gfx/texture.ts index c3969b65dc..31954487b7 100644 --- a/cocos/gfx/texture.ts +++ b/cocos/gfx/texture.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXTextureFlagBit, GFXTextureFlags, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit } from './define'; +import { GFXFormat, GFXObject, GFXObjectType, GFXTextureFlagBit, GFXTextureFlags, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit } from './define'; import { GFXDevice } from './device'; export interface IGFXTextureInfo { @@ -13,7 +13,7 @@ export interface IGFXTextureInfo { flags?: GFXTextureFlags; } -export abstract class GFXTexture { +export abstract class GFXTexture extends GFXObject { public get type (): GFXTextureType { return this._type; @@ -73,6 +73,7 @@ export abstract class GFXTexture { protected _buffer: ArrayBuffer | null = null; constructor (device: GFXDevice) { + super(GFXObjectType.TEXTURE); this._device = device; } diff --git a/cocos/gfx/webgl/webgl-binding-layout.ts b/cocos/gfx/webgl/webgl-binding-layout.ts index 2a661ef7f4..259cd84db3 100644 --- a/cocos/gfx/webgl/webgl-binding-layout.ts +++ b/cocos/gfx/webgl/webgl-binding-layout.ts @@ -1,4 +1,5 @@ import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBindingLayout } from './webgl-gpu-objects'; @@ -35,6 +36,7 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { } this._gpuBindingLayout = this.webGLDevice.emitCmdCreateGPUBindingLayout(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -44,6 +46,8 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout { this.webGLDevice.emitCmdDestroyGPUBindingLayout(this._gpuBindingLayout); this._gpuBindingLayout = null; } + + this._status = GFXStatus.UNREADY; } public update () { diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 14d8d4c7bb..031c049fa7 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,5 +1,5 @@ import { GFXBuffer, IGFXBufferInfo } from '../buffer'; -import { GFXMemoryUsageBit } from '../define'; +import { GFXMemoryUsageBit, GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; @@ -38,6 +38,7 @@ export class WebGLGFXBuffer extends GFXBuffer { // this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; this._gpuBuffer = this.webGLDevice.emitCmdCreateGPUBuffer(info, this._buffer); + this._status = GFXStatus.SUCCESS; return true; } @@ -50,6 +51,7 @@ export class WebGLGFXBuffer extends GFXBuffer { this._buffer = null; this._bufferView = null; + this._status = GFXStatus.UNREADY; } public update (buffer: ArrayBuffer, offset?: number) { diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index f5ea380c72..d103695b51 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -1,4 +1,5 @@ import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { WebGLCmdBeginRenderPass, WebGLCmdBindBindingLayout, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdCopyBufferToTexture, WebGLCmdDraw, WebGLCmdUpdateBuffer } from './webgl-commands'; @@ -70,10 +71,11 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { public initialize (info: IGFXCommandAllocatorInfo): boolean { + this._status = GFXStatus.SUCCESS; return true; } public destroy () { - + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 8aa6a42445..7c3b2363b7 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,7 +1,7 @@ import { GFXBindingLayout } from '../binding-layout'; import { GFXBuffer } from '../buffer'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; -import { GFXBufferTextureCopy, GFXTextureLayout, IGFXColor, IGFXRect, IGFXViewport } from '../define'; +import { GFXBufferTextureCopy, GFXStatus, GFXTextureLayout, IGFXColor, IGFXRect } from '../define'; import { GFXDevice } from '../device'; import { GFXFramebuffer } from '../framebuffer'; import { GFXInputAssembler } from '../input-assembler'; @@ -33,6 +33,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { this._allocator = info.allocator; this._type = info.type; + this._status = GFXStatus.SUCCESS; return true; } @@ -41,6 +42,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { if (this._allocator) { this.cmdPackage.clearCmds( this._allocator as WebGLGFXCommandAllocator); } + this._status = GFXStatus.UNREADY; } public begin () { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index c450614744..d636823ef8 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -354,154 +354,94 @@ export class WebGLGFXDevice extends GFXDevice { this._webGLRC = null; } - public createBuffer (info: IGFXBufferInfo): GFXBuffer | null { + public createBuffer (info: IGFXBufferInfo): GFXBuffer { const buffer = new WebGLGFXBuffer(this); - if (buffer.initialize(info)) { - return buffer; - } else { - buffer.destroy(); - return null; - } + buffer.initialize(info); + return buffer; } - public createTexture (info: IGFXTextureInfo): GFXTexture | null { + public createTexture (info: IGFXTextureInfo): GFXTexture { const texture = new WebGLGFXTexture(this); - if (texture.initialize(info)) { - return texture; - } else { - texture.destroy(); - return null; - } + texture.initialize(info); + return texture; } - public createTextureView (info: IGFXTextureViewInfo): GFXTextureView | null { + public createTextureView (info: IGFXTextureViewInfo): GFXTextureView { const texView = new WebGLGFXTextureView(this); - if (texView.initialize(info)) { - return texView; - } else { - texView.destroy(); - return null; - } + texView.initialize(info); + return texView; } - public createSampler (info: IGFXSamplerInfo): GFXSampler | null { + public createSampler (info: IGFXSamplerInfo): GFXSampler { const sampler = new WebGLGFXSampler(this); - if (sampler.initialize(info)) { - return sampler; - } else { - sampler.destroy(); - return null; - } + sampler.initialize(info); + return sampler; } - public createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout | null { + public createBindingLayout (info: IGFXBindingLayoutInfo): GFXBindingLayout { const bindingLayout = new WebGLGFXBindingLayout(this); - if (bindingLayout.initialize(info)) { - return bindingLayout; - } else { - bindingLayout.destroy(); - return null; - } + bindingLayout.initialize(info); + return bindingLayout; } - public createShader (info: IGFXShaderInfo): GFXShader | null { + public createShader (info: IGFXShaderInfo): GFXShader { const shader = new WebGLGFXShader(this); - if (shader.initialize(info)) { - return shader; - } else { - shader.destroy(); - return null; - } + shader.initialize(info); + return shader; } - public createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler | null { + public createInputAssembler (info: IGFXInputAssemblerInfo): GFXInputAssembler { const inputAssembler = new WebGLGFXInputAssembler(this); - if (inputAssembler.initialize(info)) { - return inputAssembler; - } else { - inputAssembler.destroy(); - return null; - } + inputAssembler.initialize(info); + return inputAssembler; } - public createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass | null { + public createRenderPass (info: IGFXRenderPassInfo): GFXRenderPass { const renderPass = new WebGLGFXRenderPass(this); - if (renderPass.initialize(info)) { - return renderPass; - } else { - renderPass.destroy(); - return null; - } + renderPass.initialize(info); + return renderPass; } - public createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer | null { + public createFramebuffer (info: IGFXFramebufferInfo): GFXFramebuffer { const framebuffer = new WebGLGFXFramebuffer(this); - if (framebuffer.initialize(info)) { - return framebuffer; - } else { - framebuffer.destroy(); - return null; - } + framebuffer.initialize(info); + return framebuffer; } - public createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout | null { + public createPipelineLayout (info: IGFXPipelineLayoutInfo): GFXPipelineLayout { const pipelineLayout = new WebGLGFXPipelineLayout(this); - if (pipelineLayout.initialize(info)) { - return pipelineLayout; - } else { - pipelineLayout.destroy(); - return null; - } + pipelineLayout.initialize(info); + return pipelineLayout; } - public createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState | null { + public createPipelineState (info: IGFXPipelineStateInfo): GFXPipelineState { const pipelineState = new WebGLGFXPipelineState(this); - if (pipelineState.initialize(info)) { - return pipelineState; - } else { - pipelineState.destroy(); - return null; - } + pipelineState.initialize(info); + return pipelineState; } - public createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator | null { + public createCommandAllocator (info: IGFXCommandAllocatorInfo): GFXCommandAllocator { const cmdAllocator = new WebGLGFXCommandAllocator(this); - if (cmdAllocator.initialize(info)) { - return cmdAllocator; - } else { - cmdAllocator.destroy(); - return null; - } + cmdAllocator.initialize(info); + return cmdAllocator; } - public createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer | null { + public createCommandBuffer (info: IGFXCommandBufferInfo): GFXCommandBuffer { const cmdBuff = new WebGLGFXCommandBuffer(this); - if (cmdBuff.initialize(info)) { - return cmdBuff; - } else { - cmdBuff.destroy(); - return null; - } + cmdBuff.initialize(info); + return cmdBuff; } - public createQueue (info: IGFXQueueInfo): GFXQueue | null { + public createQueue (info: IGFXQueueInfo): GFXQueue { const queue = new WebGLGFXQueue(this); - if (queue.initialize(info)) { - return queue; - } else { - queue.destroy(); - return null; - } + queue.initialize(info); + return queue; } - public createWindow (info: IGFXWindowInfo): GFXWindow | null { + public createWindow (info: IGFXWindowInfo): GFXWindow { const window = new WebGLGFXWindow(this); - if (window.initialize(info)) { - return window; - } else { - window.destroy(); - return null; - } + window.initialize(info); + return window; } public present () { diff --git a/cocos/gfx/webgl/webgl-framebuffer.ts b/cocos/gfx/webgl/webgl-framebuffer.ts index 67d6152b9d..de35f53804 100644 --- a/cocos/gfx/webgl/webgl-framebuffer.ts +++ b/cocos/gfx/webgl/webgl-framebuffer.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; import { WebGLGFXDevice } from './webgl-device'; @@ -31,6 +32,7 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { this._isOffscreen = info.isOffscreen !== undefined ? info.isOffscreen : true; this._gpuFramebuffer = this.webGLDevice.emitCmdCreateGPUFramebuffer(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -41,5 +43,6 @@ export class WebGLGFXFramebuffer extends GFXFramebuffer { this.webGLDevice.emitCmdDestroyGPUFramebuffer(this._gpuFramebuffer); this._gpuFramebuffer = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index 8973d9d33c..6da551bc93 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; import { WebGLGFXDevice } from './webgl-device'; @@ -42,6 +43,7 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { } this._gpuInputAssembler = this.webGLDevice.emitCmdCreateGPUInputAssembler(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -51,5 +53,6 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { this.webGLDevice.emitCmdDestroyGPUInputAssembler(this._gpuInputAssembler); this._gpuInputAssembler = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-pipeline-layout.ts b/cocos/gfx/webgl/webgl-pipeline-layout.ts index c085052818..c4c73fe4d8 100644 --- a/cocos/gfx/webgl/webgl-pipeline-layout.ts +++ b/cocos/gfx/webgl/webgl-pipeline-layout.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../pipeline-layout'; import { WebGLGFXDevice } from './webgl-device'; @@ -26,10 +27,12 @@ export class WebGLGFXPipelineLayout extends GFXPipelineLayout { if (info.pushConstantsRanges !== undefined) { this._pushConstantsRanges = info.pushConstantsRanges; } + this._status = GFXStatus.SUCCESS; return true; } public destroy () { + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-pipeline-state.ts b/cocos/gfx/webgl/webgl-pipeline-state.ts index b9072080c5..d3c3b8afe7 100644 --- a/cocos/gfx/webgl/webgl-pipeline-state.ts +++ b/cocos/gfx/webgl/webgl-pipeline-state.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXPipelineState, IGFXPipelineStateInfo } from '../pipeline-state'; import { WebGLGFXDevice } from './webgl-device'; @@ -31,6 +32,7 @@ export class WebGLGFXPipelineState extends GFXPipelineState { this._renderPass = info.renderPass; this._gpuPipelineState = this.webGLDevice.emitCmdCreateGPUPipelineState(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -40,5 +42,6 @@ export class WebGLGFXPipelineState extends GFXPipelineState { this.webGLDevice.emitCmdDestroyGPUPipelineState(this._gpuPipelineState); this._gpuPipelineState = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-queue.ts b/cocos/gfx/webgl/webgl-queue.ts index f9d2463943..99254b0777 100644 --- a/cocos/gfx/webgl/webgl-queue.ts +++ b/cocos/gfx/webgl/webgl-queue.ts @@ -1,4 +1,5 @@ import { GFXCommandBuffer } from '../command-buffer'; +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXQueue, IGFXQueueInfo } from '../queue'; import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; @@ -16,12 +17,13 @@ export class WebGLGFXQueue extends GFXQueue { public initialize (info: IGFXQueueInfo): boolean { this._type = info.type; + this._status = GFXStatus.SUCCESS; return true; } public destroy () { - + this._status = GFXStatus.UNREADY; } public submit (cmdBuffs: GFXCommandBuffer[], fence?) { diff --git a/cocos/gfx/webgl/webgl-render-pass.ts b/cocos/gfx/webgl/webgl-render-pass.ts index 4fd5224035..b22c87f1b2 100644 --- a/cocos/gfx/webgl/webgl-render-pass.ts +++ b/cocos/gfx/webgl/webgl-render-pass.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXRenderPass, IGFXRenderPassInfo } from '../render-pass'; import { WebGLGFXDevice } from './webgl-device'; @@ -30,6 +31,7 @@ export class WebGLGFXRenderPass extends GFXRenderPass { } this._gpuRenderPass = this.webGLDevice.emitCmdCreateGPURenderPass(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -40,5 +42,6 @@ export class WebGLGFXRenderPass extends GFXRenderPass { this.webGLDevice.emitCmdDestroyGPURenderPass(this._gpuRenderPass); this._gpuRenderPass = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-sampler.ts b/cocos/gfx/webgl/webgl-sampler.ts index 4f6d375535..1ff41e8869 100644 --- a/cocos/gfx/webgl/webgl-sampler.ts +++ b/cocos/gfx/webgl/webgl-sampler.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXSampler, GFXSamplerState, IGFXSamplerInfo } from '../sampler'; import { WebGLGFXDevice } from './webgl-device'; @@ -76,6 +77,7 @@ export class WebGLGFXSampler extends GFXSampler { } this._gpuSampler = this.webGLDevice.emitCmdCreateGPUSampler(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -85,5 +87,6 @@ export class WebGLGFXSampler extends GFXSampler { this.webGLDevice.emitCmdDestroyGPUSampler(this._gpuSampler); this._gpuSampler = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-shader.ts b/cocos/gfx/webgl/webgl-shader.ts index 3aefb658b7..bcdc1e015e 100644 --- a/cocos/gfx/webgl/webgl-shader.ts +++ b/cocos/gfx/webgl/webgl-shader.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXShader, IGFXShaderInfo } from '../shader'; import { WebGLGFXDevice } from './webgl-device'; @@ -33,6 +34,7 @@ export class WebGLGFXShader extends GFXShader { } this._gpuShader = this.webGLDevice.emitCmdCreateGPUShader(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -42,5 +44,6 @@ export class WebGLGFXShader extends GFXShader { this.webGLDevice.emitCmdDestroyGPUShader(this._gpuShader); this._gpuShader = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-texture-view.ts b/cocos/gfx/webgl/webgl-texture-view.ts index 64cc9d3214..632aa95b51 100644 --- a/cocos/gfx/webgl/webgl-texture-view.ts +++ b/cocos/gfx/webgl/webgl-texture-view.ts @@ -1,3 +1,4 @@ +import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXTextureView, IGFXTextureViewInfo } from '../texture-view'; import { WebGLGFXDevice } from './webgl-device'; @@ -43,6 +44,7 @@ export class WebGLGFXTextureView extends GFXTextureView { } this._gpuTextureView = this.webGLDevice.emitCmdCreateGPUTextureView(info); + this._status = GFXStatus.SUCCESS; return true; } @@ -53,5 +55,6 @@ export class WebGLGFXTextureView extends GFXTextureView { this._gpuTextureView = null; } this._texture = null; + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-texture.ts b/cocos/gfx/webgl/webgl-texture.ts index 61f056399b..2e7c33fa2a 100644 --- a/cocos/gfx/webgl/webgl-texture.ts +++ b/cocos/gfx/webgl/webgl-texture.ts @@ -1,4 +1,4 @@ -import { GFXFormatSurfaceSize, GFXTextureFlagBit } from '../define'; +import { GFXFormatSurfaceSize, GFXStatus, GFXTextureFlagBit } from '../define'; import { GFXDevice } from '../device'; import { GFXTexture, IGFXTextureInfo } from '../texture'; import { WebGLGFXDevice } from './webgl-device'; @@ -51,15 +51,16 @@ export class WebGLGFXTexture extends GFXTexture { } this._gpuTexture = this.webGLDevice.emitCmdCreateGPUTexture(info); + this._status = GFXStatus.SUCCESS; return true; } public destroy () { - if (this._gpuTexture) { this.webGLDevice.emitCmdDestroyGPUTexture(this._gpuTexture); this._gpuTexture = null; } + this._status = GFXStatus.UNREADY; } } diff --git a/cocos/gfx/webgl/webgl-window.ts b/cocos/gfx/webgl/webgl-window.ts index e88a379998..b4f39940b9 100644 --- a/cocos/gfx/webgl/webgl-window.ts +++ b/cocos/gfx/webgl/webgl-window.ts @@ -1,4 +1,4 @@ -import { GFXFormat, GFXLoadOp, GFXStoreOp, GFXTextureFlagBit, GFXTextureLayout, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../define'; +import { GFXLoadOp, GFXStatus, GFXStoreOp, GFXTextureLayout } from '../define'; import { GFXDevice } from '../device'; import { GFXWindow, IGFXWindowInfo } from '../window'; import { WebGLGFXDevice } from './webgl-device'; @@ -131,6 +131,7 @@ export class WebGLGFXWindow extends GFXWindow { this.destroy(); return false; } + this._status = GFXStatus.SUCCESS; return true; } @@ -167,6 +168,8 @@ export class WebGLGFXWindow extends GFXWindow { this._renderPass.destroy(); this._renderPass = null; } + + this._status = GFXStatus.UNREADY; } public get webGLDevice (): WebGLGFXDevice { diff --git a/cocos/gfx/window.ts b/cocos/gfx/window.ts index b4d8b2ea60..8e58075adb 100644 --- a/cocos/gfx/window.ts +++ b/cocos/gfx/window.ts @@ -1,4 +1,4 @@ -import { GFXFormat } from './define'; +import { GFXFormat, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; import { GFXRenderPass } from './render-pass'; @@ -13,7 +13,7 @@ export interface IGFXWindowInfo { depthStencilFmt: GFXFormat; } -export abstract class GFXWindow { +export abstract class GFXWindow extends GFXObject { public get width (): number { return this._width; @@ -23,20 +23,20 @@ export abstract class GFXWindow { return this._height; } - public get colorFormat (): GFXFormat | null { + public get colorFormat (): GFXFormat { return this._colorFmt; } - public get detphStencilFormat (): GFXFormat | null { + public get detphStencilFormat (): GFXFormat { return this._depthStencilFmt; } - public get renderPass (): GFXRenderPass | null { - return this._renderPass; + public get renderPass (): GFXRenderPass { + return this._renderPass as GFXRenderPass; } - public get framebuffer (): GFXFramebuffer | null { - return this._framebuffer; + public get framebuffer (): GFXFramebuffer { + return this._framebuffer as GFXFramebuffer; } protected _device: GFXDevice; @@ -55,6 +55,7 @@ export abstract class GFXWindow { protected _framebuffer: GFXFramebuffer | null = null; constructor (device: GFXDevice) { + super(GFXObjectType.WINDOW); this._device = device; } diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 55007b77f9..b4a29558dc 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,5 +1,6 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { RenderPipeline } from '../render-pipeline'; +import { ForwardStage } from './forward-stage'; // import { TestStage } from "./test-stage"; import { TestMaterialStage } from './test-material-stage'; import { TestModelStage } from './test-model-stage'; @@ -28,26 +29,27 @@ export class ForwardFlow extends RenderFlow { return false; } - /* * - this.createStage(ForwardStage, { - name: "ForwardStage", + /* + this.createStage(ForwardStage, { + name: 'ForwardStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ + */ this.createStage(TestModelStage, { name: 'TestModelStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - /* */ - // this.createStage(TestStage, { - // name: 'TestStage', - // priority: ForwardStagePriority.FORWARD, - // framebuffer: mainWindow.framebuffer, - // }); - /* */ + + /* + this.createStage(TestStage, { + name: 'TestStage', + priority: ForwardStagePriority.FORWARD, + framebuffer: mainWindow.framebuffer, + }); + */ return true; } diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index 3470871a70..02a90df558 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -1,9 +1,8 @@ -import { Root } from "../../core/root"; -import { GFXBufferUsageBit, GFXMemoryUsageBit } from "../../gfx/define"; -import { GFXRenderPass } from "../../gfx/render-pass"; -import { RenderPassStage, RenderPipeline, UBOGlobal } from "../render-pipeline"; -import { RenderQueue } from "../render-queue"; -import { ForwardFlow } from "./forward-flow"; +import { Root } from '../../core/root'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXRenderPass } from '../../gfx/render-pass'; +import { RenderPassStage, RenderPipeline, UBOGlobal } from '../render-pipeline'; +import { ForwardFlow } from './forward-flow'; export enum ForwardFlowPriority { FORWARD = 0, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index e9cf5104d8..195e1bb045 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -1,18 +1,17 @@ -import { RenderStage, IRenderStageInfo } from "../render-stage"; -import { RenderFlow } from "../render-flow"; -import { GFXCommandBuffer } from "../../gfx/command-buffer"; -import { RenderView } from "../render-view"; -import { GFXFramebuffer } from "../../gfx/framebuffer"; -import { GFXCommandBufferType } from "../../gfx/define"; -import { GFXInputAssembler } from "../../gfx/input-assembler"; +import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXFramebuffer } from '../../gfx/framebuffer'; +import { RenderFlow } from '../render-flow'; +import { IRenderStageInfo, RenderStage } from '../render-stage'; +import { RenderView } from '../render-view'; export class ForwardStage extends RenderStage { - constructor(flow: RenderFlow) { + constructor (flow: RenderFlow) { super(flow); } - public initialize(info: IRenderStageInfo): boolean { + public initialize (info: IRenderStageInfo): boolean { if (info.name !== undefined) { this._name = info.name; @@ -29,7 +28,7 @@ export class ForwardStage extends RenderStage { return true; } - public destroy() { + public destroy () { if (this._cmdBuff) { this._cmdBuff.destroy(); @@ -37,25 +36,24 @@ export class ForwardStage extends RenderStage { } } - public render(view: RenderView) { + public render (view: RenderView) { - let cmdBuff = this._cmdBuff as GFXCommandBuffer; - let queue = this._pipeline.queue; + const cmdBuff = this._cmdBuff as GFXCommandBuffer; + const queue = this._pipeline.queue; this._renderArea.width = view.width; this._renderArea.height = view.height; cmdBuff.begin(); - cmdBuff.beginRenderPass(this._framebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); + cmdBuff.beginRenderPass( this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); - for (let item of queue.opaques) { - item.model.commandBuffers + for (const item of queue.opaques) { + // item.model.commandBuffers; } - cmdBuff.endRenderPass(); cmdBuff.end(); this._device.queue.submit([cmdBuff]); } -}; +} diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts index 22198e5b84..6060404f65 100644 --- a/cocos/pipeline/forward/test-model-stage.ts +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -80,7 +80,7 @@ export class TestModelStage extends RenderStage { } } - public render(view: RenderView) { + public render (view: RenderView) { if (!this._init) { @@ -88,7 +88,6 @@ export class TestModelStage extends RenderStage { 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('#ff0000')); - this._material.inited = true; this._scene = new Scene(); this._scene._scene = this._scene; diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index 88f0e30e04..daaf6db898 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -1,30 +1,86 @@ -import { Camera } from "../renderer/scene/camera"; -import { GFXWindow } from "../gfx/window"; -import { RenderScene } from "../renderer/scene/render-scene"; +import { Root } from '../core/root'; +import { GFXWindow } from '../gfx/window'; +import { Camera } from '../renderer/scene/camera'; +import { RenderScene } from '../renderer/scene/render-scene'; export enum RenderViewPriority { GENERAL = 100, -}; +} -export interface RenderViewInfo { +export interface IRenderViewInfo { name: string; window: GFXWindow; priority: number; width: number; height: number; -}; +} export class RenderView { - public initialize(info: RenderViewInfo): boolean { + public get name (): string { + return this._name; + } + + public get window (): GFXWindow | null { + return this._window; + } + + public get priority (): number { + return this._priority; + } + + public set visibility (vis: number) { + this._visiblity = vis; + } + public get visibility (): number { + return this._visiblity; + } + + public get width (): number { + return this._width; + } + + public get height (): number { + return this._height; + } + + public get camera (): Camera { + return this._camera as Camera; + } + + public get scene (): RenderScene { + return this._scene as RenderScene; + } + + public static registerCreateFunc (root: Root) { + root._createViewFun = (_root: Root): RenderView => new RenderView(_root); + } + + private _root: Root; + private _name: string = ''; + private _window: GFXWindow | null = null; + private _priority: number = 0; + private _visiblity: number = 0; + private _width: number = 0; + private _height: number = 0; + private _scene: RenderScene | null = null; + private _camera: Camera | null = null; + private _isAttached: boolean = false; + private _isEnable: boolean = true; + + private constructor (root: Root) { + this._root = root; + } + + public initialize (info: IRenderViewInfo): boolean { if (!info.window) { - console.error("RenderViewInfo.window is null."); + console.error('RenderViewInfo.window is null.'); return false; } if (info.width <= 0 || info.height <= 0) { - console.error("RenderView size is an error size."); + console.error('RenderView size is an error size.'); return false; } @@ -37,85 +93,38 @@ export class RenderView { return true; } - public destroy() { + public destroy () { this._window = null; this._priority = 0; this._width = 0; this._height = 0; } - public resize(width, height) { + public resize (width, height) { } - public attach(camera: Camera) { + public attach (camera: Camera) { this._scene = camera.scene; this._camera = camera; this._isAttached = true; } - public detach() { + public detach () { this._scene = null; this._camera = null; this._isAttached = false; } - public enable(isEnable: boolean) { + public enable (isEnable: boolean) { this._isEnable = isEnable; } - public isEnable() : boolean { + public isEnable (): boolean { return this._isEnable; } - - public isAttached() : boolean { + + public isAttached (): boolean { return this._isAttached; } - - public get name(): string { - return this._name; - } - - public get window(): GFXWindow | null { - return this._window; - } - - public get priority(): number { - return this._priority; - } - - public get visibility(): number { - return this._visiblity; - } - - public get width(): number { - return this._width; - } - - public get height(): number { - return this._height; - } - - public get camera(): Camera { - return this._camera as Camera; - } - - public get scene(): RenderScene { - return this._scene as RenderScene; - } - - public set visibility(vis: number) { - this._visiblity = vis; - } - - private _name: string = ""; - private _window: GFXWindow | null = null; - private _priority: number = 0; - private _visiblity: number = 0; - private _width: number = 0; - private _height: number = 0; - private _scene: RenderScene | null = null; - private _camera: Camera | null = null; - private _isAttached: boolean = false; - private _isEnable: boolean = true; -}; +} diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 126f476570..387352929c 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,20 +1,20 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { Material } from '../../3d/assets/material'; import { aabb } from '../../3d/geom-utils'; -import { IGFXInputAttribute, GFXInputAssembler } from '../../gfx/input-assembler'; -import { GFXFormat, GFXBufferUsageBit, GFXMemoryUsageBit, GFXCommandBufferType } from '../../gfx/define'; -import { RenderScene } from './render-scene'; -import { vec3, mat4 } from '../../core/vmath'; import { Vec3 } from '../../core/value-types'; +import { mat4, vec3 } from '../../core/vmath'; +import { GFXBuffer } from '../../gfx/buffer'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; +import { GFXBufferUsageBit, GFXCommandBufferType, GFXFormat, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { UBOLocal } from '../../pipeline/render-pipeline'; import { Node } from '../../scene-graph'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; -import { UBOLocal } from '../../pipeline/render-pipeline'; -import { GFXBuffer } from '../../gfx/buffer'; +import { RenderScene } from './render-scene'; -let _temp_floatx16 = new Float32Array(16); -let _temp_mat4 = mat4.create(); +const _temp_floatx16 = new Float32Array(16); +const _temp_mat4 = mat4.create(); /** * A representation of a model @@ -45,7 +45,7 @@ export default class Model { /** * Setup a default empty model */ - constructor() { + constructor () { this._scene = null; this._id = 0; this._enable = false; @@ -69,7 +69,7 @@ export default class Model { this._localUBO = null; } - initialize() { + public initialize () { this._localUniforms = new UBOLocal(); this._localUBO = cc.director.root.device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, @@ -77,11 +77,12 @@ export default class Model { size: UBOLocal.SIZE, stride: UBOLocal.SIZE, }); - if (this._localUBO) + if (this._localUBO) { this._localUBO.update(this._localUniforms.view); + } } - set scene(scene: RenderScene | null) { + set scene (scene: RenderScene | null) { this._scene = scene; if (this._scene) { @@ -89,31 +90,34 @@ export default class Model { } } - get scene(): RenderScene | null { + get scene (): RenderScene | null { return this._scene; } - get id(): number { + get id (): number { return this._id; } - public _updateTransform() { + public _updateTransform () { if (!this._node._hasChanged || !this._boundingShape) { return; } this._node.updateWorldTransformFull(); this._bsModelSpace.transform(this._node._mat, this._node._pos, this._node._rot, this._node._scale, this._boundingShape); } - updateRenderData() { + public updateRenderData () { mat4.array(_temp_floatx16, this._node._mat); this._node._mat.invert(_temp_mat4); - if (this._localUniforms) + if (this._localUniforms) { this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); + } mat4.array(_temp_floatx16, _temp_mat4); - if (this._localUniforms) + if (this._localUniforms) { this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); - if (this._localUBO) + } + if (this._localUBO) { this._localUBO.update(this._localUniforms.view); + } } /** @@ -121,17 +125,17 @@ export default class Model { * @param {vec3} minPos the min position of the model * @param {vec3} maxPos the max position of the model */ - public createBoundingShape(minPos: Vec3, maxPos: Vec3) { + public createBoundingShape (minPos: Vec3, maxPos: Vec3) { if (!minPos || !maxPos) { return; } this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); this._boundingShape = aabb.clone(this._bsModelSpace); } - public enable(isEnable: boolean) { + public enable (isEnable: boolean) { this._isEnable = isEnable; } - public isEnable(): boolean { + public isEnable (): boolean { return this._isEnable; } @@ -139,7 +143,7 @@ export default class Model { * Get the hosting node of this camera * @returns {Node} the hosting node */ - get node(): Node { + get node (): Node { return this._node; } @@ -147,7 +151,7 @@ export default class Model { * Set the hosting node of this model * @param {Node} node the hosting node */ - set node(node: Node) { + set node (node: Node) { this._node = node; } @@ -155,7 +159,7 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - set inputAssembler(ia: GFXInputAssembler) { + set inputAssembler (ia: GFXInputAssembler) { this._inputAssembler = ia; } @@ -171,7 +175,7 @@ export default class Model { * Set the model effect * @param {?Effect} effect the effect to use */ - public setEffect(effect: Effect) { + public setEffect (effect: Effect) { if (effect) { this._effect = effect; // this._defines = effect.extractDefines(Object.create(null)); @@ -183,7 +187,7 @@ export default class Model { } } - set material(material: Material) { + set material (material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { this.recordCommandBuffer(i); @@ -196,7 +200,7 @@ export default class Model { } } - public recordCommandBuffer(index: number) { + public recordCommandBuffer (index: number) { const pass = (this._material as Material).passes[index]; const cmdBufferInfo = { allocator: cc.director.root.device.commandAllocator, @@ -205,8 +209,9 @@ export default class Model { if (this._cmdBuffers[index] == null) { this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); } - if (this._localUBO) + if (this._localUBO) { pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO); + } pass.bindingLayout.update(); this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); @@ -220,15 +225,15 @@ export default class Model { * Set the user key * @param {number} key */ - set userKey(key: number) { + set userKey (key: number) { this._userKey = key; } - get passes(): Pass[] { + get passes (): Pass[] { return (this._material as Material).passes; } - get commandBuffers(): GFXCommandBuffer[] { + get commandBuffers (): GFXCommandBuffer[] { return this._cmdBuffers; } @@ -236,7 +241,7 @@ export default class Model { * Extract a drawing item * @param {Object} out the receiving item */ - public extractDrawItem(out) { + public extractDrawItem (out) { out.model = this; out.node = this._node; out.ia = this._inputAssembler; diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 52a0135342..2968a6ce14 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,55 +1,92 @@ -import Node from "../../scene-graph/node"; -import Light from "./light"; -import Model from "./model"; -import { Camera } from "./camera"; -import { Root } from "../../core/root"; +import { Root, _createSceneFun } from '../../core/root'; +import Node from '../../scene-graph/node'; +import { Camera } from './camera'; +import Light from './light'; +import Model from './model'; -export interface RenderSceneInfo { +export interface IRenderSceneInfo { name: string; -}; +} -export interface SceneNodeInfo { +export interface ISceneNodeInfo { name: string; isStatic?: boolean; - //parent: Node; + // parent: Node; } export class RenderScene { - constructor(root: Root) { + public get root (): Root { + return this._root; + } + + public get name (): string { + return this._name; + } + + public get cameras (): Camera[] { + return this._cameras; + } + + public get mainCamera (): Camera | null { + return this._mainCamera; + } + + public get lights (): Light[] { + return this._lights; + } + + public get models (): Model[] { + return this._models; + } + + public static registerCreateFunc (root: Root) { + root._createSceneFun = (_root: Root): RenderScene => new RenderScene(_root); + } + + private _root: Root; + private _name: string = ''; + private _nodes: Map = new Map(); + private _cameras: Camera[] = []; + private _mainCamera: Camera | null = null; + private _lights: Light[] = []; + private _models: Model[] = []; + private _modelId: number = 0; + + private constructor (root: Root) { this._root = root; } - public initialize(info: RenderSceneInfo): boolean { + public initialize (info: IRenderSceneInfo): boolean { this._name = info.name; - this._mainCamera = this.createCamera("mainCamera"); + this._mainCamera = this.createCamera('mainCamera'); return true; } - public destroy() { + public destroy () { this.destroyCameras(); this.destroyLights(); this.destroyNodes(); this.destroyModels(); } - public createNode(info: SceneNodeInfo): Node { - let node = new Node(info.name); + public createNode (info: ISceneNodeInfo): Node { + const node = new Node(info.name); this._nodes.set(node.uuid, node); return node; } - public destroyNode(node: Node) { + public destroyNode (node: Node) { this._nodes.delete(node.uuid); } - public destroyNodes() { + public destroyNodes () { this._nodes.clear(); } - public getNode(id: number): Node | null { - let node = this._nodes.get(id); + public getNode (id: number): Node | null { + const node = this._nodes.get(id); if (node) { return node; } else { @@ -57,13 +94,13 @@ export class RenderScene { } } - public createCamera(name: string): Camera { - let camera = new Camera(this, name); + public createCamera (name: string): Camera { + const camera = new Camera(this, name); this._cameras.push(camera); return camera; } - public destroyCamera(camera: Camera) { + public destroyCamera (camera: Camera) { for (let i = 0; i < this._cameras.length; ++i) { if (this._cameras[i] === camera) { this._cameras.slice(i); @@ -72,28 +109,28 @@ export class RenderScene { } } - public destroyCameras() { + public destroyCameras () { this._cameras = []; this._mainCamera = null; } - public getCamera(name: string): Camera | null { - for (let i = 0; i < this._cameras.length; ++i) { - if (this._cameras[i].name === name) { - return this._cameras[i]; + public getCamera (name: string): Camera | null { + for (const camera of this._cameras) { + if (camera.name === name) { + return camera; } } return null; } - public createLight(name: string): Light { - let light = new Light(this, name); + public createLight (name: string): Light { + const light = new Light(this, name); this._lights.push(light); return light; } - public destroyLight(light: Light) { + public destroyLight (light: Light) { for (let i = 0; i < this._lights.length; ++i) { if (this._lights[i] === light) { this._lights.slice(i); @@ -102,13 +139,12 @@ export class RenderScene { } } - public destroyLights() { + public destroyLights () { this._lights = []; } - public getLight(name: string): Light | null { - for (let i = 0; i < this._lights.length; ++i) { - let light = this._lights[i]; + public getLight (name: string): Light | null { + for (const light of this._lights) { if (light.getName() === name) { return light; } @@ -117,15 +153,15 @@ export class RenderScene { return null; } - public createModel(clazz: new () => T): Model { - let model = new clazz; + public createModel (clazz: new () => T): Model { + const model = new clazz(); model.initialize(); model.scene = this; this._models.push(model); return model; } - public destroyModel(model: Model) { + public destroyModel (model: Model) { for (let i = 0; i < this._models.length; ++i) { if (this._models[i] === model) { this._models.slice(i); @@ -134,44 +170,11 @@ export class RenderScene { } } - public destroyModels() { + public destroyModels () { this._models = []; } - public generateModelId(): number { + public generateModelId (): number { return this._modelId++; } - - public get root(): Root { - return this._root; - } - - public get name(): string { - return this._name; - } - - public get cameras(): Camera[] { - return this._cameras; - } - - public get mainCamera(): Camera | null { - return this._mainCamera; - } - - public get lights(): Light[] { - return this._lights; - } - - public get models(): Model[] { - return this._models; - } - - private _root: Root; - private _name: string = ""; - private _nodes: Map = new Map; - private _cameras: Camera[] = []; - private _mainCamera: Camera | null = null; - private _lights: Light[] = []; - private _models: Model[] = []; - private _modelId: number = 0; -}; +} diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index 75838edfc7..b3788a9aac 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -56,7 +56,8 @@ export default class Scene extends Node { // cache all depend assets for auto release this.dependAssets = null; - this._renderScenes.push(new RenderScene()); + let scene = cc.director.root.createScene({ name: 'mainScene' }); + this._renderScenes.push(scene); } /** From e8b42aa1096e71a7031c327e782e50e3416a6f86 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 14:53:34 +0800 Subject: [PATCH 084/267] commit simple.html --- playground/simple.html | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/playground/simple.html b/playground/simple.html index 66149dabee..a914784c6d 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -39,6 +39,21 @@ cc.view.setCanvasSize(bcr.width, bcr.height); }); + /* + let scene = new cc.Scene('testScene'); + scene._scene = scene; + + let material = new cc.Material(); + material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js + material.setProperty('u_color', cc.color('#ff0000')); + + let modelCom = scene.addComponent('cc.ModelComponent'); + modelCom.material = material; + modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + scene.setRotationFromEuler(45, 45, 45); + scene._rot = scene._lrot; + */ + let root = cc.director.root; let scene = root.createScene({ name: "testScene", @@ -61,7 +76,6 @@ camera.direction = { x: 0.0, y: 0.0, z: -1.0 }; camera.update(); - //todo initialization /* let scene = new cc.Scene(); From 407ca757f41fd5c1d9e513d97ff4c455623ff5cd Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Thu, 10 Jan 2019 15:14:22 +0800 Subject: [PATCH 085/267] fix pass --- cocos/renderer/core/pass.ts | 7 ++++++- cocos/renderer/scene/model.ts | 2 -- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 52c6d904b2..dd852744b7 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -13,7 +13,7 @@ import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; -import { RenderPassStage } from '../../pipeline/render-pipeline'; +import { RenderPassStage, UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; export interface IPassInfoFull extends IPassInfo { // generated part @@ -53,6 +53,8 @@ const _type2default = { [GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], }; +const builtinRE = new RegExp(UBOGlobal.BLOCK.name + '|' + UBOLocal.BLOCK.name); + const btMask = 0xf0000000; // 4 bits, 16 slots const typeMask = 0x0fc00000; // 6 bits, 64 slots const bindingMask = 0x003ff800; // 11 bits, 2048 slots @@ -115,6 +117,9 @@ export class Pass { this.createPipelineState(info); for (const u of info.blocks) { + if (builtinRE.test(u.name)) { + continue; + } // create gfx buffer resource const buffer = device.createBuffer({ memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 8b6a072261..7d4806b5fe 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -23,7 +23,6 @@ export default class Model { private _scene: RenderScene | null; private _id: number; - private _enable: boolean; private _type: string; private _poolID: number; private _isEnable: boolean; @@ -48,7 +47,6 @@ export default class Model { constructor() { this._scene = null; this._id = 0; - this._enable = false; this._type = 'default'; this._poolID = -1; From 66e4b216a8a437dabfacc369c95ee4cb1cb10fe6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 15:28:52 +0800 Subject: [PATCH 086/267] fix undefined property --- cocos/3d/primitive/defines.ts | 2 +- cocos/pipeline/forward/test-model-stage.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts index 9a3edcd280..00768e2276 100644 --- a/cocos/3d/primitive/defines.ts +++ b/cocos/3d/primitive/defines.ts @@ -39,7 +39,7 @@ export interface IGeometryOptions { } export function normalizeGeometryOptions (options: IGeometryOptions) { - options.wireframed = options.wireframed || false; + options.wireframed = options.wireframed !== undefined? options.wireframed : false; options.windingOrder = options.windingOrder === undefined ? WindingOrder.CounterClockwise : options.windingOrder; options.includeNormal = options.includeNormal === undefined ? diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts index c0b167a9a2..218111fd7b 100644 --- a/cocos/pipeline/forward/test-model-stage.ts +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -85,7 +85,7 @@ export class TestModelStage extends RenderStage { this._scene._scene = this._scene; const modelCom = this._scene.addComponent('cc.ModelComponent'); modelCom.material = this._material; - modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, 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; From 592468de04031d70f5cce7d57070c148924681f9 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 16:40:13 +0800 Subject: [PATCH 087/267] revert box.ts --- cocos/3d/primitive/box.ts | 266 +++++++++++++++----------------- cocos/3d/primitive/defines.ts | 70 ++++----- cocos/3d/primitive/index.js | 3 +- cocos/3d/primitive/transform.ts | 23 +++ 4 files changed, 178 insertions(+), 184 deletions(-) create mode 100644 cocos/3d/primitive/transform.ts diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts index 0152d15079..7617d64963 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/3d/primitive/box.ts @@ -1,21 +1,37 @@ +import { vec3 } from '../../core/vmath'; import { GFXPrimitiveMode } from '../../gfx/define'; -import { IGeometry, IGeometryOptions, normalizeGeometryOptions, WindingOrder } from './defines'; +import { IGeometry, IGeometryOptions, normalizeGeometryOptions } from './defines'; interface IBoxOptions extends IGeometryOptions { /** * Box extent on X-axis. */ - length: number; - - /** - * Box extent on Z-axis. - */ width: number; /** * Box extent on Y-axis. */ height: number; + + /** + * Box extent on Z-axis. + */ + length: number; + + /** + * Segment count on X-axis. + */ + widthSegments?: number; + + /** + * Segment count on Y-axis. + */ + heightSegments?: number; + + /** + * Segment count on Z-axis. + */ + lengthSegments?: number; } /** @@ -25,150 +41,116 @@ interface IBoxOptions extends IGeometryOptions { */ export default function box (options: IBoxOptions): IGeometry { normalizeGeometryOptions(options); + const ws = options.widthSegments || 1; + const hs = options.heightSegments || 1; + const ls = options.lengthSegments || 1; - const right = options.length / 2; - const left = -right; - const top = options.height / 2; - const bottom = -top; - const near = options.width / 2; - const far = -near; - const center = options.center ? { - x: options.center.x || 0, - y: options.center.y || 0, - z: options.center.z || 0, - } : { - x: 0, - y: 0, - z: 0, - }; + const hw = options.width / 2; + const hh = options.height / 2; + const hl = options.length / 2; - const vertices: number[] = []; - const addVertex = (x: number, y: number, z: number) => { - vertices.push(x + center.x, y + center.y, z + center.z); - }; - addVertex(left, top, near); - addVertex(left, bottom, near); - addVertex(right, bottom, near); - addVertex(right, top, near); - addVertex(left, top, far); - addVertex(left, bottom, far); - addVertex(right, bottom, far); - addVertex(right, top, far); + const corners = [ + vec3.set(c0, -hw, -hh, hl), + vec3.set(c1, hw, -hh, hl), + vec3.set(c2, hw, hh, hl), + vec3.set(c3, -hw, hh, hl), + vec3.set(c4, hw, -hh, -hl), + vec3.set(c5, -hw, -hh, -hl), + vec3.set(c6, -hw, hh, -hl), + vec3.set(c7, hw, hh, -hl), + ]; - let indices: number[] = []; - let normals: number[] | undefined; - let primitiveType: GFXPrimitiveMode = GFXPrimitiveMode.POINT_LIST; - if (options.wireframed) { - primitiveType = GFXPrimitiveMode.LINE_LIST; - indices = indices.concat([ - 0, 1, 1, 2, 2, 3, 3, 0, // Front quad - 4, 5, 5, 6, 6, 7, 7, 4, // Back quad - 0, 4, 1, 5, 2, 6, 3, 7, // Side lines - ]); - } else { - primitiveType = GFXPrimitiveMode.TRIANGLE_LIST; - type FaceNormal = [ number, number, number ]; - type FaceQuad = [ - number, // Left top - number, // Left bottom - number, // Right bottom - number // Right top - ]; - interface IFaceInfo { - quad: FaceQuad; - normal: FaceNormal; - } - interface IFaceInfos { - front: IFaceInfo; - right: IFaceInfo; - back: IFaceInfo; - left: IFaceInfo; - top: IFaceInfo; - bottom: IFaceInfo; - } + const faceAxes = [ + [2, 3, 1], // FRONT + [4, 5, 7], // BACK + [7, 6, 2], // TOP + [1, 0, 4], // BOTTOM + [1, 4, 2], // RIGHT + [5, 0, 6], // LEFT + ]; - const addTri = (i: number, j: number, k: number) => { - if (options.windingOrder === WindingOrder.CounterClockwise) { - indices.push(i, j, k); - } else { - indices.push(i, k, j); + const faceNormals = [ + [0, 0, 1], // FRONT + [0, 0, -1], // BACK + [0, 1, 0], // TOP + [0, -1, 0], // BOTTOM + [1, 0, 0], // RIGHT + [-1, 0, 0], // LEFT + ]; + + const positions: number[] = []; + const normals: number[] = []; + const uvs: number[] = []; + const indices: number[] = []; + const minPos = vec3.create(-hw, -hh, -hl); + const maxPos = vec3.create(hw, hh, hl); + const boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl); + + function _buildPlane (side: number, uSegments: number, vSegments: number) { + let u: number; + let v: number; + let ix: number; + let iy: number; + const offset = positions.length / 3; + const faceAxe = faceAxes[side]; + const faceNormal = faceNormals[side]; + + for (iy = 0; iy <= vSegments; iy++) { + for (ix = 0; ix <= uSegments; ix++) { + u = ix / uSegments; + v = iy / vSegments; + + vec3.lerp(temp1, corners[faceAxe[0]], corners[faceAxe[1]], u); + vec3.lerp(temp2, corners[faceAxe[0]], corners[faceAxe[2]], v); + vec3.sub(temp3, temp2, corners[faceAxe[0]]); + vec3.add(r, temp1, temp3); + + positions.push(r.x, r.y, r.z); + normals.push(faceNormal[0], faceNormal[1], faceNormal[2]); + uvs.push(u, v); + + if ((ix < uSegments) && (iy < vSegments)) { + const useg1 = uSegments + 1; + const a = ix + iy * useg1; + const b = ix + (iy + 1) * useg1; + const c = (ix + 1) + (iy + 1) * useg1; + const d = (ix + 1) + iy * useg1; + + indices.push(offset + a, offset + d, offset + b); + indices.push(offset + b, offset + d, offset + c); + } } - }; - - const addQuad = (faceQuad: FaceQuad) => { - const lt = faceQuad[0]; - const lb = faceQuad[1]; - const rb = faceQuad[2]; - const rt = faceQuad[3]; - addTri(lt, lb, rb); - addTri(lt, rb, rt); - }; - - const addNormal = (faceNormal: FaceNormal) => { - const x = faceNormal[0]; - const y = faceNormal[1]; - const z = faceNormal[2]; - if (options.windingOrder === WindingOrder.CounterClockwise) { - normals!.push(x, y, z); - } else { - normals!.push(-x, -y, -z); - } - }; - - const addFace = (face: IFaceInfo) => { - addQuad(face.quad); - if (normals) { - addNormal(face.normal); - } - }; - - const faceInfos: IFaceInfos = { - front: { - quad: [0, 1, 2, 3], - normal: [0, 0, 1], - }, - right: { - quad: [3, 2, 6, 7], - normal: [1, 0, 0], - }, - back: { - quad: [7, 6, 5, 4], - normal: [0, 0, -1], - }, - left: { - quad: [4, 5, 1, 0], - normal: [-1, 0, 0], - }, - top: { - quad: [4, 0, 3, 7], - normal: [0, 1, 0], - }, - bottom: { - quad: [1, 5, 6, 2], - normal: [0, -1, 0], - }, - }; - - if (options.includeNormal) { - normals = []; } - addFace(faceInfos.front); - addFace(faceInfos.right); - addFace(faceInfos.back); - addFace(faceInfos.left); - addFace(faceInfos.top); - addFace(faceInfos.bottom); } - const result: IGeometry = { - primitiveType, - vertices, + _buildPlane(0, ws, hs); // FRONT + _buildPlane(4, ls, hs); // RIGHT + _buildPlane(1, ws, hs); // BACK + _buildPlane(5, ls, hs); // LEFT + _buildPlane(3, ws, ls); // BOTTOM + _buildPlane(2, ws, ls); // TOP + + return { + primitiveType: GFXPrimitiveMode.TRIANGLE_LIST, + positions, + normals, + uvs, indices, + minPos, + maxPos, + boundingRadius, }; - - if (normals) { - result.normals = normals; - } - - return result; } + +const temp1 = vec3.create(0, 0, 0); +const temp2 = vec3.create(0, 0, 0); +const temp3 = vec3.create(0, 0, 0); +const r = vec3.create(0, 0, 0); +const c0 = vec3.create(0, 0, 0); +const c1 = vec3.create(0, 0, 0); +const c2 = vec3.create(0, 0, 0); +const c3 = vec3.create(0, 0, 0); +const c4 = vec3.create(0, 0, 0); +const c5 = vec3.create(0, 0, 0); +const c6 = vec3.create(0, 0, 0); +const c7 = vec3.create(0, 0, 0); diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts index 00768e2276..145b174f65 100644 --- a/cocos/3d/primitive/defines.ts +++ b/cocos/3d/primitive/defines.ts @@ -1,55 +1,15 @@ import { GFXPrimitiveMode } from '../../gfx/define'; -export enum WindingOrder { - /** - * Clockwise. - */ - Clockwise, - - /** - * Counter-clockwise. - */ - CounterClockwise, -} - export interface IGeometryOptions { - /** - * Whether generated wireframed geometry. Default to false. - */ - wireframed?: boolean; - - /** - * The winding order. Default to counter-clockwise. - */ - windingOrder?: WindingOrder; - /** * Whether to include normal. Default to true. */ includeNormal?: boolean; - - /** - * The center of the geometry. Default to (0, 0, 0). - */ - center?: { - x?: number; - y?: number; - z?: number; - }; } export function normalizeGeometryOptions (options: IGeometryOptions) { - options.wireframed = options.wireframed !== undefined? options.wireframed : false; - options.windingOrder = options.windingOrder === undefined ? - WindingOrder.CounterClockwise : options.windingOrder; options.includeNormal = options.includeNormal === undefined ? true : options.includeNormal; - if (!options.center) { - options.center = {}; - } - options.center.x = options.center.x || 0; - options.center.y = options.center.y || 0; - options.center.z = options.center.z || 0; return options; } @@ -62,7 +22,30 @@ export interface IGeometry { /** * Vertex positions. */ - vertices: number[]; + positions: number[]; + + /** + * Min position. + */ + minPos: { + x: number; + y: number; + z: number; + }; + + /** + * Max position. + */ + maxPos: { + x: number; + y: number; + z: number; + }; + + /** + * Bounding sphere radius. + */ + boundingRadius: number; /** * Gemetry indices, if one needs indexed-draw. @@ -73,4 +56,9 @@ export interface IGeometry { * Vertex normals. */ normals?: number[]; + + /** + * Texture coordinates. + */ + uvs?: number[]; } diff --git a/cocos/3d/primitive/index.js b/cocos/3d/primitive/index.js index f69ede2753..f7e2132075 100644 --- a/cocos/3d/primitive/index.js +++ b/cocos/3d/primitive/index.js @@ -6,4 +6,5 @@ export { default as plane } from './plane'; export { default as quad } from './quad'; export { default as sphere } from './sphere'; export { default as torus } from './torus'; -export { default as capsule } from './capsule'; \ No newline at end of file +export { default as capsule } from './capsule'; +export { translate } from './transform'; \ No newline at end of file diff --git a/cocos/3d/primitive/transform.ts b/cocos/3d/primitive/transform.ts new file mode 100644 index 0000000000..fac9fb15d2 --- /dev/null +++ b/cocos/3d/primitive/transform.ts @@ -0,0 +1,23 @@ +import { IGeometry } from './defines'; + +export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }) { + const x = offset.x || 0; + const y = offset.y || 0; + const z = offset.z || 0; + const nVertex = Math.floor(geometry.positions.length / 3); + for (let iVertex = 0; iVertex < nVertex; ++iVertex) { + const iX = iVertex * 3; + const iY = iVertex * 3 + 1; + const iZ = iVertex * 3 + 2; + geometry[iX] = geometry[iX] + x; + geometry[iY] = geometry[iY] + y; + geometry[iZ] = geometry[iZ] + z; + } + geometry.minPos.x += x; + geometry.minPos.y += y; + geometry.minPos.z += z; + geometry.maxPos.x += x; + geometry.maxPos.y += y; + geometry.maxPos.z += z; + return geometry; +} From a825b47439055fd98962594f7b09e7d4b5ac9533 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 16:49:49 +0800 Subject: [PATCH 088/267] bug fix --- cocos/3d/primitive/transform.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/3d/primitive/transform.ts b/cocos/3d/primitive/transform.ts index fac9fb15d2..a308cb01df 100644 --- a/cocos/3d/primitive/transform.ts +++ b/cocos/3d/primitive/transform.ts @@ -9,9 +9,9 @@ export function translate (geometry: IGeometry, offset: { x?: number; y?: number const iX = iVertex * 3; const iY = iVertex * 3 + 1; const iZ = iVertex * 3 + 2; - geometry[iX] = geometry[iX] + x; - geometry[iY] = geometry[iY] + y; - geometry[iZ] = geometry[iZ] + z; + geometry.positions[iX] = geometry.positions[iX] + x; + geometry.positions[iY] = geometry.positions[iY] + y; + geometry.positions[iZ] = geometry.positions[iZ] + z; } geometry.minPos.x += x; geometry.minPos.y += y; From a12d79b9841c98cca9ca563e89ab433983ce19b6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 16:51:48 +0800 Subject: [PATCH 089/267] add a size param into GFXBuffer.update() interface --- cocos/gfx/buffer.ts | 2 +- cocos/gfx/webgl/webgl-buffer.ts | 15 ++++++++++----- cocos/gfx/webgl/webgl-commands.ts | 20 ++++++++++++++++---- cocos/gfx/webgl/webgl-device.ts | 4 ++-- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 957b756227..627a9e231e 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -45,5 +45,5 @@ export abstract class GFXBuffer extends GFXObject { public abstract initialize (info: IGFXBufferInfo): boolean; public abstract destroy (): void; - public abstract update (buffer: ArrayBuffer, offset?: number); + public abstract update (buffer: ArrayBuffer, offset?: number, size?: number); } diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 031c049fa7..ac7c889c94 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,5 +1,5 @@ import { GFXBuffer, IGFXBufferInfo } from '../buffer'; -import { GFXMemoryUsageBit, GFXStatus } from '../define'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; @@ -54,12 +54,17 @@ export class WebGLGFXBuffer extends GFXBuffer { this._status = GFXStatus.UNREADY; } - public update (buffer: ArrayBuffer, offset?: number) { + public update (buffer: ArrayBuffer, offset?: number, size?: number) { - if (this._bufferView) { - this._bufferView.set(new Uint8Array(buffer), offset); + const isUniformBuffer = (this._usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; + if (this._bufferView && !isUniformBuffer) { + this._bufferView.set(new Uint8Array(buffer, 0, size), offset); } - this.webGLDevice.emitCmdUpdateGPUBuffer( this._gpuBuffer as WebGLGPUBuffer, offset ? offset : 0, buffer); + this.webGLDevice.emitCmdUpdateGPUBuffer( + this._gpuBuffer as WebGLGPUBuffer, + buffer, + offset !== undefined ? offset : 0, + size !== undefined ? size : buffer.byteLength); } } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 8f29fe8ecd..77963cd05a 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -577,11 +577,11 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: We } } -export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { +export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: ArrayBuffer, offset: number, size: number) { if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { if (gpuBuffer.viewF32 && buffer) { - gpuBuffer.viewF32.set(new Float32Array(buffer), offset); + gpuBuffer.viewF32.set(new Float32Array(buffer, 0, size / 4), offset); } } else { const gl = device.gl; @@ -592,7 +592,13 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: Web gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + + if (size === buffer.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buffer, 0, size)); + } + break; } case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { @@ -600,7 +606,13 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: Web gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + + if (size === buffer.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + } else { + gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buffer, 0, size)); + } + break; } default: { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index d636823ef8..9d8604c6bd 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -537,11 +537,11 @@ export class WebGLGFXDevice extends GFXDevice { WebGLCmdFuncDestroyBuffer(this as WebGLGFXDevice, gpuBuffer); } - public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, offset: number, buffer: ArrayBuffer) { + public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: ArrayBuffer, offset: number, size: number) { // TODO: Async const isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; if (!isStagingBuffer) { - WebGLCmdFuncUpdateBuffer(this as WebGLGFXDevice, gpuBuffer, offset, buffer); + WebGLCmdFuncUpdateBuffer(this as WebGLGFXDevice, gpuBuffer, buffer, offset, size); } } From 6681e9c770c915075d7195969529dba7d25500f9 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 11:28:35 +0800 Subject: [PATCH 090/267] rename, tslint --- cocos/3d/assets/{mesh.js => mesh.ts} | 75 ++++++++++++++-------------- 1 file changed, 37 insertions(+), 38 deletions(-) rename cocos/3d/assets/{mesh.js => mesh.ts} (85%) diff --git a/cocos/3d/assets/mesh.js b/cocos/3d/assets/mesh.ts similarity index 85% rename from cocos/3d/assets/mesh.js rename to cocos/3d/assets/mesh.ts index 16f7f76ddf..8b9ec9d4d0 100644 --- a/cocos/3d/assets/mesh.js +++ b/cocos/3d/assets/mesh.ts @@ -24,22 +24,22 @@ ****************************************************************************/ // @ts-check -import { _decorator } from "../../core/data"; +import { _decorator } from '../../core/data'; const { ccclass, property } = _decorator; -import { Asset } from "../../assets/asset"; -import gfx from "../../renderer/gfx"; -import { enums as gfxEnums } from "../../renderer/gfx/enums"; -import InputAssembler from "../../renderer/core/input-assembler"; -import BufferRange from "./utils/buffer-range"; -import { Vec3 } from "../../core/value-types"; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from "../../gfx/define"; +import { Asset } from '../../assets/asset'; +import { Vec3 } from '../../core/value-types'; +import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit } from '../../gfx/define'; +import InputAssembler from '../../renderer/core/input-assembler'; +import gfx from '../../renderer/gfx'; +import { enums as gfxEnums } from '../../renderer/gfx/enums'; +import BufferRange from './utils/buffer-range'; /** * A vertex bundle describes a serials of vertex attributes. * These vertex attributes occupy a range of the buffer and * are interleaved, no padding bytes, in the range. */ -@ccclass("cc.VertexBundle") +@ccclass('cc.VertexBundle') export class VertexBundle { /** * The data range of this bundle. @@ -47,21 +47,21 @@ export class VertexBundle { * @type {BufferRange} */ @property(BufferRange) - _data = null; + public _data = null; /** * This bundle's vertices count. * @type {number} */ @property(Number) - _verticesCount = 0; + public _verticesCount = 0; /** * The attributes's formats. * @type {{name: string, type: number, num: number, normalize: boolean}[]} */ @property - _formats = []; + public _formats = []; } cc.VertexBundle = VertexBundle; @@ -69,7 +69,7 @@ cc.VertexBundle = VertexBundle; * A primitive is a geometry constituted with a list of * same topology primitive graphic(such as points, lines or triangles). */ -@ccclass("cc.Primitive") +@ccclass('cc.Primitive') export class Primitive { /** @@ -77,28 +77,28 @@ export class Primitive { * @type {number[]} */ @property([Number]) - _vertexBundelIndices = []; + public _vertexBundelIndices = []; /** * The indices data range of this primitive. * @type {BufferRange} */ @property(BufferRange) - _indices = null; + public _indices = null; /** * The type of this primitive's indices. * @type {number} */ @property(Number) - _indexUnit = gfxEnums.INDEX_FMT_UINT16; + public _indexUnit = gfxEnums.INDEX_FMT_UINT16; /** * This primitive's topology. * @type {number} */ @property(Number) - _topology = gfxEnums.PT_TRIANGLES; + public _topology = gfxEnums.PT_TRIANGLES; } cc.Primitive = Primitive; @@ -109,27 +109,27 @@ export default class Mesh extends Asset { * @type {VertexBundle[]} */ @property([VertexBundle]) - _vertexBundles = []; + public _vertexBundles = []; /** * @type {Primitive[]} */ @property([Primitive]) - _primitives = []; + public _primitives = []; /** * The min position of this mesh's vertices. */ @property(Vec3) - _minPosition = null; + public _minPosition = null; /** * The max position of this mesh's vertices. */ @property(Vec3) - _maxPosition = null; + public _maxPosition = null; - constructor() { + constructor () { super(); /** @@ -143,18 +143,18 @@ export default class Mesh extends Asset { this._data = null; } - get _nativeAsset() { + get _nativeAsset () { return this._data; } - set _nativeAsset(value) { + set _nativeAsset (value) { this._data = value; } /** * */ - _lazyInitRenderResources() { + public _lazyInitRenderResources () { if (this._subMeshes != null) { return; } @@ -166,7 +166,7 @@ export default class Mesh extends Asset { } const buffer = this._getBuffer(); const vertexBuffers = this._vertexBundles.map((vertexBundle) => { - let vb = cc.director.root.device.createBuffer({ + const vb = cc.director.root.device.createBuffer({ usage: GFXBufferUsageBit.VERTEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: vertexBundle._data._length, @@ -188,8 +188,7 @@ export default class Mesh extends Asset { // Currently, an IA only has one vertex buffer. const vertexBuffer = vertexBuffers[primitive._vertexBundelIndices[0]]; - - let ib = cc.director.root.device.createBuffer({ + const ib = cc.director.root.device.createBuffer({ usage: GFXBufferUsageBit.INDEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: primitive._indices._length, @@ -202,11 +201,11 @@ export default class Mesh extends Asset { ib.update(new DataView(buffer, primitive._indices._offset, primitive._indices._length)); - let attributes = []; + const attributes = []; - let vertexBundle = this._vertexBundles[primitive._vertexBundelIndices[0]]; + const vertexBundle = this._vertexBundles[primitive._vertexBundelIndices[0]]; for (let i = 0; i < vertexBundle._formats.length; i++) { - let gfxAttr = {}; + const gfxAttr = {}; gfxAttr.name = vertexBundle._formats[i].name; let gfxFormat; switch (vertexBundle._formats[i].num) { @@ -263,7 +262,7 @@ export default class Mesh extends Asset { * !#en * Destory this mesh and immediately release its video memory. */ - destroy() { + public destroy () { if (this._subMeshes !== null) { // Destroy vertex buffer this._subMeshes[0]._vertexBuffer.destroy(); @@ -282,7 +281,7 @@ export default class Mesh extends Asset { * Submeshes count of this mesh. * @type {number} */ - get subMeshCount() { + get subMeshCount () { this._lazyInitRenderResources(); return this._subMeshes.length; } @@ -292,16 +291,16 @@ export default class Mesh extends Asset { * Gets the specified submesh. * @param {number} index Index of the specified submesh. */ - getSubMesh(index) { + public getSubMesh (index) { this._lazyInitRenderResources(); return this._subMeshes[index]; } - get minPosition() { + get minPosition () { return this._minPosition; } - get maxPosition() { + get maxPosition () { return this._maxPosition; } @@ -320,11 +319,11 @@ export default class Mesh extends Asset { /** * @return {ArrayBuffer} */ - _getBuffer() { + public _getBuffer () { return this._data.buffer; } - _getIndexUnitSize(indexUnit) { + public _getIndexUnitSize (indexUnit) { switch (indexUnit) { case gfxEnums.INDEX_FMT_UINT8: return 1; From 06797ddb05c03ff9bdedf37af8dd941ca571eb79 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 11:48:45 +0800 Subject: [PATCH 091/267] rename; tslint --- .../utils/{buffer-range.js => buffer-range.ts} | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) rename cocos/3d/assets/utils/{buffer-range.js => buffer-range.ts} (90%) diff --git a/cocos/3d/assets/utils/buffer-range.js b/cocos/3d/assets/utils/buffer-range.ts similarity index 90% rename from cocos/3d/assets/utils/buffer-range.js rename to cocos/3d/assets/utils/buffer-range.ts index bbd720b2df..fdd98c48f9 100644 --- a/cocos/3d/assets/utils/buffer-range.js +++ b/cocos/3d/assets/utils/buffer-range.ts @@ -24,32 +24,32 @@ ****************************************************************************/ // @ts-check -import { _decorator } from "../../../core/data"; +import { _decorator } from '../../../core/data'; const { ccclass, property } = _decorator; /** * The class BufferRange denotes a range of the buffer. */ -@ccclass("cc.BufferRange") +@ccclass('cc.BufferRange') export default class BufferRange { /** * The offset of the range. * @type {Number} */ @property(Number) - _offset = 0; + public _offset = 0; /** * The length of the range, in bytes. * @type {Number} */ @property(Number) - _length = 0; + public _length = 0; - constructor(offset, length) { + constructor (offset, length) { this._offset = offset; this._length = length; } } -cc.BufferRange = BufferRange; \ No newline at end of file +cc.BufferRange = BufferRange; From 14fd6888c61aee629279ef3ab768140b7cac2e2f Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 16:07:39 +0800 Subject: [PATCH 092/267] restruct mesh --- cocos/3d/assets/mesh.ts | 599 ++++++++++++++++---------- cocos/3d/assets/utils/buffer-range.ts | 32 +- 2 files changed, 364 insertions(+), 267 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 8b9ec9d4d0..5aab6e00d5 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -25,123 +25,242 @@ // @ts-check import { _decorator } from '../../core/data'; +import { ccenum } from '../../core/value-types/enum'; const { ccclass, property } = _decorator; import { Asset } from '../../assets/asset'; import { Vec3 } from '../../core/value-types'; +import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit } from '../../gfx/define'; -import InputAssembler from '../../renderer/core/input-assembler'; -import gfx from '../../renderer/gfx'; -import { enums as gfxEnums } from '../../renderer/gfx/enums'; -import BufferRange from './utils/buffer-range'; +import { GFXDevice } from '../../gfx/device'; +import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { IBufferRange } from './utils/buffer-range'; -/** - * A vertex bundle describes a serials of vertex attributes. - * These vertex attributes occupy a range of the buffer and - * are interleaved, no padding bytes, in the range. - */ -@ccclass('cc.VertexBundle') -export class VertexBundle { +export enum AttributeBaseType { + /** + * 8 bits signed integer. + */ + INT8, + + /** + * 8 bits unsigned integer. + */ + UINT8, + + /** + * 16 bits signed integer. + */ + INT16, + + /** + * 16 bits unsigned integer. + */ + UINT16, + + /** + * 32 bits signed integer. + */ + INT32, + + /** + * 32 bits unsigned integer. + */ + UINT32, + + /** + * 32 bits floating number. + */ + FLOAT32, +} + +ccenum(AttributeBaseType); + +export enum AttributeType { + /** + * Scalar. + */ + SCALAR, + + /** + * 2 components vector. + */ + VEC2, + + /** + * 3 components vector. + */ + VEC3, + + /** + * 4 components vector. + */ + VEC4, +} + +ccenum(AttributeType); + +export enum Topology { + /** + * Point list. + */ + POINT_LIST, + + /** + * Line list. + */ + LINE_LIST, + + /** + * Triangle list. + */ + TRIANGLE_LIST, +} + +ccenum(Topology); + +export enum IndexUnit { + /** + * 8 bits unsigned integer. + */ + UINT8, + + /** + * 8 bits unsigned integer. + */ + UINT16, + + /** + * 8 bits unsigned integer. + */ + UINT32, +} + +ccenum(IndexUnit); + +function getIndexUnitStride (indexUnit: IndexUnit) { + switch (indexUnit) { + case IndexUnit.UINT8: return 1; + case IndexUnit.UINT16: return 2; + case IndexUnit.UINT32: return 3; + } + return 1; +} + +export interface IVertexAttribute { + /** + * Attribute Name. + */ + name: string; + + /** + * Attribute base type. + */ + baseType: AttributeBaseType; + + /** + * Attribute type. + */ + type: AttributeType; + + /** + * Whether normalize. + */ + normalize: boolean; +} + +function toGfxAttributeType (vertexAttribute: IVertexAttribute) { + let formatName = ''; + switch (vertexAttribute.type) { + case AttributeType.SCALAR: + formatName = 'R'; + break; + case AttributeType.VEC2: + formatName = 'RG'; + break; + case AttributeType.VEC3: + formatName = 'RGB'; + break; + case AttributeType.VEC4: + formatName = 'RGBA'; + break; + } + switch (vertexAttribute.baseType) { + case AttributeBaseType.INT8: + formatName += '8I'; + break; + case AttributeBaseType.UINT8: + formatName += '8UI'; + break; + case AttributeBaseType.INT16: + formatName += '16I'; + break; + case AttributeBaseType.UINT16: + formatName += '16UI'; + break; + case AttributeBaseType.INT32: + formatName += '32I'; + break; + case AttributeBaseType.UINT32: + formatName += '32UI'; + break; + case AttributeBaseType.FLOAT32: + formatName += '32F'; + break; + } + + const resultFormat = GFXFormat[formatName]; + if (resultFormat !== undefined) { + return resultFormat; + } + + return GFXFormat.R8UI; +} + +export interface IVertexBundle { /** * The data range of this bundle. * This range of data is essentially mapped to a GPU vertex buffer. - * @type {BufferRange} */ - @property(BufferRange) - public _data = null; + data: IBufferRange; /** * This bundle's vertices count. - * @type {number} */ - @property(Number) - public _verticesCount = 0; + verticesCount: number; /** - * The attributes's formats. - * @type {{name: string, type: number, num: number, normalize: boolean}[]} + * Attributes. */ - @property - public _formats = []; + attributes: IVertexAttribute[]; } -cc.VertexBundle = VertexBundle; /** * A primitive is a geometry constituted with a list of * same topology primitive graphic(such as points, lines or triangles). */ -@ccclass('cc.Primitive') -export class Primitive { - +export interface IPrimitive { /** * The vertex bundles that this primitive use. - * @type {number[]} */ - @property([Number]) - public _vertexBundelIndices = []; + vertexBundelIndices: number[]; /** * The indices data range of this primitive. - * @type {BufferRange} */ - @property(BufferRange) - public _indices = null; + indices: IBufferRange; /** * The type of this primitive's indices. - * @type {number} */ - @property(Number) - public _indexUnit = gfxEnums.INDEX_FMT_UINT16; + indexUnit: IndexUnit; /** * This primitive's topology. - * @type {number} */ - @property(Number) - public _topology = gfxEnums.PT_TRIANGLES; + topology: Topology; } -cc.Primitive = Primitive; @ccclass('cc.Mesh') export default class Mesh extends Asset { - /** - * The vertex bundles that this mesh owns. - * @type {VertexBundle[]} - */ - @property([VertexBundle]) - public _vertexBundles = []; - - /** - * @type {Primitive[]} - */ - @property([Primitive]) - public _primitives = []; - - /** - * The min position of this mesh's vertices. - */ - @property(Vec3) - public _minPosition = null; - - /** - * The max position of this mesh's vertices. - */ - @property(Vec3) - public _maxPosition = null; - - constructor () { - super(); - - /** - * @type {GFXInputAssembler[]} - */ - this._subMeshes = null; - - /** - * @type {Uint8Array} - */ - this._data = null; - } get _nativeAsset () { return this._data; @@ -152,148 +271,11 @@ export default class Mesh extends Asset { } /** - * - */ - public _lazyInitRenderResources () { - if (this._subMeshes != null) { - return; - } - - this._subMeshes = []; - - if (this._data === null) { - return; - } - const buffer = this._getBuffer(); - const vertexBuffers = this._vertexBundles.map((vertexBundle) => { - const vb = cc.director.root.device.createBuffer({ - usage: GFXBufferUsageBit.VERTEX, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: vertexBundle._data._length, - stride: vertexBundle._data._length / vertexBundle._verticesCount, - }); - - if (!vb) { - return null; - } - - vb.update(new Uint8Array(buffer, vertexBundle._data._offset, vertexBundle._data._length)); - return vb; - }); - this._subMeshes = this._primitives.map((primitive) => { - if (primitive._vertexBundelIndices.length === 0) { - return null; - } - - // Currently, an IA only has one vertex buffer. - const vertexBuffer = vertexBuffers[primitive._vertexBundelIndices[0]]; - - const ib = cc.director.root.device.createBuffer({ - usage: GFXBufferUsageBit.INDEX, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: primitive._indices._length, - stride: this._getIndexUnitSize(primitive._indexUnit), - }); - - if (!ib) { - return null; - } - - ib.update(new DataView(buffer, primitive._indices._offset, primitive._indices._length)); - - const attributes = []; - - const vertexBundle = this._vertexBundles[primitive._vertexBundelIndices[0]]; - for (let i = 0; i < vertexBundle._formats.length; i++) { - const gfxAttr = {}; - gfxAttr.name = vertexBundle._formats[i].name; - let gfxFormat; - switch (vertexBundle._formats[i].num) { - case 1: - gfxFormat = 'R'; - break; - case 2: - gfxFormat = 'RG'; - break; - case 3: - gfxFormat = 'RGB'; - break; - case 4: - gfxFormat = 'RGBA'; - break; - } - switch (vertexBundle._formats[i].type) { - case gfx.ATTR_TYPE_INT8: - gfxFormat += '8I'; - break; - case gfx.ATTR_TYPE_UINT8: - gfxFormat += '8UI'; - break; - case gfx.ATTR_TYPE_INT16: - gfxFormat += '16I'; - break; - case gfx.ATTR_TYPE_UINT16: - gfxFormat += '16UI'; - break; - case gfx.ATTR_TYPE_INT32: - gfxFormat += '32I'; - break; - case gfx.ATTR_TYPE_UINT32: - gfxFormat += '32UI'; - break; - case gfx.ATTR_TYPE_FLOAT32: - gfxFormat += '32F'; - break; - } - gfxAttr.format = GFXFormat[gfxFormat]; - gfxAttr.normalize = vertexBundle._formats[i].normalize; - attributes.push(gfxAttr); - } - - return cc.director.root.device.createInputAssembler({ - attributes, - vertexBuffers: [vertexBuffer], - indexBuffer: ib, - }); - }); - } - - /** - * !#en - * Destory this mesh and immediately release its video memory. - */ - public destroy () { - if (this._subMeshes !== null) { - // Destroy vertex buffer - this._subMeshes[0]._vertexBuffer.destroy(); - // Destroy index buffers - for (let i = 0; i < this._subMeshes.length; ++i) { - this._subMeshes[i]._indexBuffer.destroy(); - } - this._subMeshes = null; - } - - return super.destroy(); - } - - /** - * !#en * Submeshes count of this mesh. - * @type {number} */ get subMeshCount () { this._lazyInitRenderResources(); - return this._subMeshes.length; - } - - /** - * !#en - * Gets the specified submesh. - * @param {number} index Index of the specified submesh. - */ - public getSubMesh (index) { - this._lazyInitRenderResources(); - return this._subMeshes[index]; + return this._subMeshes!.length; } get minPosition () { @@ -303,36 +285,177 @@ export default class Mesh extends Asset { get maxPosition () { return this._maxPosition; } - - // TODO - // updateData () { - // // store the data - // if (this._persist) { - // if (this._data) { - // this._data.set(data, offset); - // } else { - // this._data = data; - // } - // } - // } + /** + * The vertex bundles that this mesh owns. + */ + @property + public _vertexBundles: IVertexBundle[] = []; /** - * @return {ArrayBuffer} + * The primitives that this mesh owns. */ - public _getBuffer () { - return this._data.buffer; + public _primitives: IPrimitive[] = []; + + /** + * The min position of this mesh's vertices. + */ + @property(Vec3) + public _minPosition: Vec3 = new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + + /** + * The max position of this mesh's vertices. + */ + @property(Vec3) + public _maxPosition: Vec3 = new Vec3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + + private _data: Uint8Array | null = null; + + private _initialized = false; + + private _subMeshes: Array = []; + + private _vertexBuffers: GFXBuffer[] = []; + + private _indexBuffers: GFXBuffer[] = []; + + constructor () { + super(); } - public _getIndexUnitSize (indexUnit) { - switch (indexUnit) { - case gfxEnums.INDEX_FMT_UINT8: - return 1; - case gfxEnums.INDEX_FMT_UINT16: - return 2; - case gfxEnums.INDEX_FMT_UINT32: - return 3; + /** + * Destory this mesh and immediately release its video memory. + */ + public destroy () { + this._vertexBuffers.forEach((vertexBuffer) => { + vertexBuffer.destroy(); + }); + this._vertexBuffers.length = 0; + + this._indexBuffers.forEach((indexBuffer) => { + indexBuffer.destroy(); + }); + this._indexBuffers.length = 0; + + this._subMeshes.forEach((subMesh) => { + if (subMesh) { + subMesh.destroy(); + } + }); + this._subMeshes.length = 0; + + this._initialized = false; + + return super.destroy(); + } + + /** + * !#en + * Gets the specified submesh. + * @param {number} index Index of the specified submesh. + */ + public getSubMesh (index) { + this._lazyInitRenderResources(); + return this._subMeshes![index]; + } + + /** + * + */ + private _lazyInitRenderResources () { + if (this._initialized) { + return; } - return 1; + + this._initialized = true; + + if (this._data === null) { + return; + } + + const buffer = this._data.buffer; + + const gfxDevice = cc.director.root.device as GFXDevice; + + this._createVertexBuffers(gfxDevice, buffer); + + const submeshes = this._primitives.map((primitive) => { + if (primitive.vertexBundelIndices.length === 0) { + return null; + } + + const indexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.INDEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: primitive.indices.length, + stride: getIndexUnitStride(primitive.indexUnit), + }); + + if (!indexBuffer) { + return null; + } + + indexBuffer.update(buffer, primitive.indices.offset, primitive.indices.length); + + const gfxAttributes: IGFXInputAttribute[] = []; + primitive.vertexBundelIndices.forEach((iVertexBundle) => { + const vertexBundle = this._vertexBundles[iVertexBundle]; + vertexBundle.attributes.forEach((attribute) => { + const gfxAttribute: IGFXInputAttribute = { + name: attribute.name, + format: toGfxAttributeType(attribute), + stream: iVertexBundle, + }; + if ('normalize' in attribute) { + gfxAttribute.isNormalized = attribute.normalize; + } + gfxAttributes.push(gfxAttribute); + }); + }); + + const referedVertexBuffers = primitive.vertexBundelIndices.map( + (i) => this._vertexBuffers[i]); + + return gfxDevice.createInputAssembler({ + attributes: gfxAttributes, + vertexBuffers: referedVertexBuffers, + indexBuffer, + }); + }); + + this._subMeshes = submeshes; + } + + private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer) { + let nullish = false; + + const vertexBuffers = this._vertexBundles.map((vertexBundle) => { + const vertexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.VERTEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: vertexBundle.data.length, + stride: vertexBundle.data.length / vertexBundle.verticesCount, + }); + + if (!vertexBuffer) { + nullish = true; + return null; + } + + vertexBuffer.update(new Uint8Array(data, vertexBundle.data.offset, vertexBundle.data.length)); + return vertexBuffer; + }); + + if (!nullish) { + this._vertexBuffers = vertexBuffers as GFXBuffer[]; + } else { + vertexBuffers.forEach((vertexBuffer) => { + if (vertexBuffer) { + vertexBuffer.destroy(); + } + }); + } + + return !nullish; } } cc.Mesh = Mesh; diff --git a/cocos/3d/assets/utils/buffer-range.ts b/cocos/3d/assets/utils/buffer-range.ts index fdd98c48f9..25f2f386ed 100644 --- a/cocos/3d/assets/utils/buffer-range.ts +++ b/cocos/3d/assets/utils/buffer-range.ts @@ -23,33 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -// @ts-check -import { _decorator } from '../../../core/data'; -const { ccclass, property } = _decorator; - -/** - * The class BufferRange denotes a range of the buffer. - */ -@ccclass('cc.BufferRange') -export default class BufferRange { - /** - * The offset of the range. - * @type {Number} - */ - @property(Number) - public _offset = 0; - - /** - * The length of the range, in bytes. - * @type {Number} - */ - @property(Number) - public _length = 0; - - constructor (offset, length) { - this._offset = offset; - this._length = length; - } +export interface IBufferRange { + offset: number; + length: number; } - -cc.BufferRange = BufferRange; From 934bc477139b5bb93d787b984ad58039912b29ab Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 16:55:27 +0800 Subject: [PATCH 093/267] topology --- cocos/3d/assets/mesh.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 5aab6e00d5..090b2dd4c9 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -30,7 +30,7 @@ const { ccclass, property } = _decorator; import { Asset } from '../../assets/asset'; import { Vec3 } from '../../core/value-types'; import { GFXBuffer } from '../../gfx/buffer'; -import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; import { IBufferRange } from './utils/buffer-range'; @@ -102,21 +102,25 @@ export enum Topology { /** * Point list. */ - POINT_LIST, + POINT_LIST = GFXPrimitiveMode.POINT_LIST, /** * Line list. */ - LINE_LIST, + LINE_LIST = GFXPrimitiveMode.LINE_LIST, /** * Triangle list. */ - TRIANGLE_LIST, + TRIANGLE_LIST = GFXPrimitiveMode.TRIANGLE_LIST, } ccenum(Topology); +function toGFXTopology (topology: Topology) { + return topology as unknown as GFXPrimitiveMode; +} + export enum IndexUnit { /** * 8 bits unsigned integer. @@ -167,7 +171,7 @@ export interface IVertexAttribute { normalize: boolean; } -function toGfxAttributeType (vertexAttribute: IVertexAttribute) { +function toGFXAttributeType (vertexAttribute: IVertexAttribute) { let formatName = ''; switch (vertexAttribute.type) { case AttributeType.SCALAR: @@ -358,6 +362,10 @@ export default class Mesh extends Asset { return this._subMeshes![index]; } + public getGFXPrimitiveMode (index: number) { + return toGFXTopology(this._primitives[index].topology); + } + /** * */ @@ -402,7 +410,7 @@ export default class Mesh extends Asset { vertexBundle.attributes.forEach((attribute) => { const gfxAttribute: IGFXInputAttribute = { name: attribute.name, - format: toGfxAttributeType(attribute), + format: toGFXAttributeType(attribute), stream: iVertexBundle, }; if ('normalize' in attribute) { From 2cf99a2ad171fd236b97ad9f8cf8df1176a818ba Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 17:43:31 +0800 Subject: [PATCH 094/267] restruct mesh.ts --- cocos/3d/assets/mesh.ts | 160 +++++++++++++++++++--------------- cocos/3d/misc/utils.js | 6 +- cocos/3d/primitive/box.ts | 2 +- cocos/3d/primitive/defines.ts | 2 +- 4 files changed, 94 insertions(+), 76 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 090b2dd4c9..3fb1a594b0 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -263,6 +263,47 @@ export interface IPrimitive { topology: Topology; } +export interface IRenderingSubmesh { + inputAssembler: GFXInputAssembler; + primitiveMode: GFXPrimitiveMode; +} + +export class RenderingMesh { + public constructor ( + private _subMeshes: Array, + private _vertexBuffers: GFXBuffer[], + private _indexBuffers: GFXBuffer[]) { + + } + + public get subMeshCount () { + return this._subMeshes.length; + } + + public getSubmesh (index: number) { + return this._subMeshes[index]; + } + + public destroy () { + this._vertexBuffers.forEach((vertexBuffer) => { + vertexBuffer.destroy(); + }); + this._vertexBuffers.length = 0; + + this._indexBuffers.forEach((indexBuffer) => { + indexBuffer.destroy(); + }); + this._indexBuffers.length = 0; + + this._subMeshes.forEach((subMesh) => { + if (subMesh) { + subMesh.inputAssembler.destroy(); + } + }); + this._subMeshes.length = 0; + } +} + @ccclass('cc.Mesh') export default class Mesh extends Asset { @@ -276,19 +317,27 @@ export default class Mesh extends Asset { /** * Submeshes count of this mesh. + * @deprecated Use this.renderingMesh.subMeshCount instead. */ get subMeshCount () { - this._lazyInitRenderResources(); - return this._subMeshes!.length; + const renderingMesh = this.renderingMesh; + return renderingMesh ? renderingMesh.subMeshCount : 0; } + /** + * Min position of this mesh. + */ get minPosition () { return this._minPosition; } + /** + * Max position of this mesh. + */ get maxPosition () { return this._maxPosition; } + /** * The vertex bundles that this mesh owns. */ @@ -298,6 +347,7 @@ export default class Mesh extends Asset { /** * The primitives that this mesh owns. */ + @property public _primitives: IPrimitive[] = []; /** @@ -316,11 +366,7 @@ export default class Mesh extends Asset { private _initialized = false; - private _subMeshes: Array = []; - - private _vertexBuffers: GFXBuffer[] = []; - - private _indexBuffers: GFXBuffer[] = []; + private _renderingMesh: RenderingMesh | null = null; constructor () { super(); @@ -330,45 +376,33 @@ export default class Mesh extends Asset { * Destory this mesh and immediately release its video memory. */ public destroy () { - this._vertexBuffers.forEach((vertexBuffer) => { - vertexBuffer.destroy(); - }); - this._vertexBuffers.length = 0; - - this._indexBuffers.forEach((indexBuffer) => { - indexBuffer.destroy(); - }); - this._indexBuffers.length = 0; - - this._subMeshes.forEach((subMesh) => { - if (subMesh) { - subMesh.destroy(); - } - }); - this._subMeshes.length = 0; - - this._initialized = false; - + if (this._renderingMesh) { + this._renderingMesh.destroy(); + this._renderingMesh = null; + this._initialized = false; + } return super.destroy(); } + /** + * Gets the rendering mesh. + */ + public get renderingMesh () { + this._lazyInitRenderResources(); + return this._renderingMesh; + } + /** * !#en * Gets the specified submesh. - * @param {number} index Index of the specified submesh. + * @param index Index of the specified submesh. + * @deprecated Using this.renderingMesh() instead. */ - public getSubMesh (index) { - this._lazyInitRenderResources(); - return this._subMeshes![index]; + public getSubMesh (index: number) { + const renderingMesh = this.renderingMesh; + return renderingMesh ? renderingMesh.getSubmesh(index) : null; } - public getGFXPrimitiveMode (index: number) { - return toGFXTopology(this._primitives[index].topology); - } - - /** - * - */ private _lazyInitRenderResources () { if (this._initialized) { return; @@ -384,9 +418,11 @@ export default class Mesh extends Asset { const gfxDevice = cc.director.root.device as GFXDevice; - this._createVertexBuffers(gfxDevice, buffer); + const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer); - const submeshes = this._primitives.map((primitive) => { + const indexBuffers: GFXBuffer[] = []; + + const renderingSubmeshes = this._primitives.map((primitive) => { if (primitive.vertexBundelIndices.length === 0) { return null; } @@ -397,10 +433,7 @@ export default class Mesh extends Asset { size: primitive.indices.length, stride: getIndexUnitStride(primitive.indexUnit), }); - - if (!indexBuffer) { - return null; - } + indexBuffers.push(indexBuffer); indexBuffer.update(buffer, primitive.indices.offset, primitive.indices.length); @@ -421,49 +454,32 @@ export default class Mesh extends Asset { }); const referedVertexBuffers = primitive.vertexBundelIndices.map( - (i) => this._vertexBuffers[i]); + (i) => vertexBuffers[i]); - return gfxDevice.createInputAssembler({ - attributes: gfxAttributes, - vertexBuffers: referedVertexBuffers, - indexBuffer, - }); + return { + primitiveMode: toGFXTopology(primitive.topology), + inputAssembler: gfxDevice.createInputAssembler({ + attributes: gfxAttributes, + vertexBuffers: referedVertexBuffers, + indexBuffer, + }), + } as IRenderingSubmesh ; }); - this._subMeshes = submeshes; + this._renderingMesh = new RenderingMesh(renderingSubmeshes, vertexBuffers, indexBuffers); } - private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer) { - let nullish = false; - - const vertexBuffers = this._vertexBundles.map((vertexBundle) => { + private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer): GFXBuffer[] { + return this._vertexBundles.map((vertexBundle) => { const vertexBuffer = gfxDevice.createBuffer({ usage: GFXBufferUsageBit.VERTEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: vertexBundle.data.length, stride: vertexBundle.data.length / vertexBundle.verticesCount, }); - - if (!vertexBuffer) { - nullish = true; - return null; - } - vertexBuffer.update(new Uint8Array(data, vertexBundle.data.offset, vertexBundle.data.length)); return vertexBuffer; }); - - if (!nullish) { - this._vertexBuffers = vertexBuffers as GFXBuffer[]; - } else { - vertexBuffers.forEach((vertexBuffer) => { - if (vertexBuffer) { - vertexBuffer.destroy(); - } - }); - } - - return !nullish; } } cc.Mesh = Mesh; diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js index f4f7bde08a..b9b9f948d5 100644 --- a/cocos/3d/misc/utils.js +++ b/cocos/3d/misc/utils.js @@ -1,7 +1,8 @@ import { renderer } from '../../renderer'; import find from '../../scene-graph/find'; -import Mesh from '../assets/mesh'; +import Mesh, { RenderingMesh } from '../assets/mesh'; import gfx from '../../renderer/gfx/index'; +import { GFXPrimitiveMode } from '../../gfx/define'; /** * @@ -44,7 +45,8 @@ function createJointsTexture(skinning) { function createMesh(context, data) { let ia = renderer.createIA(context, data); let meshAsset = new Mesh(); - meshAsset._subMeshes = [ia]; + const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; + meshAsset._renderingMesh = new RenderingMesh([{inputAssembler: ia, primitiveMode}], [], []); meshAsset._minPosition = data.minPos; meshAsset._maxPosition = data.maxPos; diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts index 7617d64963..8d4661e587 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/3d/primitive/box.ts @@ -131,7 +131,7 @@ export default function box (options: IBoxOptions): IGeometry { _buildPlane(2, ws, ls); // TOP return { - primitiveType: GFXPrimitiveMode.TRIANGLE_LIST, + primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST, positions, normals, uvs, diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts index 145b174f65..c189b4c6d2 100644 --- a/cocos/3d/primitive/defines.ts +++ b/cocos/3d/primitive/defines.ts @@ -17,7 +17,7 @@ export interface IGeometry { /** * Topology of the geometry vertices. */ - primitiveType: GFXPrimitiveMode; + primitiveMode: GFXPrimitiveMode; /** * Vertex positions. From 7d183439677b76b801bfdc4ab053efc66ecad859 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 10 Jan 2019 17:54:48 +0800 Subject: [PATCH 095/267] fix old deprecated api --- cocos/3d/assets/mesh.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 3fb1a594b0..972ef75f88 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -396,11 +396,11 @@ export default class Mesh extends Asset { * !#en * Gets the specified submesh. * @param index Index of the specified submesh. - * @deprecated Using this.renderingMesh() instead. + * @deprecated Using this.renderingMesh.getSubmesh(index)inputAssembler instead. */ public getSubMesh (index: number) { - const renderingMesh = this.renderingMesh; - return renderingMesh ? renderingMesh.getSubmesh(index) : null; + const renderingSubmesh = this.renderingMesh ? this.renderingMesh.getSubmesh(index) : null; + return renderingSubmesh ? renderingSubmesh.inputAssembler : null; } private _lazyInitRenderResources () { From 224c842a8bac2ecaa399fa51ab90aac966301ed2 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Thu, 10 Jan 2019 18:12:21 +0800 Subject: [PATCH 096/267] adapt model to new mesh --- cocos/3d/framework/model-component.js | 3 +-- cocos/renderer/core/pass.ts | 1 + cocos/renderer/scene/model.ts | 17 ++++++++++------- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 9b6807e7fa..b461facd97 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -214,9 +214,8 @@ export default class ModelComponent extends RenderableComponent { for (let i = 0; i < this._models.length; ++i) { let model = this._models[i]; let material = this.getSharedMaterial(i); - let inputAssembler = this._mesh.getSubMesh(i); - model.inputAssembler = inputAssembler; + model.subMeshData = this._mesh.renderingMesh.getSubmesh(i); model.node = this.node; this._updateModelMaterial(model, material); } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 9c45f15f9a..691f276973 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -258,4 +258,5 @@ export class Pass { get programName () { return this._programName; } get pipelineState () { return this._pipelineState as GFXPipelineState; } get bindingLayout () { return this._bindingLayout as GFXBindingLayout; } + get primitive(): GFXPrimitiveMode { return this._primitive; } } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 3f53faf4c1..252f28b80e 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -12,6 +12,7 @@ import { Node } from '../../scene-graph'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; import { RenderScene } from './render-scene'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; const _temp_floatx16 = new Float32Array(16); const _temp_mat4 = mat4.create(); @@ -27,7 +28,7 @@ export default class Model { private _poolID: number; private _isEnable: boolean; private _node: Node; - private _inputAssembler: GFXInputAssembler | null; + private _subMeshObject: IRenderingSubmesh | null; private _effect: Effect | null; private _defines: Object; private _dependencies: Object; @@ -52,7 +53,7 @@ export default class Model { this._poolID = -1; this._isEnable = true; this._node = null; - this._inputAssembler = null; + this._subMeshObject = null; this._effect = null; this._defines = {}; this._dependencies = {}; @@ -157,8 +158,8 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - set inputAssembler (ia: GFXInputAssembler) { - this._inputAssembler = ia; + set subMeshData(sm: IRenderingSubmesh) { + this._subMeshObject = sm; } get boundingShape (): aabb { @@ -185,9 +186,11 @@ export default class Model { } } - set material (material: Material) { + set material(material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { + if (this._material.passes[i].primitive !== (this._subMeshObject as IRenderingSubmesh).primitiveMode) + cc.error('the model(%d)\'s primitive type doesn\'t match its pass\'s'); this.recordCommandBuffer(i); } for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { @@ -214,8 +217,8 @@ export default class Model { this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); - this._cmdBuffers[index].bindInputAssembler(this._inputAssembler as GFXInputAssembler); - this._cmdBuffers[index].draw(this._inputAssembler as GFXInputAssembler); + this._cmdBuffers[index].bindInputAssembler((this._subMeshObject as IRenderingSubmesh).inputAssembler); + this._cmdBuffers[index].draw((this._subMeshObject as IRenderingSubmesh).inputAssembler); this._cmdBuffers[index].end(); } From a71c1ba5eb6c0e7e99a6cc09e063398c49ecdbd2 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 18:20:37 +0800 Subject: [PATCH 097/267] commit modified files --- cocos/pipeline/forward/forward-flow.ts | 3 --- cocos/pipeline/forward/forward-stage.ts | 7 +++++-- cocos/pipeline/forward/test-material-stage.ts | 9 +++++--- cocos/pipeline/forward/test-model-stage.ts | 7 +++++-- cocos/pipeline/forward/test-stage.ts | 10 ++++++--- cocos/pipeline/render-flow.ts | 3 ++- cocos/pipeline/render-stage.ts | 1 + cocos/pipeline/render-view.ts | 21 ------------------- cocos/renderer/scene/camera.ts | 9 ++++++++ playground/simple.html | 2 -- 10 files changed, 35 insertions(+), 37 deletions(-) diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index b4a29558dc..bc92cf1096 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,10 +1,7 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { RenderPipeline } from '../render-pipeline'; -import { ForwardStage } from './forward-stage'; // import { TestStage } from "./test-stage"; -import { TestMaterialStage } from './test-material-stage'; import { TestModelStage } from './test-model-stage'; -import { TestStage } from './test-stage'; export enum ForwardStagePriority { FORWARD = 0, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 195e1bb045..263fbed8d9 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -1,6 +1,7 @@ import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXCommandBufferType } 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'; @@ -41,8 +42,10 @@ export class ForwardStage extends RenderStage { const cmdBuff = this._cmdBuff as GFXCommandBuffer; const queue = this._pipeline.queue; - this._renderArea.width = view.width; - this._renderArea.height = view.height; + 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); diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/forward/test-material-stage.ts index 7627dac090..93aed934bc 100644 --- a/cocos/pipeline/forward/test-material-stage.ts +++ b/cocos/pipeline/forward/test-material-stage.ts @@ -5,8 +5,9 @@ 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 { RenderStage, IRenderStageInfo } from '../render-stage'; +import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; export class TestMaterialStage extends RenderStage { @@ -84,9 +85,11 @@ export class TestMaterialStage extends RenderStage { mtl.inited = true; } + const camera = view.camera as Camera; + const cmdBuff = this._cmdBuff as GFXCommandBuffer; - this._renderArea.width = view.width; - this._renderArea.height = view.height; + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; cmdBuff.begin(); cmdBuff.beginRenderPass( this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts index 218111fd7b..f4119759c1 100644 --- a/cocos/pipeline/forward/test-model-stage.ts +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -4,6 +4,7 @@ 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'; @@ -92,9 +93,11 @@ export class TestModelStage extends RenderStage { this._init = true; } + const camera = view.camera as Camera; + const cmdBuff = this._cmdBuff as GFXCommandBuffer; - this._renderArea.width = view.width; - this._renderArea.height = view.height; + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; this._model._updateTransform(); this._model.updateRenderData(); cmdBuff.begin(); diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/forward/test-stage.ts index 4e0744bda0..1a28677ccc 100644 --- a/cocos/pipeline/forward/test-stage.ts +++ b/cocos/pipeline/forward/test-stage.ts @@ -10,9 +10,10 @@ 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 { RenderStage, IRenderStageInfo } from '../render-stage'; +import { IRenderStageInfo, RenderStage } from '../render-stage'; import { RenderView } from '../render-view'; /* @@ -235,8 +236,11 @@ export class TestStage extends RenderStage { public render (view: RenderView) { const cmdBuff = this._cmdBuff as GFXCommandBuffer; - this._renderArea.width = view.width; - this._renderArea.height = view.height; + + 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); diff --git a/cocos/pipeline/render-flow.ts b/cocos/pipeline/render-flow.ts index e7377b1e29..52c2a836ad 100644 --- a/cocos/pipeline/render-flow.ts +++ b/cocos/pipeline/render-flow.ts @@ -1,6 +1,7 @@ import { GFXDevice } from '../gfx/device'; +import { Camera } from '../renderer/scene/camera'; import { RenderPipeline } from './render-pipeline'; -import { RenderStage, IRenderStageInfo } from './render-stage'; +import { IRenderStageInfo, RenderStage } from './render-stage'; import { RenderView } from './render-view'; export interface IRenderFlowInfo { diff --git a/cocos/pipeline/render-stage.ts b/cocos/pipeline/render-stage.ts index 2f4a56b7ee..0712d9eac1 100644 --- a/cocos/pipeline/render-stage.ts +++ b/cocos/pipeline/render-stage.ts @@ -2,6 +2,7 @@ import { GFXCommandBuffer } from '../gfx/command-buffer'; import { IGFXColor, IGFXRect } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; import { GFXFramebuffer } from '../gfx/framebuffer'; +import { Camera } from '../renderer/scene/camera'; import { RenderFlow } from './render-flow'; import { RenderPipeline } from './render-pipeline'; import { RenderView } from './render-view'; diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index daaf6db898..58b3a34b91 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -11,8 +11,6 @@ export interface IRenderViewInfo { name: string; window: GFXWindow; priority: number; - width: number; - height: number; } export class RenderView { @@ -36,14 +34,6 @@ export class RenderView { return this._visiblity; } - public get width (): number { - return this._width; - } - - public get height (): number { - return this._height; - } - public get camera (): Camera { return this._camera as Camera; } @@ -61,8 +51,6 @@ export class RenderView { private _window: GFXWindow | null = null; private _priority: number = 0; private _visiblity: number = 0; - private _width: number = 0; - private _height: number = 0; private _scene: RenderScene | null = null; private _camera: Camera | null = null; private _isAttached: boolean = false; @@ -79,16 +67,9 @@ export class RenderView { return false; } - if (info.width <= 0 || info.height <= 0) { - console.error('RenderView size is an error size.'); - return false; - } - this._name = info.name; this._window = info.window; this._priority = info.priority; - this._width = info.width; - this._height = info.height; return true; } @@ -96,8 +77,6 @@ export class RenderView { public destroy () { this._window = null; this._priority = 0; - this._width = 0; - this._height = 0; } public resize (width, height) { diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index d78252b389..7657bf1c95 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -46,6 +46,7 @@ export class Camera { private _rotation: quat = new quat(); private _direction: vec3 = new vec3(); private _frustum: frustum = new frustum(); + private _visibility: number; constructor (scene: RenderScene, name: string) { this._scene = scene; @@ -67,6 +68,7 @@ export class Camera { this._fov = Math.PI / 4; this._nearClip = 1.0; this._farClip = 10000.0; + this._visibility = 0; } public resize (width: number, height: number) { @@ -175,6 +177,13 @@ export class Camera { return this._frustum; } + public set visibility (vis: number) { + this._visibility = vis; + } + public get visibility (): number { + return this._visibility; + } + public rotate (rot: quat, ns?: NodeSpace) { const space = (ns !== undefined ? ns : NodeSpace.LOCAL); if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { diff --git a/playground/simple.html b/playground/simple.html index 718538365e..6addcf5b12 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -66,8 +66,6 @@ window: mainWindow, //priority: cc.RenderViewPriority.GENERAL, priority: 100, - width: mainWindow.width, - height: mainWindow.height, }); view.attach(scene.mainCamera); From f099e500c3aaab2afc68e0527e1f2a1f7d5a02a9 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 10 Jan 2019 15:26:27 +0800 Subject: [PATCH 098/267] node & camera refactor --- .eslintrc.json | 17 +- cocos/3d/assets/index.js | 2 +- cocos/3d/assets/mesh.ts | 2 +- cocos/3d/framework/camera-component.js | 89 +-- cocos/3d/framework/model-component.js | 2 +- cocos/3d/framework/physics/body.ts | 2 +- .../3d/framework/skinning-model-component.js | 2 +- cocos/3d/geom-utils/frustum.ts | 102 ++- cocos/3d/misc/utils.js | 2 +- cocos/components/component.d.ts | 6 +- cocos/components/component.js | 2 +- cocos/core/data/object.d.ts | 3 +- cocos/core/value-types/color.js | 10 +- cocos/core/vmath/color4.ts | 79 +-- cocos/core/vmath/quat.ts | 15 +- cocos/core/vmath/vec2.ts | 3 + cocos/core/vmath/vec3.ts | 12 +- cocos/core/vmath/vec4.ts | 3 + cocos/gfx/define.ts | 7 + cocos/pipeline/render-pipeline.ts | 2 +- cocos/renderer/scene/camera.ts | 300 ++++----- cocos/renderer/scene/render-scene.ts | 2 +- cocos/renderer/scene/scene.js | 2 +- cocos/scene-graph/base-node.d.ts | 77 +++ cocos/scene-graph/base-node.js | 2 +- cocos/scene-graph/index.js | 6 +- cocos/scene-graph/{layers.js => layers.ts} | 48 +- cocos/scene-graph/node-2d.js | 54 +- cocos/scene-graph/node.js | 502 --------------- cocos/scene-graph/node.ts | 591 ++++++++++++++++++ cocos/scene-graph/private-node.js | 4 +- cocos/scene-graph/scene.js | 5 +- 32 files changed, 1003 insertions(+), 952 deletions(-) create mode 100644 cocos/scene-graph/base-node.d.ts rename cocos/scene-graph/{layers.js => layers.ts} (50%) delete mode 100644 cocos/scene-graph/node.js create mode 100644 cocos/scene-graph/node.ts diff --git a/.eslintrc.json b/.eslintrc.json index 705297c9a8..f53f8b7076 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -23,19 +23,20 @@ "globals": { "cc": false, "wx": false, - "CC_EDITOR": false, - "CC_DEV": false, - "CC_JSB": false, - "CC_PREVIEW": false, - "CC_DEBUG": false, "CC_BUILD": false, + "CC_TEST": false, + "CC_EDITOR": false, + "CC_PREVIEW": false, + "CC_DEV": false, + "CC_DEBUG": false, + "CC_JSB": false, + "CC_WECHATGAME_SUB": false, "CC_WECHATGAME": false, "CC_QQPLAY": false, "CC_RUNTIME": false, "CC_SUPPORT_JIT": false, - "CC_PREVIEW": false, - "CC_PREVIEW": false, - "CC_PREVIEW": false, + "Editor": false, + "_Scene": false, "_ccsg": false } } diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js index 6df8f5d3d3..4cc366051f 100644 --- a/cocos/3d/assets/index.js +++ b/cocos/3d/assets/index.js @@ -29,7 +29,7 @@ export { DOMAudioClip } from "./dom-audio-clip"; export { BitmapFont } from "./bitmap-font"; export { EffectAsset } from "./effect-asset"; export { Material } from "./material"; -export { default as Mesh } from "./mesh"; +export { Mesh } from "./mesh"; export { default as OpentypeFont } from "./opentype-font"; export { default as Skeleton } from "./skeleton"; export { default as Sprite } from "./sprite"; diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 972ef75f88..5ba28687e9 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -305,7 +305,7 @@ export class RenderingMesh { } @ccclass('cc.Mesh') -export default class Mesh extends Asset { +export class Mesh extends Asset { get _nativeAsset () { return this._data; diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.js index b556cb3904..cf58a3a0c4 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.js @@ -23,13 +23,12 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import RenderSystemActor from './renderSystemActor'; -import { renderer } from '../../renderer/index'; -import { toRadian } from '../../core/vmath'; +import { toRadian, color4 } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; -import { Color, Enum, Rect } from '../../core/value-types'; -import enums from '../../renderer/enums'; +import { Enum, Rect } from '../../core/value-types'; import { Component } from '../../components/component'; +import { CameraProjection } from '../../renderer/scene/camera'; +import { GFXClearFlag } from '../../gfx/define'; /** * @typedef {import('../../core/value-types/index').Color} Color @@ -42,7 +41,7 @@ import { Component } from '../../components/component'; * @static * @enum CameraComponent.Projection */ -let CameraProjection = Enum({ +let ProjectionType = Enum({ /** * !#en The orthogonal camera * @@ -64,9 +63,9 @@ let CameraProjection = Enum({ }); let CameraClearFlag = Enum({ - SKYBOX: enums.CLEAR_SKYBOX | enums.CLEAR_DEPTH | enums.CLEAR_STENCIL, - SOLID_COLOR: enums.CLEAR_COLOR | enums.CLEAR_DEPTH | enums.CLEAR_STENCIL, - DEPTH_ONLY: enums.CLEAR_DEPTH | enums.CLEAR_STENCIL, + SKYBOX: GFXClearFlag.SKYBOX | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + SOLID_COLOR: GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, + DEPTH_ONLY: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, DONT_CLEAR: 0 }); @@ -82,7 +81,7 @@ let CameraClearFlag = Enum({ @executeInEditMode export default class CameraComponent extends Component { @property - _projection = CameraProjection.PERSPECTIVE; + _projection = ProjectionType.PERSPECTIVE; @property _priority = 0; @@ -121,7 +120,7 @@ export default class CameraComponent extends Component { * @type {Number} */ @property({ - type: CameraProjection + type: ProjectionType }) get projection() { return this._projection; @@ -130,29 +129,11 @@ export default class CameraComponent extends Component { set projection(val) { this._projection = val; - let type = renderer.PROJ_PERSPECTIVE; - if (this._projection === CameraProjection.Ortho) { - type = renderer.PROJ_ORTHO; + let type = CameraProjection.PERSPECTIVE; + if (this._projection === ProjectionType.ORTHO) { + type = CameraProjection.ORTHO; } - if (this.enabled) - this._camera.setType(type); - } - - /** - * !#en The camera priority - * - * !#ch 相机的优先级,优先级低的优先渲染 - * @type {Number} - */ - @property - get priority() { - return this._priority; - } - - set priority(val) { - this._priority = val; - if (this.enabled) - this._camera.setPriority(val); + if (this.enabled) this._camera.projectionType = type; } /** @@ -168,8 +149,7 @@ export default class CameraComponent extends Component { set fov(val) { this._fov = val; - if (this.enabled) - this._camera.setFov(toRadian(val)); + if (this.enabled) this._camera.fov = toRadian(val); } /** @@ -185,8 +165,7 @@ export default class CameraComponent extends Component { set orthoHeight(val) { this._orthoHeight = val; - if (this.enabled) - this._camera.setOrthoHeight(val); + if (this.enabled) this._camera.orthoHeight = val; } /** @@ -202,8 +181,7 @@ export default class CameraComponent extends Component { set near(val) { this._near = val; - if (this.enabled) - this._camera.setNear(val); + if (this.enabled) this._camera.nearClip =val; } /** @@ -219,8 +197,7 @@ export default class CameraComponent extends Component { set far(val) { this._far = val; - if (this.enabled) - this._camera.setFar(val); + if (this.enabled) this._camera.farClip = val; } /** @@ -236,8 +213,8 @@ export default class CameraComponent extends Component { set color(val) { this._color = val; - if (this.enabled) - this._camera.setColor(val.r / 255, val.g / 255, val.b / 255, val.a / 255); + if (this.enabled) this._camera.clearColor = + color4.create(val.r / 255, val.g / 255, val.b / 255, val.a / 255); } /** @@ -254,7 +231,7 @@ export default class CameraComponent extends Component { set depth(val) { this._depth = val; if (this.enabled) - this._camera.setDepth(val); + this._camera.clearDepth = val; } /** @@ -270,8 +247,7 @@ export default class CameraComponent extends Component { set stencil(val) { this._stencil = val; - if (this.enabled) - this._camera.setStencil(val); + if (this.enabled) this._camera.clearStencil = val; } /** @@ -289,8 +265,7 @@ export default class CameraComponent extends Component { set clearFlags(val) { this._clearFlags = val; - if (this.enabled) - this._camera.setClearFlags(val); + if (this.enabled) this._camera.clearFlag = val; } /** @@ -306,8 +281,7 @@ export default class CameraComponent extends Component { set rect(val) { this._rect = val; - if (this.enabled) - this._camera.setRect(val.x, val.y, val.width, val.height); + if (this.enabled) this._camera.viewport = val; } static Projection = CameraProjection; @@ -333,8 +307,7 @@ export default class CameraComponent extends Component { this.stencil = this._stencil; this.clearFlags = this._clearFlags; this.rect = this._rect; - this._camera.setStages(renderer.PassStage.DEFAULT | renderer.PassStage.FORWARD); - this._camera.setNode(this.node); + this._camera.node = this.node; } onDisable() { @@ -344,16 +317,4 @@ export default class CameraComponent extends Component { onDestroy() { } - - /** - * transform a screen position to world space - * @param out the resulting vector - * @param screenPos the screen position to be transformed - * @param width framebuffer width - * @param height framebuffer height - * @returns the resulting vector - */ - screenToWorld(out, screenPos, width, height) { - return this._camera.screenToWorld(out, screenPos, width, height); - } } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index b461facd97..02ddc06c4e 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -25,7 +25,7 @@ // @ts-check import Model from '../../renderer/scene/model'; import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator'; -import Mesh from '../assets/mesh'; +import { Mesh } from '../assets/mesh'; import Enum from '../../core/value-types/enum'; import RenderableComponent from './renderable-component'; /** diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts index f183d680f9..1f9a8c63aa 100644 --- a/cocos/3d/framework/physics/body.ts +++ b/cocos/3d/framework/physics/body.ts @@ -1,7 +1,7 @@ import CANNON from 'cannon'; import Vec3 from '../../../core/value-types/vec3'; import { vec3 } from '../../../core/vmath'; -import Node from '../../../scene-graph/node'; +import { Node } from '../../../scene-graph/node'; import { PhysicsMaterial as PhysicsMaterial } from '../../assets/physics/material'; import { setWrap, getWrap } from './util'; import { Quat } from '../../../core/value-types'; diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js index c3c9349a69..c170eb5617 100644 --- a/cocos/3d/framework/skinning-model-component.js +++ b/cocos/3d/framework/skinning-model-component.js @@ -30,7 +30,7 @@ import { renderer } from '../../renderer/index'; import { ccclass, property, executionOrder, menu,executeInEditMode } from '../../core/data/class-decorator'; import utils from '../misc/utils'; import Skeleton from '../assets/skeleton'; -import Node from '../../scene-graph/node'; +import { Node } from '../../scene-graph/node'; /** * @typedef {import("../framework/skeleton-instance").default} SkeletonInstance diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/3d/geom-utils/frustum.ts index 9f7caa9f8a..26330d9e37 100644 --- a/cocos/3d/geom-utils/frustum.ts +++ b/cocos/3d/geom-utils/frustum.ts @@ -1,8 +1,8 @@ +import { mat4, vec3 } from '../../core/vmath'; import enums from './enums'; import plane from './plane'; -import { vec3, mat4 } from '../../core/vmath'; -let _v = new Array(8); +const _v = new Array(8); _v[0] = vec3.create(1, 1, 1); _v[1] = vec3.create(-1, 1, 1); _v[2] = vec3.create(-1, -1, 1); @@ -12,13 +12,51 @@ _v[5] = vec3.create(-1, 1, -1); _v[6] = vec3.create(-1, -1, -1); _v[7] = vec3.create(1, -1, -1); +// tslint:disable-next-line: class-name export class frustum { + /** + * Set whether to use accurate intersection testing function on this frustum + */ + set accurate (b: boolean) { + this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; + } + + /** + * create a new frustum + * + * @return {frustum} + */ + public static create () { + return new frustum(); + } + + /** + * Clone a frustum + */ + public static clone (f: frustum): frustum { + return frustum.copy(new frustum(), f); + } + + /** + * Copy the values from one frustum to another + */ + public static copy (out: frustum, f: frustum): frustum { + out._type = f._type; + for (let i = 0; i < 6; ++i) { + plane.copy(out.planes[i], f.planes[i]); + } + for (let i = 0; i < 8; ++i) { + vec3.copy(out.vertices[i], f.vertices[i]); + } + return out; + } + public planes: plane[]; public vertices: vec3[]; private _type: number; - constructor() { + constructor () { this._type = enums.SHAPE_FRUSTUM; this.planes = new Array(6); for (let i = 0; i < 6; ++i) { @@ -30,52 +68,6 @@ export class frustum { } } - /** - * create a new frustum - * - * @return {frustum} - */ - static create() { - return new frustum(); - } - - /** - * Clone a frustum - * - * @param {frustum} f frustum to clone - * @return {frustum} the new frustum - */ - static clone(f: frustum) { - return frustum.copy(new frustum(), f); - } - - /** - * Copy the values from one frustum to another - * - * @param {frustum} out the receiving frustum - * @param {frustum} f the source frustum - * @return {frustum} - */ - static copy(out, f) { - out._type = f._type; - for (let i = 0; i < 6; ++i) { - plane.copy(out.planes[i], f.planes[i]); - } - for (let i = 0; i < 8; ++i) { - vec3.copy(out.vertices[i], f.vertices[i]); - } - return out; - } - - /** - * Set whether to use accurate intersection testing function on this frustum - * - * @param {boolean} b - */ - set accurate(b) { - this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; - } - /** * Update the frustum information according to the given transform matrix. * Note that the resulting planes are not normalized under normal mode. @@ -83,7 +75,7 @@ export class frustum { * @param {mat4} m the view-projection matrix * @param {mat4} inv the inverse view-projection matrix */ - update(m: mat4, inv: mat4) { + public update (m: mat4, inv: mat4) { // RTR4, ch. 22.14.1, p. 983 // extract frustum planes from view-proj matrix. @@ -106,14 +98,14 @@ export class frustum { vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10); this.planes[5].d = -(m.m15 - m.m14); - if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) return; + if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) { return; } // normalize planes for (let i = 0; i < 6; i++) { - let plane = this.planes[i]; - let invDist = 1 / vec3.magnitude(plane.n); - vec3.scale(plane.n, plane.n, invDist); - plane.d *= invDist; + const pl = this.planes[i]; + const invDist = 1 / vec3.magnitude(pl.n); + vec3.scale(pl.n, pl.n, invDist); + pl.d *= invDist; } // update frustum vertices diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js index b9b9f948d5..d74cafab42 100644 --- a/cocos/3d/misc/utils.js +++ b/cocos/3d/misc/utils.js @@ -1,6 +1,6 @@ import { renderer } from '../../renderer'; import find from '../../scene-graph/find'; -import Mesh, { RenderingMesh } from '../assets/mesh'; +import { Mesh, RenderingMesh } from '../assets/mesh'; import gfx from '../../renderer/gfx/index'; import { GFXPrimitiveMode } from '../../gfx/define'; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index 1deb53422d..873270c9e4 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -28,7 +28,7 @@ import { CCObject } from '../core/data/object'; import { getClassName, value } from '../core/utils/js'; import IDGenerator from '../core/utils/id-generator'; import { ccclass, property } from '../core/data/class-decorator'; -import Node from '../scene-graph/node'; +import { Node } from '../scene-graph/node'; import { RenderScene } from '../renderer/scene/render-scene'; export class Component extends CCObject { @@ -37,7 +37,9 @@ export class Component extends CCObject { enabled: boolean; enabledInHierarchy: boolean; - getRenderScene(index?: number): RenderScene | undefined; + public constructor(); + + _getRenderScene(index?: number): RenderScene | undefined; addComponent(typeOrClassName: Function | string): Component; getComponent(typeOrClassName: Function | string): Component; getComponents(typeOrClassName: Function | string): Component[]; diff --git a/cocos/components/component.js b/cocos/components/component.js index 6370572336..a4cbd179ee 100644 --- a/cocos/components/component.js +++ b/cocos/components/component.js @@ -105,7 +105,7 @@ class Component extends CCObject { type: cc._Script, tooltip: CC_DEV && 'i18n:INSPECTOR.component.script' }) - get __scriptAsset () {} + get __scriptAsset () { return null; } //set __scriptAsset (value) { // if (this.__scriptUuid !== value) { // if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) { diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts index 5d70237897..463c47b429 100644 --- a/cocos/core/data/object.d.ts +++ b/cocos/core/data/object.d.ts @@ -24,10 +24,11 @@ ****************************************************************************/ export class CCObject { + protected static _deferredDestroy(): void; protected _name: string; protected _objFlags: number; - static _deferredDestroy(): void; + public constructor(name: string); public name: string; public isValid: boolean; diff --git a/cocos/core/value-types/color.js b/cocos/core/value-types/color.js index 3594466bf7..76b09bb909 100644 --- a/cocos/core/value-types/color.js +++ b/cocos/core/value-types/color.js @@ -570,10 +570,10 @@ CCClass.fastDefine('cc.Color', Color, {r: 0, g: 0, b: 0, a: 255}); * Alpha 通道是可选的。默认值是 255。 * * @method color - * @param {Number} [r=0] - * @param {Number} [g=0] - * @param {Number} [b=0] - * @param {Number} [a=255] + * @param {number|string|object} [r=0] + * @param {number} [g=0] + * @param {number} [b=0] + * @param {number} [a=255] * @return {Color} * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCColor/color.js} */ @@ -588,4 +588,4 @@ cc.color = function color (r, g, b, a) { return new Color(r, g, b, a); }; -cc.Color = Color; \ No newline at end of file +cc.Color = Color; diff --git a/cocos/core/vmath/color4.ts b/cocos/core/vmath/color4.ts index 957ca79df7..9438446489 100644 --- a/cocos/core/vmath/color4.ts +++ b/cocos/core/vmath/color4.ts @@ -1,5 +1,8 @@ import { EPSILON } from './utils'; +// tslint:disable: one-variable-per-declaration +// tslint:disable: class-name + /** * Represents a color with red(r), green(g), blue(b) component of that color and * and an extra alpha(a) component indicating how opaque this color is. @@ -25,7 +28,7 @@ class color4 { * @param a - Color to clone. * @return The newly created color. */ - public static clone (a) { + public static clone (a: color4) { return new color4(a.r, a.g, a.b, a.a); } @@ -36,7 +39,7 @@ class color4 { * @param a - The specified color. * @return out. */ - public static copy (out, a) { + public static copy (out: color4, a: color4) { out.r = a.r; out.g = a.g; out.b = a.b; @@ -54,7 +57,7 @@ class color4 { * @param a - Value assigned to a component. * @return out. */ - public static set (out, r, g, b, a) { + public static set (out: color4, r: number, g: number, b: number, a: number) { out.r = r; out.g = g; out.b = b; @@ -70,7 +73,7 @@ class color4 { * @return out. * @function */ - public static fromHex (out, hex) { + public static fromHex (out: color4, hex: number) { const r = ((hex >> 24)) / 255.0; const g = ((hex >> 16) & 0xff) / 255.0; const b = ((hex >> 8) & 0xff) / 255.0; @@ -91,7 +94,7 @@ class color4 { * @param b - The second operand. * @return out. */ - public static add (out, a, b) { + public static add (out: color4, a: color4, b: color4) { out.r = a.r + b.r; out.g = a.g + b.g; out.b = a.b + b.b; @@ -107,7 +110,7 @@ class color4 { * @param b - The b. * @return out. */ - public static subtract (out, a, b) { + public static subtract (out: color4, a: color4, b: color4) { out.r = a.r - b.r; out.g = a.g - b.g; out.b = a.b - b.b; @@ -118,7 +121,7 @@ class color4 { /** * Alias of {@link color4.subtract}. */ - public static sub (out, a, b) { + public static sub (out: color4, a: color4, b: color4) { return color4.subtract(out, a, b); } @@ -130,7 +133,7 @@ class color4 { * @param b - The second operand. * @return out. */ - public static multiply (out, a, b) { + public static multiply (out: color4, a: color4, b: color4) { out.r = a.r * b.r; out.g = a.g * b.g; out.b = a.b * b.b; @@ -141,7 +144,7 @@ class color4 { /** * Alias of {@link color4.multiply}. */ - public static mul (out, a, b) { + public static mul (out: color4, a: color4, b: color4) { return color4.multiply(out, a, b); } @@ -153,7 +156,7 @@ class color4 { * @param b - The second operand. * @return out. */ - public static divide (out, a, b) { + public static divide (out: color4, a: color4, b: color4) { out.r = a.r / b.r; out.g = a.g / b.g; out.b = a.b / b.b; @@ -164,7 +167,7 @@ class color4 { /** * Alias of {@link color4.divide}. */ - public static div (out, a, b) { + public static div (out: color4, a: color4, b: color4) { return color4.divide(out, a, b); } @@ -176,7 +179,7 @@ class color4 { * @param b - The scale number. * @return out. */ - public static scale (out, a, b) { + public static scale (out: color4, a: color4, b: number) { out.r = a.r * b; out.g = a.g * b; out.b = a.b * b; @@ -193,11 +196,8 @@ class color4 { * @param t - The interpolation coefficient. * @return out. */ - public static lerp (out, a, b, t) { - const ar = a.r, - ag = a.g, - ab = a.b, - aa = a.a; + public static lerp (out: color4, a: color4, b: color4, t: number) { + const ar = a.r, ag = a.g, ab = a.b, aa = a.a; out.r = ar + t * (b.r - ar); out.g = ag + t * (b.g - ag); out.b = ab + t * (b.b - ab); @@ -211,7 +211,7 @@ class color4 { * @param a - The color. * @return - String representation of this color. */ - public static str (a) { + public static str (a: color4) { return `color4(${a.r}, ${a.g}, ${a.b}, ${a.a})`; } @@ -222,7 +222,7 @@ class color4 { * @param a - The color. * @return out. */ - public static array (out, a) { + public static array (out: number[], a: color4) { const scale = (a instanceof cc.Color || a.a > 1) ? 1 / 255 : 1; out[0] = a.r * scale; out[1] = a.g * scale; @@ -239,7 +239,7 @@ class color4 { * @param b - The second color. * @return True if the colors are equal, false otherwise. */ - public static exactEquals (a, b) { + public static exactEquals (a: color4, b: color4) { return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a; } @@ -248,9 +248,9 @@ class color4 { * * @param a - The first color. * @param b - The second color. - * @return True if the colors are approximately equal, false otherwise. + * @return True if the colors are equal, false otherwise. */ - public static equals (a, b) { + public static equals (a: color4, b: color4) { const a0 = a.r, a1 = a.g, a2 = a.b, a3 = a.a; const b0 = b.r, b1 = b.g, b2 = b.b, b3 = b.a; return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && @@ -261,44 +261,23 @@ class color4 { /** * Converts a color's rgb formal into the hexadecimal one. - * - * @param a - The color. - * @return - The color's hexadecimal formal. */ - public static hex (a) { + public static hex (a: color4) { return ((a.r * 255) << 24 | (a.g * 255) << 16 | (a.b * 255) << 8 | a.a * 255) >>> 0; } + + public r: number; + public g: number; + public b: number; + public a: number; + /** * Creates a color, with components specified separately. - * - * @param r - Value assigned to r component. - * @param g - Value assigned to g component. - * @param b - Value assigned to b component. - * @param a - Value assigned to a component. */ constructor (r = 1, g = 1, b = 1, a = 1) { - /** - * The r component. - * @type {number} - * */ this.r = r; - - /** - * The g component. - * @type {number} - * */ this.g = g; - - /** - * The b component. - * @type {number} - * */ this.b = b; - - /** - * The a component. - * @type {number} - * */ this.a = a; } } diff --git a/cocos/core/vmath/quat.ts b/cocos/core/vmath/quat.ts index cdc51b966b..aef11c1c83 100644 --- a/cocos/core/vmath/quat.ts +++ b/cocos/core/vmath/quat.ts @@ -14,6 +14,7 @@ const halfToRad = 0.5 * Math.PI / 180.0; * x, y, z and w are real numbers(called here its components), and i, j, and k are the fundamental quaternion units. */ export default class quat { + public static IDENTITY = new quat(); /** * Creates a quaternion, with components specified separately. @@ -67,20 +68,6 @@ export default class quat { return out; } - /** - * Sets a quaternion as identity quaternion. - * - * @param out - Quaternion to set. - * @return out. - */ - public static identity(out: Out) { - out.x = 0; - out.y = 0; - out.z = 0; - out.w = 1; - return out; - } - /** * Sets a quaternion to represent the shortest rotation from one * vector to another. diff --git a/cocos/core/vmath/vec2.ts b/cocos/core/vmath/vec2.ts index 4069876766..80b54bc8e7 100644 --- a/cocos/core/vmath/vec2.ts +++ b/cocos/core/vmath/vec2.ts @@ -8,6 +8,9 @@ import { EPSILON, random } from './utils'; * x, y is alias of the first, second component of vector, respectively. */ export default class vec2 { + public static ZERO = new vec2(0, 0); + public static ONE = new vec2(1, 1); + public static NEG_ONE = new vec2(-1, -1); /** * Creates a vector, with components specified separately. diff --git a/cocos/core/vmath/vec3.ts b/cocos/core/vmath/vec3.ts index 690d6fb21a..310aeccad8 100644 --- a/cocos/core/vmath/vec3.ts +++ b/cocos/core/vmath/vec3.ts @@ -8,12 +8,12 @@ import { EPSILON, random } from './utils'; * x, y, z is alias of the first, second, third component of vector, respectively. */ export default class vec3 { - public static UNIT_X = { x: 1, y: 0, z: 0 }; - public static UNIT_Y = { x: 0, y: 1, z: 0 }; - public static UNIT_Z = { x: 0, y: 0, z: 1 }; - public static ZERO = { x: 0, y: 0, z: 0 }; - public static ONE = { x: 1, y: 1, z: 1 }; - public static NEG_ONE = { x: -1, y: -1, z: -1 }; + public static UNIT_X = new vec3(1, 0, 0); + public static UNIT_Y = new vec3(0, 1, 0); + public static UNIT_Z = new vec3(0, 0, 1); + public static ZERO = new vec3(0, 0, 0); + public static ONE = new vec3(1, 1, 1); + public static NEG_ONE = new vec3(-1, -1, -1); /** * Creates a vector, with components specified separately. diff --git a/cocos/core/vmath/vec4.ts b/cocos/core/vmath/vec4.ts index f69969bd2b..7eeb1c22f5 100644 --- a/cocos/core/vmath/vec4.ts +++ b/cocos/core/vmath/vec4.ts @@ -8,6 +8,9 @@ import { EPSILON, random } from './utils'; * x, y, z, w is alias of the first, second, third, fourth component of vector, respectively. */ export default class vec4 { + public static ZERO = new vec4(0, 0, 0, 0); + public static ONE = new vec4(1, 1, 1, 1); + public static NEG_ONE = new vec4(-1, -1, -1, -1); /** * Create a vector, with components specified separately. diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index d1b0317d0e..329b970485 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -480,6 +480,13 @@ export interface IGFXColor { a: number; } +export enum GFXClearFlag { + COLOR = 1, + DEPTH = 2, + STENCIL = 4, + SKYBOX = 8, +} + export interface IGFXOffset { x: number; y: number; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index aa1c6f8d96..c77795a958 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -34,7 +34,7 @@ export class UBOGlobal { public static SIZE: number = UBOGlobal.COUNT * 4; public static BLOCK: GFXUniformBlock = { - binding: 30, name: 'Global', members: [ + binding: 30, name: 'CCGlobal', members: [ { name: 'u_time', type: GFXType.FLOAT4, count: 1 }, { name: 'u_screenSize', type: GFXType.FLOAT4, count: 1 }, { name: 'u_screenScale', type: GFXType.FLOAT4, count: 1 }, diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index d78252b389..6e72fb3e4f 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,50 +1,40 @@ import { frustum, ray } from '../../3d/geom-utils'; -import { lerp, mat4, quat, vec3 } from '../../core/vmath'; -import Node from '../../scene-graph/node'; +import { Mat4, Rect } from '../../core/value-types'; +import { color4, lerp, mat4, vec3 } from '../../core/vmath'; +import { GFXClearFlag, IGFXColor } from '../../gfx/define'; +import { Node } from '../../scene-graph/node'; import { RenderScene } from './render-scene'; -export enum NodeSpace { - LOCAL, - PARENT, - WORLD, -} - export enum CameraProjection { PERSPECTIVE, ORTHO, } -const q_a = cc.quat(); const v_a = cc.v3(); const v_b = cc.v3(); -export interface INormalizedViewPort { - x: number; - y: number; - w: number; - h: number; -} - export class Camera { private _scene: RenderScene; private _name: string; private _node: Node; private _proj: CameraProjection; - private _viewport: INormalizedViewPort; private _width: number; private _height: number; private _aspect: number; + private _orthoHeight: number; private _fov: number; private _nearClip: number; private _farClip: number; - private _matView: mat4 = new mat4(); - private _matProj: mat4 = new mat4(); - private _matViewProj: mat4 = new mat4(); - private _matViewProjInv: mat4 = new mat4(); - private _position: vec3 = new vec3(); - private _rotation: quat = new quat(); - private _direction: vec3 = new vec3(); + private _clearStencil: number; + private _clearDepth: number; + private _clearFlag: GFXClearFlag; + private _clearColor: IGFXColor = new color4(); + private _viewport: Rect = new Rect(0, 0, 1, 1); + private _matView: mat4 = new Mat4(); + private _matProj: mat4 = new Mat4(); + private _matViewProj: mat4 = new Mat4(); + private _matViewProjInv: mat4 = new Mat4(); private _frustum: frustum = new frustum(); constructor (scene: RenderScene, name: string) { @@ -52,21 +42,25 @@ export class Camera { this._name = name; this._node = scene.createNode({ name: name + 'Node', isStatic: false }); this._proj = CameraProjection.PERSPECTIVE; - this._viewport = { x: 0, y: 0, w: 1, h: 1 }; - const window = scene.root.mainWindow; - if (window) { - this._width = window.width; - this._height = window.height; + const win = scene.root.mainWindow; + if (win) { + this._width = win.width; + this._height = win.height; } else { this._width = 1; this._height = 1; } this._aspect = this._width / this._height; + this._orthoHeight = 10; this._fov = Math.PI / 4; this._nearClip = 1.0; this._farClip = 10000.0; + + this._clearDepth = 1; + this._clearStencil = 0; + this._clearFlag = GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL; } public resize (width: number, height: number) { @@ -84,8 +78,8 @@ export class Camera { if (this._proj === CameraProjection.PERSPECTIVE) { mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip); } else { - const x = this._width; - const y = this._height; + const x = this._orthoHeight * this._aspect; + const y = this._orthoHeight; mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip); } @@ -96,180 +90,134 @@ export class Camera { this._frustum.update(this._matViewProj, this._matViewProjInv); } - public set viewport (v: Partial) { - this._viewport.x = v.x || 0; - this._viewport.y = v.y || 0; - this._viewport.w = v.w || 1; - this._viewport.h = v.h || 1; + set node (val) { + this._node = val; } - public get viewport () { - return this._viewport; - } - - public set fov (fov: number) { - this._fov = fov; - } - - public get fov (): number { - return this._fov; - } - - public set nearClip (nearClip: number) { - this._nearClip = nearClip; - } - - public get nearClip (): number { - return this._nearClip; - } - - public set farClip (farClip: number) { - this._farClip = farClip; - } - - public get farClip (): number { - return this._farClip; - } - - public get scene (): RenderScene { - return this._scene; - } - - public get name (): string { - return this._name; - } - - public get node (): Node { + get node () { return this._node; } - public get width (): number { + set orthoHeight (val) { + this._orthoHeight = val; + } + + get orthoHeight () { + return this._orthoHeight; + } + + set projectionType (val) { + this._proj = val; + } + + get projectionType () { + return this._proj; + } + + set viewport (v) { + this._viewport = v; + } + + get viewport () { + return this._viewport; + } + + set fov (fov) { + this._fov = fov; + } + + get fov () { + return this._fov; + } + + set nearClip (nearClip) { + this._nearClip = nearClip; + } + + get nearClip () { + return this._nearClip; + } + + set farClip (farClip) { + this._farClip = farClip; + } + + get farClip () { + return this._farClip; + } + + set clearColor (val) { + this._clearColor = val; + } + + get clearColor () { + return this._clearColor; + } + + set clearDepth (val) { + this._clearDepth = val; + } + + get clearDepth () { + return this._clearDepth; + } + + set clearStencil (val) { + this._clearStencil = val; + } + + get clearStencil () { + return this._clearStencil; + } + + set clearFlag (val) { + this._clearFlag = val; + } + + get clearFlag () { + return this._clearFlag; + } + + get scene () { + return this._scene; + } + + get name () { + return this._name; + } + + get width () { return this._width; } - public get height (): number { + get height () { return this._height; } - public get aspect (): number { + get aspect () { return this._aspect; } - public get matView (): mat4 { + get matView () { return this._matView; } - public get matProj (): mat4 { + get matProj () { return this._matProj; } - public get matViewProj (): mat4 { + get matViewProj () { return this._matViewProj; } - public get matViewProjInv (): mat4 { + get matViewProjInv () { return this._matViewProjInv; } - public get frustum (): frustum { + get frustum () { return this._frustum; } - public rotate (rot: quat, ns?: NodeSpace) { - const space = (ns !== undefined ? ns : NodeSpace.LOCAL); - if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.getRotation(q_a); - this._node.setRotation(quat.multiply(q_a, q_a, rot)); - } else if (space === NodeSpace.WORLD) { - this._node.getWorldRotation(q_a); - this._node.setWorldRotation(quat.multiply(q_a, rot, q_a)); - } - } - - public rotateFromAxisAngle (axis: vec3, rad: number, ns?: NodeSpace) { - quat.fromAxisAngle(this._rotation, axis, rad); - const space = (ns !== undefined ? ns : NodeSpace.LOCAL); - if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.getRotation(q_a); - this._node.setRotation(quat.multiply(q_a, q_a, this._rotation)); - } else if (space === NodeSpace.WORLD) { - this._node.getWorldRotation(q_a); - this._node.setWorldRotation(quat.multiply(q_a, this._rotation, q_a)); - } - } - - public setRotation (rot: quat, ns?: NodeSpace) { - const space = (ns !== undefined ? ns : NodeSpace.LOCAL); - if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.setRotation(rot); - } else if (space === NodeSpace.WORLD) { - this._node.setWorldRotation(rot); - } - } - - public pitch (rad: number, ns?: NodeSpace) { - const space = (ns !== undefined ? ns : NodeSpace.LOCAL); - if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.getRotation(this._rotation); - quat.toAxisX(this._direction, this._rotation); - this.rotateFromAxisAngle(this._direction, rad, ns); - } else if (space === NodeSpace.WORLD) { - this._node.getWorldRotation(this._rotation); - quat.toAxisX(this._direction, this._rotation); - this.rotateFromAxisAngle(this._direction, rad, ns); - } - } - - public yaw (rad: number, ns?: NodeSpace) { - const space = (ns !== undefined ? ns : NodeSpace.LOCAL); - if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.getRotation(this._rotation); - quat.toAxisY(this._direction, this._rotation); - this.rotateFromAxisAngle(this._direction, rad, ns); - } else if (space === NodeSpace.WORLD) { - this._node.getWorldRotation(this._rotation); - quat.toAxisY(this._direction, this._rotation); - this.rotateFromAxisAngle(this._direction, rad, ns); - } - } - - public roll (rad: number, ns?: NodeSpace) { - const space = (ns !== undefined ? ns : NodeSpace.LOCAL); - if (space === NodeSpace.LOCAL || space === NodeSpace.PARENT) { - this._node.getRotation(this._rotation); - quat.toAxisZ(this._direction, this._rotation); - this.rotateFromAxisAngle(this._direction, rad, ns); - } else if (space === NodeSpace.WORLD) { - this._node.getWorldRotation(this._rotation); - quat.toAxisZ(this._direction, this._rotation); - this.rotateFromAxisAngle(this._direction, rad, ns); - } - } - - public set target (target: vec3) { - this._node.lookAt(target); - } - - public get position (): vec3 { - this._node.getPosition(this._position); - return this._position; - } - - public set position (pos: vec3) { - this._node.setWorldPosition(pos.x, pos.y, pos.z); - } - - public get direction (): vec3 { - this._node.getRotation(this._rotation); - vec3.transformQuat(this._direction, vec3.UNIT_Z, this._rotation); - return this._direction; - } - - public set direction (dir: vec3) { - quat.rotationTo(this._rotation, vec3.UNIT_Z, dir); - this._node.setRotation(this._rotation); - } - /** * transform a screen position to a world space ray */ diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index bb13775a62..bc62661518 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,5 +1,5 @@ import { Root, _createSceneFun } from '../../core/root'; -import Node from '../../scene-graph/node'; +import { Node } from '../../scene-graph/node'; import { Camera } from './camera'; import Light from './light'; import Model from './model'; diff --git a/cocos/renderer/scene/scene.js b/cocos/renderer/scene/scene.js index 8d68d51083..39899fbb0c 100644 --- a/cocos/renderer/scene/scene.js +++ b/cocos/renderer/scene/scene.js @@ -2,7 +2,7 @@ import { FixedArray, RecyclePool } from '../../3d/memop'; import { ray, triangle, intersect } from '../../3d/geom-utils'; -import Layers from '../../scene-graph/layers'; +import { Layers } from '../../scene-graph/layers'; import { vec3, mat4 } from '../../core/vmath'; import gfx from '../../renderer/gfx'; diff --git a/cocos/scene-graph/base-node.d.ts b/cocos/scene-graph/base-node.d.ts new file mode 100644 index 0000000000..1d52aba5c9 --- /dev/null +++ b/cocos/scene-graph/base-node.d.ts @@ -0,0 +1,77 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { CCObject } from '../core/data/object'; +import { Component } from '../components/component'; + +export class BaseNode extends CCObject { + protected static _setScene(node: BaseNode): void; + + protected _parent: this | null; + protected _children: this[]; + protected _active: boolean; + protected _level: number; + protected _components: Component[]; + protected _persistNode: boolean; + + protected uuid: string; + protected children: this[]; + protected childrenCount: number; + protected active: boolean; + protected parent: this; + + public getParent(): this; + public setParent(value: this): void; + public getChildByUuid(uuid: string): this; + public getChildByName(name: string): this; + public getChildByPath(path: string): this; + public addChild(child: this): void; + public insertChild(child: this, siblingIndex: number): void; + public getSiblingIndex(): number; + public setSiblingIndex(index: number): void; + public walk(prefunc: (target: this) => any, postfunc: (target: this) => any): void; + public removeFromParent(cleanup: boolean): void; + public removeChild(child: this, cleanup: boolean): void; + public removeAllChildren(cleanup: boolean): void; + public isChildOf(parent: this): boolean; + + public getComponent(typeOrClassName: object | string): Component | null; + public getComponents(typeOrClassName: object | string): Component[]; + public getComponentInChildren(typeOrClassName: object | string): Component | null; + public getComponentsInChildren(typeOrClassName: object | string): Component[]; + public addComponent(typeOrClassName: object | string): Component | null; + public removeComponent(typeOrClassName: object | string): void; + public destroyAllChildren(): void; + public cleanup(): void; + public onRestore(): void; + + protected _onSetParent(oldParent: this): void; + protected _onPostActivated(): void; + protected _onBatchRestored(): void; + protected _onBatchCreated(): void; + protected _onHierarchyChanged(oldParent: this): void; + protected _onHierarchyChangedBase(oldParent: this): void; + protected _instantiate(cloned: this): this; +} diff --git a/cocos/scene-graph/base-node.js b/cocos/scene-graph/base-node.js index 457c9d7871..81343aa01a 100644 --- a/cocos/scene-graph/base-node.js +++ b/cocos/scene-graph/base-node.js @@ -132,7 +132,7 @@ function findChildComponents(children, constructor, components) { * @private */ @ccclass("cc._BaseNode") -export default class BaseNode extends CCObject { +export class BaseNode extends CCObject { @property _parent = null; diff --git a/cocos/scene-graph/index.js b/cocos/scene-graph/index.js index d3cab311db..94e05131b6 100644 --- a/cocos/scene-graph/index.js +++ b/cocos/scene-graph/index.js @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -export { default as BaseNode } from './base-node'; -export { default as Node } from './node'; +export { BaseNode } from './base-node'; +export { Node } from './node'; export { default as PrivateNode } from './private-node'; export { default as NodeActivator } from './node-activator'; export { default as Scene } from './scene'; export { default as find } from './find'; -export { default as Layers } from './layers'; +export { Layers } from './layers'; diff --git a/cocos/scene-graph/layers.js b/cocos/scene-graph/layers.ts similarity index 50% rename from cocos/scene-graph/layers.js rename to cocos/scene-graph/layers.ts index cbf668b1b3..47ac5ad384 100644 --- a/cocos/scene-graph/layers.js +++ b/cocos/scene-graph/layers.ts @@ -2,15 +2,27 @@ /** * Entity layer system */ -class Layers { +export class Layers { + + // built-in layers, reserved up to (1 << 7) + public static Default = (1 << 0); + public static IgnoreRaycast = (1 << 1); + public static Gizmos = (1 << 2); + public static Editor = (1 << 3); + // masks + public static All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor]); + public static RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor, Layers.IgnoreRaycast]); + /** * Add a new layer * @param {string} name name of the new layer * @return {number} new layer's index */ - static addLayer(name) { - if (Layers._nextAvailable > 31) - return new Error('maximum layers reached.'); + public static addLayer (name: string): number | undefined { + if (Layers._nextAvailable > 31) { + console.warn('maximum layers reached.'); + return; + } Layers[name] = (1 << Layers._nextAvailable++); return Layers[name]; } @@ -20,10 +32,11 @@ class Layers { * @param {number[]} includes layers accepted by the mask * @return {number} the specified layer mask */ - static makeInclusiveMask(includes) { + public static makeInclusiveMask (includes: number[]): number { let mask = 0; - for (let i = 0; i < includes.length; i++) - mask |= includes[i]; + for (const inc of includes) { + mask |= inc; + } return mask; } @@ -32,7 +45,7 @@ class Layers { * @param {number[]} excludes layers rejected by the mask * @return {number} the specified layer mask */ - static makeExclusiveMask(excludes) { + public static makeExclusiveMask (excludes: number[]): number { return ~Layers.makeInclusiveMask(excludes); } @@ -42,22 +55,11 @@ class Layers { * @param {number} mask the testing layer mask * @return {boolean} true if accepted */ - static check(layer, mask) { - return (layer & mask) == layer; + public static check (layer: number, mask: number): boolean { + return (layer & mask) === layer; } + + private static _nextAvailable = 8; } -Layers._nextAvailable = 8; - -// built-in layers, reserved up to (1 << 7) -Layers.Default = (1 << 0); -Layers.IgnoreRaycast = (1 << 1); -Layers.Gizmos = (1 << 2); -Layers.Editor = (1 << 3); - -// masks -Layers.All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor]); -Layers.RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor, Layers.IgnoreRaycast]); - -export default Layers; cc.Layers = Layers; diff --git a/cocos/scene-graph/node-2d.js b/cocos/scene-graph/node-2d.js index b26011c840..d378db9d0f 100644 --- a/cocos/scene-graph/node-2d.js +++ b/cocos/scene-graph/node-2d.js @@ -32,7 +32,7 @@ import eventManager from '../core/platform/event-manager/CCEventManager'; import macro from '../core/platform/CCMacro'; import * as js from '../core/utils/js'; import EventTarget from '../core/event/event-target'; -import BaseNode from './base-node'; +import { BaseNode } from './base-node'; import { ccclass, property } from '../core/data/class-decorator'; const Flags = cc.Object.Flags; @@ -644,7 +644,7 @@ export default class Node extends BaseNode { localPosition.x = value; this.setLocalDirty(LocalDirtyFlag.POSITION); - + // fast check event if (this._eventMask & POSITION_ON) { // send event @@ -702,7 +702,7 @@ export default class Node extends BaseNode { } } } - + @property get z() { return this._position.z; @@ -1126,7 +1126,7 @@ export default class Node extends BaseNode { constructor (name) { super(name); this._reorderChildDirty = false; - + // cache component this._widget = null; // fast render component access @@ -1337,7 +1337,7 @@ export default class Node extends BaseNode { if (!this._activeInHierarchy) { // deactivate ActionManager and EventManager by default - + // ActionManager may not be inited in the editor worker. let manager = cc.director.getActionManager(); manager && manager.pauseTarget(this); @@ -1628,12 +1628,12 @@ export default class Node extends BaseNode { var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; if (listeners) { listeners.remove(type, callback, target); - + if (target && target.__eventTargets) { js.array.fastRemove(target.__eventTargets, this); } } - + } } @@ -1713,7 +1713,7 @@ export default class Node extends BaseNode { * @param {*} [arg4] - Fourth argument in callback * @param {*} [arg5] - Fifth argument in callback * @example - * + * * eventTarget.emit('fire', event); * eventTarget.emit('fire', message, emitter); */ @@ -1774,7 +1774,7 @@ export default class Node extends BaseNode { h = this._contentSize.height, cameraPt = _vec2a, testPt = _vec2b; - + let camera = cc.Camera.findCamera(this); if (camera) { camera.getCameraToWorldPoint(point, cameraPt); @@ -1834,7 +1834,7 @@ export default class Node extends BaseNode { parent = parent.parent; } } - + /** * Get all the targets listening to the supplied type of event in the target's bubbling phase. * The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree. @@ -1911,7 +1911,7 @@ export default class Node extends BaseNode { if (!CC_EDITOR || isFinite(y)) { locPosition.y = y; } - else { + else { return cc.error(ERR_INVALID_NUMBER, 'y of new position'); } this.setLocalDirty(LocalDirtyFlag.POSITION); @@ -2136,7 +2136,7 @@ export default class Node extends BaseNode { return out; } - + /* * Calculate and return world position. * This is not a public API yet, its usage could be updated @@ -2256,7 +2256,7 @@ export default class Node extends BaseNode { math.vec3.sub(_vec3_temp, _vec3_temp, pos); // NOTE: we use -z for view-dir math.vec3.normalize(_vec3_temp, _vec3_temp); math.quat.fromViewUp(_quat_temp, _vec3_temp, up); - + this.setWorldRot(_quat_temp); } @@ -2321,7 +2321,7 @@ export default class Node extends BaseNode { // position t.m12 = this._position.x; t.m13 = this._position.y; - + this._localMatDirty = 0; // Register dirty status of world matrix so that it can be recalculated this._worldMatDirty = true; @@ -2332,7 +2332,7 @@ export default class Node extends BaseNode { if (this._localMatDirty) { this._updateLocalMatrix(); } - + // Assume parent world matrix is correct let parent = this._parent; if (parent) { @@ -2403,7 +2403,7 @@ export default class Node extends BaseNode { this._updateLocalMatrix(); return math.mat4.copy(out, this._matrix); } - + /** * !#en * Get the world transform matrix (4x4) @@ -2517,7 +2517,7 @@ export default class Node extends BaseNode { out = AffineTrans.identity(); } this._updateLocalMatrix(); - + var contentSize = this._contentSize; _vec3_temp.x = -this._anchorPoint.x * contentSize.width; _vec3_temp.y = -this._anchorPoint.y * contentSize.height; @@ -2568,7 +2568,7 @@ export default class Node extends BaseNode { out = AffineTrans.identity(); } this._updateWorldMatrix(); - + var contentSize = this._contentSize; _vec3_temp.x = -this._anchorPoint.x * contentSize.width; _vec3_temp.y = -this._anchorPoint.y * contentSize.height; @@ -2673,7 +2673,7 @@ export default class Node extends BaseNode { convertTouchToNodeSpaceAR (touch) { return this.convertToNodeSpaceAR(touch.getLocation()); } - + /** * !#en * Returns a "local" axis aligned bounding box of the node.
@@ -2689,9 +2689,9 @@ export default class Node extends BaseNode { let width = this._contentSize.width; let height = this._contentSize.height; let rect = cc.rect( - -this._anchorPoint.x * width, - -this._anchorPoint.y * height, - width, + -this._anchorPoint.x * width, + -this._anchorPoint.y * height, + width, height); return rect.transformMat4(rect, this._matrix); } @@ -2723,9 +2723,9 @@ export default class Node extends BaseNode { let width = this._contentSize.width; let height = this._contentSize.height; let rect = cc.rect( - -this._anchorPoint.x * width, - -this._anchorPoint.y * height, - width, + -this._anchorPoint.x * width, + -this._anchorPoint.y * height, + width, height); var pMat = math.mat4.mul(this._worldMatrix, parentMat, this._matrix); @@ -2894,9 +2894,9 @@ if (CC_EDITOR) { // 3D Node Property /** - * !en + * !en * Switch 2D/3D node. The 2D nodes will run faster. - * !zh + * !zh * 切换 2D/3D 节点,2D 节点会有更高的运行效率 * @property {Boolean} is3DNode * @default false diff --git a/cocos/scene-graph/node.js b/cocos/scene-graph/node.js deleted file mode 100644 index 72461062ad..0000000000 --- a/cocos/scene-graph/node.js +++ /dev/null @@ -1,502 +0,0 @@ -import { vec3, mat4, quat } from '../core/vmath'; -import { Vec3 } from '../core/value-types'; -import BaseNode from './base-node'; -import Layers from './layers'; -import { EventTarget } from "../core/event"; -import { ccclass, property, mixins } from '../core/data/class-decorator'; - -let v3_a = cc.v3(); -let q_a = cc.quat(); -let q_b = cc.quat(); -let array_a = new Array(10); - -let EventType = cc.Enum({ - TRANSFORM_CHANGED: 'transform-changed', - POSITION_PART: 1, - ROTATION_PART: 2, - SCALE_PART: 4 -}); - -@ccclass('cc.Node') -@mixins(EventTarget) -class Node extends BaseNode { - // local transform - @property - _lpos = cc.v3(); - @property - _lrot = cc.quat(); - @property - _lscale = cc.v3(1, 1, 1); - @property - _layer = Layers.Default; // the layer this node belongs to - - @property - _euler = cc.v3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. - - @property({ - type: Vec3 - }) - set eulerAngles(val) { - this.setRotationFromEuler(val.x, val.y, val.z); - } - get eulerAngles() { - if (this._eulerDirty) { - quat.toEuler(this._euler, this._lrot); - this._eulerDirty = false; - } - return this._euler; - } - - set layer(l) { - this._layer = l; - } - - get layer() { - return this._layer; - } - - // world transform - _pos = cc.v3(); - _rot = cc.quat(); - _scale = cc.v3(1, 1, 1); - _mat = cc.mat4(); - - _dirty = false; // does the world transform need to update? - _hasChanged = false; // has the transform changed in this frame? - - _matDirty = false; - _eulerDirty = false; - - // is node but not scene - static isNode(obj) { - return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); - } - - static EventType = EventType; - - constructor(name) { - super(name); - EventTarget.call(this); - } - - - // =============================== - // hierarchy - // =============================== - - /** - * invalidate all children after relevant events - */ - onRestore() { - super.onRestore(); - this.invalidateChildren(); - } - - _onSetParent(oldParent) { - super._onSetParent(oldParent); - this.invalidateChildren(); - } - - _onPostActivated() { - this.invalidateChildren(); - } - - // =============================== - // transform helper - // =============================== - - /** - * Set rotation by lookAt target point - * @param {vec3} pos target position - * @param {vec3} up the up vector, default to (0,1,0) - */ - lookAt(pos, up) { - this.getWorldPosition(v3_a); - vec3.sub(v3_a, v3_a, pos); // NOTE: we use -z for view-dir - vec3.normalize(v3_a, v3_a); - quat.fromViewUp(q_a, v3_a, up); - - this.setWorldRotation(q_a); - } - - /** - * Reset the `hasChanged` flag recursively - */ - resetHasChanged() { - this._hasChanged = false; - let len = this._children.length; - for (let i = 0; i < len; ++i) { - this._children[i].resetHasChanged(); - } - } - - /** - * invalidate the world transform information - * for this node and all its children recursively - */ - invalidateChildren() { - if (this._dirty && this._hasChanged) return; - this._dirty = this._hasChanged = true; - for (const child of this._children) { - child.invalidateChildren(); - } - } - - /** - * update the world transform information if outdated - * here we assume all nodes are children of a scene node, - * which is always not dirty, has an identity transform and no parent. - */ - updateWorldTransform() { - if (!this._dirty) return; - let cur = this, child, i = 0; - while (cur._dirty) { - // top level node - array_a[i++] = cur; - cur = cur._parent; - if (!cur || !cur._parent) { - cur = null; - break; - } - } - while (i) { - child = array_a[--i]; - if (cur) { - vec3.mul(child._pos, child._lpos, cur._scale); - vec3.transformQuat(child._pos, child._pos, cur._rot); - vec3.add(child._pos, child._pos, cur._pos); - quat.mul(child._rot, cur._rot, child._lrot); - vec3.mul(child._scale, cur._scale, child._lscale); - } - child._matDirty = true; // further deferred eval - child._dirty = false; - cur = child; - } - } - - updateWorldTransformFull() { - this.updateWorldTransform(); - if (!this._matDirty) return; - mat4.fromRTS(this._mat, this._rot, this._pos, this._scale); - this._matDirty = false; - } - - // =============================== - // transform - // =============================== - - /** - * set local position - * @param {vec3|number} val the new local position, or the x component of it - * @param {number} [y] the y component of the new local position - * @param {number} [z] the z component of the new local position - */ - setPosition(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._lpos, val); - } else if (arguments.length === 3) { - vec3.set(this._lpos, val, y, z); - } - vec3.copy(this._pos, this._lpos); - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); - } - - /** - * get local position - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getPosition(out) { - if (out) { - return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); - } else { - return vec3.copy(cc.v3(), this._lpos); - } - } - - /** - * set local rotation - * @param {quat|number} val the new local rotation, or the x component of it - * @param {number} [y] the y component of the new local rotation - * @param {number} [z] the z component of the new local rotation - * @param {number} [w] the w component of the new local rotation - */ - setRotation(val, y, z, w) { - if (arguments.length === 1) { - quat.copy(this._lrot, val); - } else if (arguments.length === 4) { - quat.set(this._lrot, val, y, z, w); - } - quat.copy(this._rot, this._lrot); - this._eulerDirty = true; - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * set local rotation from euler angles - * @param {number} x - Angle to rotate around X axis in degrees. - * @param {number} y - Angle to rotate around Y axis in degrees. - * @param {number} z - Angle to rotate around Z axis in degrees. - */ - setRotationFromEuler(x, y, z) { - vec3.set(this._euler, x, y, z); - this._eulerDirty = false; - quat.fromEuler(this._lrot, x, y, z); - quat.copy(this._rot, this._lrot); - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * get local rotation - * @param {quat} [out] the receiving quaternion - * @return {quat} the resulting quaternion - */ - getRotation(out) { - if (out) { - return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w); - } else { - return quat.copy(cc.quat(), this._lrot); - } - } - - /** - * set local scale - * @param {vec3|number} val the new local scale, or the x component of it - * @param {number} [y] the y component of the new local scale - * @param {number} [z] the z component of the new local scale - */ - setScale(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._lscale, val); - } else if (arguments.length === 3) { - vec3.set(this._lscale, val, y, z); - } - vec3.copy(this._scale, this._lscale); - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); - } - - /** - * get local scale - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getScale(out) { - if (out) { - return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); - } else { - return vec3.copy(cc.v3(), this._lscale); - } - } - - /** - * set world position - * @param {vec3|number} val the new world position, or the x component of it - * @param {number} [y] the y component of the new world position - * @param {number} [z] the z component of the new world position - */ - setWorldPosition(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._pos, val); - } else if (arguments.length === 3) { - vec3.set(this._pos, val, y, z); - } - let parent = this._parent, local = this._lpos; - if (parent) { - parent.updateWorldTransform(); - vec3.sub(local, this._pos, parent._pos); - vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot)); - vec3.div(local, local, parent._scale); - } else { - vec3.copy(this._lpos, this._pos); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); - } - - /** - * get world position - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getWorldPosition(out) { - this.updateWorldTransform(); - if (out) { - return vec3.copy(out, this._pos); - } else { - return vec3.copy(cc.v3(), this._pos); - } - } - - /** - * set world rotation - * @param {quat|number} val the new world rotation, or the x component of it - * @param {number} [y] the y component of the new world rotation - * @param {number} [z] the z component of the new world rotation - * @param {number} [w] the w component of the new world rotation - */ - setWorldRotation(val, y, z, w) { - if (arguments.length === 1) { - quat.copy(this._rot, val); - } else if (arguments.length === 4) { - quat.set(this._rot, val, y, z, w); - } - if (this._parent) { - this._parent.getWorldRotation(q_a); - quat.mul(this._lrot, quat.conjugate(q_a, q_a), this._rot); - } else { - quat.copy(this._lrot, this._rot); - } - this._eulerDirty = true; - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * set world rotation from euler angles - * @param {number} x - Angle to rotate around X axis in degrees. - * @param {number} y - Angle to rotate around Y axis in degrees. - * @param {number} z - Angle to rotate around Z axis in degrees. - */ - setWorldRotationFromEuler(x, y, z) { - vec3.set(this._euler, x, y, z); - this._eulerDirty = false; - quat.fromEuler(this._rot, x, y, z); - if (this._parent) { - this._parent.getWorldRotation(q_a); - quat.mul(this._lrot, this._rot, quat.conjugate(q_a, q_a)); - } else { - quat.copy(this._lrot, this._rot); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); - } - - /** - * get world rotation - * @param {quat} [out] the receiving quaternion - * @return {quat} the resulting quaternion - */ - getWorldRotation(out) { - this.updateWorldTransform(); - if (out) { - return quat.copy(out, this._rot); - } else { - return quat.copy(cc.quat(), this._rot); - } - } - - /** - * set world scale - * @param {vec3|number} val the new world scale, or the x component of it - * @param {number} [y] the y component of the new world scale - * @param {number} [z] the z component of the new world scale - */ - setWorldScale(val, y, z) { - if (arguments.length === 1) { - vec3.copy(this._scale, val); - } else if (arguments.length === 3) { - vec3.set(this._scale, val, y, z); - } - if (this._parent) { - this._parent.getWorldScale(v3_a); - vec3.div(this._lscale, this._scale, v3_a); - } else { - vec3.copy(this._lscale, this._scale); - } - - this.invalidateChildren(); - this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); - } - - /** - * get world scale - * @param {vec3} [out] the receiving vector - * @return {vec3} the resulting vector - */ - getWorldScale(out) { - this.updateWorldTransform(); - if (out) { - return vec3.copy(out, this._scale); - } else { - return vec3.copy(cc.v3(), this._scale); - } - } - - /** - * get the matrix that transforms a point from local space into world space - * @param {mat4} [out] the receiving matrix - * @return {mat4} the resulting matrix - */ - getWorldMatrix(out) { - this.updateWorldTransformFull(); - if (out) { - return mat4.copy(out, this._mat); - } else { - return mat4.copy(cc.mat4(), this._mat); - } - } - - /** - * get world transform matrix (with only rotation and scale) - * @param {mat4} [out] the receiving matrix - * @return {mat4} the resulting matrix - */ - getWorldRS(out) { - this.updateWorldTransformFull(); - if (out) { - mat4.copy(out, this._mat); - } else { - out = mat4.copy(cc.mat4(), this._mat); - } - out.m12 = 0; out.m13 = 0; out.m14 = 0; - return out; - } - - /** - * get world transform matrix (with only rotation and translation) - * @param {mat4} [out] the receiving matrix - * @return {mat4} the resulting matrix - */ - getWorldRT(out) { - this.updateWorldTransform(); - if (!out) { - out = cc.mat4(); - } - return mat4.fromRT(out, this._rot, this._pos); - } -} - -if (CC_EDITOR) { - let repeat = (t, l) => t - Math.floor(t / l) * l; - let desc = { - set(val) { - this.setRotationFromEuler(val.x, val.y, val.z); - }, - get() { - if (this._eulerDirty) { - let eu = this._euler; - quat.toEuler(v3_a, this._lrot); - eu.x = repeat(v3_a.x - eu.x + 180, 360) + eu.x - 180; - eu.y = repeat(v3_a.y - eu.y + 180, 360) + eu.y - 180; - eu.z = repeat(v3_a.z - eu.z + 180, 360) + eu.z - 180; - this._eulerDirty = false; - } - return this._euler; - } - }; - Object.defineProperty(Node.prototype, 'eulerAngles', desc); -} - -cc.Node = Node; -export default Node; diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts new file mode 100644 index 0000000000..2915cc3ed2 --- /dev/null +++ b/cocos/scene-graph/node.ts @@ -0,0 +1,591 @@ +import { ccclass, mixins, property } from '../core/data/class-decorator'; +import { EventTarget } from '../core/event'; +import { Enum, Mat4, Quat, Vec3 } from '../core/value-types'; +import { mat4, quat, vec3 } from '../core/vmath'; +import { BaseNode } from './base-node'; +import { Layers } from './layers'; + +const v3_a = new Vec3(); +const q_a = new Quat(); +const array_a = new Array(10); + +const EventType = Enum({ + TRANSFORM_CHANGED: 'transform-changed', + POSITION_PART: 1, + ROTATION_PART: 2, + SCALE_PART: 4, +}); + +enum NodeSpace { + LOCAL, + WORLD, +} + +@ccclass('cc.Node') +@mixins(EventTarget) +class Node extends BaseNode { + public static EventType = EventType; + public static NodeSpace = NodeSpace; + + // is node but not scene + public static isNode (obj: object) { + return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); + } + // local transform + @property + public _lpos = new Vec3(); + @property + public _lrot = new Quat(); + @property + public _lscale = new Vec3(1, 1, 1); + @property + public _layer = Layers.Default; // the layer this node belongs to + + @property + public _euler = new Vec3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. + + // world transform + public _pos = new Vec3(); + public _rot = new Quat(); + public _scale = new Vec3(1, 1, 1); + public _mat = new Mat4(); + + public _dirty = false; // does the world transform need to update? + public _hasChanged = false; // has the transform changed in this frame? + + public _matDirty = false; + public _eulerDirty = false; + + @property({ + type: Vec3, + }) + set eulerAngles (val) { + this.setRotationFromEuler(val.x, val.y, val.z); + } + get eulerAngles () { + if (this._eulerDirty) { + quat.toEuler(this._euler, this._lrot); + this._eulerDirty = false; + } + return this._euler; + } + + set layer (l) { + this._layer = l; + } + + get layer () { + return this._layer; + } + + constructor (name: string) { + super(name); + EventTarget.call(this); + } + + // =============================== + // hierarchy + // =============================== + + /** + * invalidate all children after relevant events + */ + public onRestore () { + super.onRestore(); + this.invalidateChildren(); + } + + public _onSetParent (oldParent: this) { + super._onSetParent(oldParent); + this.invalidateChildren(); + } + + public _onPostActivated () { + this.invalidateChildren(); + } + + // =============================== + // transform helper, convenient but not the most efficient + // =============================== + + /** + * Rotate the node + * @param rot - rotation to apply + * @param ns - the operating space + */ + public rotate (rot: Quat, ns?: NodeSpace) { + const space = ns || NodeSpace.LOCAL; + if (space === NodeSpace.LOCAL) { + this.getRotation(q_a); + this.setRotation(quat.multiply(q_a, q_a, rot)); + } else if (space === NodeSpace.WORLD) { + this.getWorldRotation(q_a); + this.setWorldRotation(quat.multiply(q_a, rot, q_a)); + } + } + + /** + * rotate the node around X axis + * @param rad - rotating angle + * @param ns - the operating space + */ + public pitch (rad: number, ns?: NodeSpace) { + const space = ns || NodeSpace.LOCAL; + if (space === NodeSpace.LOCAL) { + this.getWorldRotation(q_a); + quat.toAxisX(v3_a, q_a); + quat.fromAxisAngle(q_a, v3_a, rad); + this.rotate(q_a, ns); + } else if (space === NodeSpace.WORLD) { + quat.fromAxisAngle(q_a, vec3.UNIT_X, rad); + this.rotate(q_a, ns); + } + } + + /** + * rotate the node around Y axis + * @param rad - rotating angle + * @param ns - the operating space + */ + public yaw (rad: number, ns?: NodeSpace) { + const space = ns || NodeSpace.LOCAL; + if (space === NodeSpace.LOCAL) { + this.getWorldRotation(q_a); + quat.toAxisY(v3_a, q_a); + quat.fromAxisAngle(q_a, v3_a, rad); + this.rotate(q_a, ns); + } else if (space === NodeSpace.WORLD) { + quat.fromAxisAngle(q_a, vec3.UNIT_Y, rad); + this.rotate(q_a, ns); + } + } + + /** + * rotate the node around Z axis + * @param rad - rotating angle + * @param ns - the operating space + */ + public roll (rad: number, ns?: NodeSpace) { + const space = (ns !== undefined ? ns : NodeSpace.LOCAL); + if (space === NodeSpace.LOCAL) { + this.getWorldRotation(q_a); + quat.toAxisZ(v3_a, q_a); + quat.fromAxisAngle(q_a, v3_a, rad); + this.rotate(q_a, ns); + } else if (space === NodeSpace.WORLD) { + quat.fromAxisAngle(q_a, vec3.UNIT_Z, rad); + this.rotate(q_a, ns); + } + } + + public get direction (): Vec3 { + this.getRotation(q_a); + return vec3.transformQuat(new Vec3(), vec3.UNIT_Z, q_a); + } + + public set direction (dir: Vec3) { + quat.rotationTo(q_a, vec3.UNIT_Z, dir); + this.setRotation(q_a); + } + + /** + * Set rotation by lookAt target point + * @param pos - target position + * @param up - the up vector, default to (0,1,0) + */ + public lookAt (pos: Vec3, up: Vec3) { + this.getWorldPosition(v3_a); + vec3.sub(v3_a, v3_a, pos); // NOTE: we use -z for view-dir + vec3.normalize(v3_a, v3_a); + quat.fromViewUp(q_a, v3_a, up); + + this.setWorldRotation(q_a); + } + + // =============================== + // transform maintainer + // =============================== + + /** + * Reset the `hasChanged` flag recursively + */ + public resetHasChanged () { + this._hasChanged = false; + const len = this._children.length; + for (let i = 0; i < len; ++i) { + this._children[i].resetHasChanged(); + } + } + + /** + * invalidate the world transform information + * for this node and all its children recursively + */ + public invalidateChildren () { + if (this._dirty && this._hasChanged) { return; } + this._dirty = this._hasChanged = true; + for (const child of this._children) { + child.invalidateChildren(); + } + } + + /** + * update the world transform information if outdated + * here we assume all nodes are children of a scene node, + * which is always not dirty, has an identity transform and no parent. + */ + public updateWorldTransform () { + if (!this._dirty) { return; } + let cur: this | null = this; + let i = 0; + while (cur._dirty) { + // top level node + array_a[i++] = cur; + cur = cur._parent; + if (!cur || !cur._parent) { + cur = null; + break; + } + } + let child: this; + while (i) { + child = array_a[--i]; + if (cur) { + vec3.mul(child._pos, child._lpos, cur._scale); + vec3.transformQuat(child._pos, child._pos, cur._rot); + vec3.add(child._pos, child._pos, cur._pos); + quat.mul(child._rot, cur._rot, child._lrot); + vec3.mul(child._scale, cur._scale, child._lscale); + } + child._matDirty = true; // further deferred eval + child._dirty = false; + cur = child; + } + } + + public updateWorldTransformFull () { + this.updateWorldTransform(); + if (!this._matDirty) { return; } + mat4.fromRTS(this._mat, this._rot, this._pos, this._scale); + this._matDirty = false; + } + + // =============================== + // transform + // =============================== + + /** + * set local position + * @param val - the new local position, or the x component of it + * @param y - the y component of the new local position + * @param z - the z component of the new local position + */ + public setPosition (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._lpos, val); + } else if (arguments.length === 3) { + vec3.set(this._lpos, val, y, z); + } + vec3.copy(this._pos, this._lpos); + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); + } + + /** + * get local position + * @param out the receiving vector + * @returns the resulting vector + */ + public getPosition (out: Vec3): Vec3 { + if (out) { + return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); + } else { + return vec3.copy(new Vec3(), this._lpos); + } + } + + /** + * set local rotation + * @param val - the new local rotation, or the x component of it + * @param y - the y component of the new local rotation + * @param z - the z component of the new local rotation + * @param w - the w component of the new local rotation + */ + public setRotation (val: Quat | number, y?: number, z?: number, w?: number) { + if (y === undefined || z === undefined || w === undefined) { + quat.copy(this._lrot, val); + } else if (arguments.length === 4) { + quat.set(this._lrot, val, y, z, w); + } + quat.copy(this._rot, this._lrot); + this._eulerDirty = true; + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * set local rotation from euler angles + * @param x - Angle to rotate around X axis in degrees. + * @param y - Angle to rotate around Y axis in degrees. + * @param z - Angle to rotate around Z axis in degrees. + */ + public setRotationFromEuler (x: number, y: number, z: number) { + vec3.set(this._euler, x, y, z); + this._eulerDirty = false; + quat.fromEuler(this._lrot, x, y, z); + quat.copy(this._rot, this._lrot); + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * get local rotation + * @param out - the receiving quaternion + * @returns the resulting quaternion + */ + public getRotation (out: Quat): Quat { + if (out) { + return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w); + } else { + return quat.copy(new Quat(), this._lrot); + } + } + + /** + * set local scale + * @param val - the new local scale, or the x component of it + * @param y - the y component of the new local scale + * @param z - the z component of the new local scale + */ + public setScale (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._lscale, val); + } else if (arguments.length === 3) { + vec3.set(this._lscale, val, y, z); + } + vec3.copy(this._scale, this._lscale); + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); + } + + /** + * get local scale + * @param out - the receiving vector + * @returns the resulting vector + */ + public getScale (out: Vec3): Vec3 { + if (out) { + return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); + } else { + return vec3.copy(new Vec3(), this._lscale); + } + } + + /** + * set world position + * @param val - the new world position, or the x component of it + * @param y - the y component of the new world position + * @param z - the z component of the new world position + */ + public setWorldPosition (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._pos, val); + } else if (arguments.length === 3) { + vec3.set(this._pos, val, y, z); + } + const parent = this._parent; + const local = this._lpos; + if (parent) { + parent.updateWorldTransform(); + vec3.sub(local, this._pos, parent._pos); + vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot)); + vec3.div(local, local, parent._scale); + } else { + vec3.copy(this._lpos, this._pos); + } + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART); + } + + /** + * get world position + * @param out - the receiving vector + * @returns the resulting vector + */ + public getWorldPosition (out: Vec3): Vec3 { + this.updateWorldTransform(); + if (out) { + return vec3.copy(out, this._pos); + } else { + return vec3.copy(new Vec3(), this._pos); + } + } + + /** + * set world rotation + * @param val - the new world rotation, or the x component of it + * @param y - the y component of the new world rotation + * @param z - the z component of the new world rotation + * @param w - the w component of the new world rotation + */ + public setWorldRotation (val: Quat | number, y?: number, z?: number, w?: number) { + if (y === undefined || z === undefined || w === undefined) { + quat.copy(this._rot, val); + } else if (arguments.length === 4) { + quat.set(this._rot, val, y, z, w); + } + if (this._parent) { + this._parent.getWorldRotation(q_a); + quat.mul(this._lrot, quat.conjugate(q_a, q_a), this._rot); + } else { + quat.copy(this._lrot, this._rot); + } + this._eulerDirty = true; + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * set world rotation from euler angles + * @param x - Angle to rotate around X axis in degrees. + * @param y - Angle to rotate around Y axis in degrees. + * @param z - Angle to rotate around Z axis in degrees. + */ + public setWorldRotationFromEuler (x: number, y: number, z: number) { + vec3.set(this._euler, x, y, z); + this._eulerDirty = false; + quat.fromEuler(this._rot, x, y, z); + if (this._parent) { + this._parent.getWorldRotation(q_a); + quat.mul(this._lrot, this._rot, quat.conjugate(q_a, q_a)); + } else { + quat.copy(this._lrot, this._rot); + } + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART); + } + + /** + * get world rotation + * @param out - the receiving quaternion + * @returns the resulting quaternion + */ + public getWorldRotation (out: Quat): Quat { + this.updateWorldTransform(); + if (out) { + return quat.copy(out, this._rot); + } else { + return quat.copy(new Quat(), this._rot); + } + } + + /** + * set world scale + * @param val - the new world scale, or the x component of it + * @param y - the y component of the new world scale + * @param z - the z component of the new world scale + */ + public setWorldScale (val: Vec3 | number, y?: number, z?: number) { + if (y === undefined || z === undefined) { + vec3.copy(this._scale, val); + } else if (arguments.length === 3) { + vec3.set(this._scale, val, y, z); + } + if (this._parent) { + this._parent.getWorldScale(v3_a); + vec3.div(this._lscale, this._scale, v3_a); + } else { + vec3.copy(this._lscale, this._scale); + } + + this.invalidateChildren(); + this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART); + } + + /** + * get world scale + * @param out - the receiving vector + * @returns the resulting vector + */ + public getWorldScale (out: Vec3): Vec3 { + this.updateWorldTransform(); + if (out) { + return vec3.copy(out, this._scale); + } else { + return vec3.copy(new Vec3(), this._scale); + } + } + + /** + * get the matrix that transforms a point from local space into world space + * @param out - the receiving matrix + * @returns the - resulting matrix + */ + public getWorldMatrix (out: Mat4): Mat4 { + this.updateWorldTransformFull(); + if (out) { + return mat4.copy(out, this._mat); + } else { + return mat4.copy(new Mat4(), this._mat); + } + } + + /** + * get world transform matrix (with only rotation and scale) + * @param out - the receiving matrix + * @returns the - resulting matrix + */ + public getWorldRS (out: Mat4): Mat4 { + this.updateWorldTransformFull(); + if (out) { + mat4.copy(out, this._mat); + } else { + out = mat4.copy(new Mat4(), this._mat); + } + out.m12 = 0; out.m13 = 0; out.m14 = 0; + return out; + } + + /** + * get world transform matrix (with only rotation and translation) + * @param out - the receiving matrix + * @returns the - resulting matrix + */ + public getWorldRT (out: Mat4): Mat4 { + this.updateWorldTransform(); + if (!out) { + out = new Mat4(); + } + return mat4.fromRT(out, this._rot, this._pos); + } +} + +if (CC_EDITOR) { + const repeat = (t: number, l: number) => t - Math.floor(t / l) * l; + Object.defineProperty(Node.prototype, 'eulerAngles', { + set (val: Vec3) { + this.setRotationFromEuler(val.x, val.y, val.z); + }, + get () { + if (this._eulerDirty) { + const eu = this._euler; + quat.toEuler(v3_a, this._lrot); + eu.x = repeat(v3_a.x - eu.x + 180, 360) + eu.x - 180; + eu.y = repeat(v3_a.y - eu.y + 180, 360) + eu.y - 180; + eu.z = repeat(v3_a.z - eu.z + 180, 360) + eu.z - 180; + this._eulerDirty = false; + } + return this._euler; + }, + }); +} + +cc.Node = Node; +export { Node }; diff --git a/cocos/scene-graph/private-node.js b/cocos/scene-graph/private-node.js index 50c22cb9bf..f17569b64e 100644 --- a/cocos/scene-graph/private-node.js +++ b/cocos/scene-graph/private-node.js @@ -25,7 +25,7 @@ 'use strict'; -import Node from './node'; +import { Node } from './node'; import { ccclass, property } from '../core/data/class-decorator'; const LocalDirtyFlag = Node._LocalDirtyFlag; @@ -164,4 +164,4 @@ export default class PrivateNode extends Node { cc.js.getset(PrivateNode.prototype, "parent", PrivateNode.prototype.getParent, PrivateNode.prototype.setParent); cc.js.getset(PrivateNode.prototype, "position", PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition); -cc.PrivateNode = PrivateNode; \ No newline at end of file +cc.PrivateNode = PrivateNode; diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index 2e508061b5..53bc05b996 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -23,10 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -import Node from './node'; +import { Node } from './node'; import { ccclass, property } from '../core/data/class-decorator'; -import BaseNode from './base-node'; -import { RenderScene } from '../renderer/scene/render-scene'; +import { BaseNode } from './base-node'; /** * !#en From 852d4ec1a63dc92f5d91a071133127cfa0dc475f Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 10 Jan 2019 20:37:37 +0800 Subject: [PATCH 099/267] node from compoennt --- ...amera-component.js => camera-component.ts} | 148 ++++++++---------- cocos/3d/framework/index.js | 2 +- cocos/3d/framework/model-component.js | 7 - cocos/components/component.d.ts | 20 +-- cocos/core/data/instantiate.js | 4 +- cocos/core/value-types/color.js | 2 +- cocos/core/value-types/index.js | 4 +- cocos/core/value-types/mat4.js | 2 +- cocos/core/value-types/quat.js | 2 +- cocos/core/value-types/rect.js | 4 +- cocos/core/value-types/size.js | 2 +- .../{value-type.js => value-type.ts} | 31 ++-- cocos/core/value-types/vec2.js | 4 +- cocos/core/value-types/vec3.js | 4 +- cocos/core/value-types/vec4.js | 4 +- cocos/renderer/scene/camera.ts | 4 +- cocos/scene-graph/node.ts | 26 +-- 17 files changed, 122 insertions(+), 148 deletions(-) rename cocos/3d/framework/{camera-component.js => camera-component.ts} (71%) rename cocos/core/value-types/{value-type.js => value-type.ts} (84%) diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.ts similarity index 71% rename from cocos/3d/framework/camera-component.js rename to cocos/3d/framework/camera-component.ts index cf58a3a0c4..e23e1c7d11 100644 --- a/cocos/3d/framework/camera-component.js +++ b/cocos/3d/framework/camera-component.ts @@ -22,17 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -// @ts-check -import { toRadian, color4 } from '../../core/vmath'; -import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; -import { Enum, Rect } from '../../core/value-types'; import { Component } from '../../components/component'; -import { CameraProjection } from '../../renderer/scene/camera'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { Enum, Rect } from '../../core/value-types'; +import { color4, toRadian } from '../../core/vmath'; import { GFXClearFlag } from '../../gfx/define'; - -/** - * @typedef {import('../../core/value-types/index').Color} Color - */ +import { Camera, CameraProjection } from '../../renderer/scene/camera'; /** * !#en The light source type @@ -41,7 +36,7 @@ import { GFXClearFlag } from '../../gfx/define'; * @static * @enum CameraComponent.Projection */ -let ProjectionType = Enum({ +const ProjectionType = Enum({ /** * !#en The orthogonal camera * @@ -59,14 +54,14 @@ let ProjectionType = Enum({ * @readonly * @type {Number} */ - PERSPECTIVE: 1 + PERSPECTIVE: 1, }); -let CameraClearFlag = Enum({ +const CameraClearFlag = Enum({ SKYBOX: GFXClearFlag.SKYBOX | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, SOLID_COLOR: GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, DEPTH_ONLY: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, - DONT_CLEAR: 0 + DONT_CLEAR: 0, }); /** @@ -79,39 +74,37 @@ let CameraClearFlag = Enum({ @ccclass('cc.CameraComponent') @menu('Components/CameraComponent') @executeInEditMode -export default class CameraComponent extends Component { - @property - _projection = ProjectionType.PERSPECTIVE; +export class CameraComponent extends Component { + public static ProjectionType = ProjectionType; @property - _priority = 0; - + protected _projection = ProjectionType.PERSPECTIVE; @property - _fov = 45; - + protected _priority = 0; @property - _orthoHeight = 10; - + protected _fov = 45; @property - _near = 0.01; - + protected _orthoHeight = 10; @property - _far = 1000.0; - + protected _near = 0.01; @property - _color = cc.color('#334C78'); - + protected _far = 1000.0; @property - _depth = 1; - + protected _color = cc.color('#334C78'); @property - _stencil = 0; - + protected _depth = 1; @property - _clearFlags = CameraClearFlag.SOLID_COLOR; - + protected _stencil = 0; @property - _rect = new Rect(0, 0, 1, 1); + protected _clearFlags = CameraClearFlag.SOLID_COLOR; + @property + protected _rect = new Rect(0, 0, 1, 1); + + protected _camera: Camera | null = null; + + constructor () { + super(); + } /** * !#en The projection type of the camera @@ -120,20 +113,20 @@ export default class CameraComponent extends Component { * @type {Number} */ @property({ - type: ProjectionType + type: ProjectionType, }) - get projection() { + get projection () { return this._projection; } - set projection(val) { + set projection (val) { this._projection = val; let type = CameraProjection.PERSPECTIVE; if (this._projection === ProjectionType.ORTHO) { type = CameraProjection.ORTHO; } - if (this.enabled) this._camera.projectionType = type; + if (this._camera) { this._camera.projectionType = type; } } /** @@ -143,13 +136,13 @@ export default class CameraComponent extends Component { * @type {Number} */ @property - get fov() { + get fov () { return this._fov; } - set fov(val) { + set fov (val) { this._fov = val; - if (this.enabled) this._camera.fov = toRadian(val); + if (this._camera) { this._camera.fov = toRadian(val); } } /** @@ -159,13 +152,13 @@ export default class CameraComponent extends Component { * @type {Number} */ @property - get orthoHeight() { + get orthoHeight () { return this._orthoHeight; } - set orthoHeight(val) { + set orthoHeight (val) { this._orthoHeight = val; - if (this.enabled) this._camera.orthoHeight = val; + if (this._camera) { this._camera.orthoHeight = val; } } /** @@ -175,13 +168,13 @@ export default class CameraComponent extends Component { * @type {Number} */ @property - get near() { + get near () { return this._near; } - set near(val) { + set near (val) { this._near = val; - if (this.enabled) this._camera.nearClip =val; + if (this._camera) { this._camera.nearClip = val; } } /** @@ -191,13 +184,13 @@ export default class CameraComponent extends Component { * @type {Number} */ @property - get far() { + get far () { return this._far; } - set far(val) { + set far (val) { this._far = val; - if (this.enabled) this._camera.farClip = val; + if (this._camera) { this._camera.farClip = val; } } /** @@ -207,14 +200,15 @@ export default class CameraComponent extends Component { * @type {Color} */ @property - get color() { + get color () { return this._color; } - set color(val) { + set color (val) { this._color = val; - if (this.enabled) this._camera.clearColor = + if (this._camera) { this._camera.clearColor = color4.create(val.r / 255, val.g / 255, val.b / 255, val.a / 255); + } } /** @@ -224,14 +218,15 @@ export default class CameraComponent extends Component { * @type {Number} */ @property - get depth() { + get depth () { return this._depth; } - set depth(val) { + set depth (val) { this._depth = val; - if (this.enabled) + if (this._camera) { this._camera.clearDepth = val; + } } /** @@ -241,13 +236,13 @@ export default class CameraComponent extends Component { * @type {Number} */ @property - get stencil() { + get stencil () { return this._stencil; } - set stencil(val) { + set stencil (val) { this._stencil = val; - if (this.enabled) this._camera.clearStencil = val; + if (this._camera) { this._camera.clearStencil = val; } } /** @@ -257,15 +252,15 @@ export default class CameraComponent extends Component { * @type {Number} */ @property({ - type: CameraClearFlag + type: CameraClearFlag, }) - get clearFlags() { + get clearFlags () { return this._clearFlags; } - set clearFlags(val) { + set clearFlags (val) { this._clearFlags = val; - if (this.enabled) this._camera.clearFlag = val; + if (this._camera) { this._camera.clearFlag = val; } } /** @@ -275,29 +270,23 @@ export default class CameraComponent extends Component { * @type {Rect} */ @property - get rect() { + get rect () { return this._rect; } - set rect(val) { + set rect (val) { this._rect = val; - if (this.enabled) this._camera.viewport = val; + if (this._camera) { this._camera.viewport = val; } } - static Projection = CameraProjection; - - constructor() { - super(); - } - - onLoad() { + public onLoad () { } - onEnable() { + public onEnable () { this._camera = this._getRenderScene().createCamera(this.name); + this._camera.node = this.node; this.projection = this._projection; - this.priority = this._priority; this.fov = this._fov; this.orthoHeight = this._orthoHeight; this.near = this._near; @@ -307,14 +296,13 @@ export default class CameraComponent extends Component { this.stencil = this._stencil; this.clearFlags = this._clearFlags; this.rect = this._rect; - this._camera.node = this.node; } - onDisable() { - this._getRenderScene().destroyCamera(this._camera); + public onDisable () { + if (this._camera) { this._getRenderScene().destroyCamera(this._camera); } } - onDestroy() { + public onDestroy () { } } diff --git a/cocos/3d/framework/index.js b/cocos/3d/framework/index.js index eeaeffaafe..c0750bd999 100644 --- a/cocos/3d/framework/index.js +++ b/cocos/3d/framework/index.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import CameraComponent from './camera-component'; +import { CameraComponent } from './camera-component'; import AnimationComponent from './animation-component'; import LightComponent from './light-component'; import ModelComponent from './model-component'; diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 02ddc06c4e..c55f399e76 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -22,15 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -// @ts-check import Model from '../../renderer/scene/model'; import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator'; import { Mesh } from '../assets/mesh'; import Enum from '../../core/value-types/enum'; import RenderableComponent from './renderable-component'; -/** - * @typedef {import('../assets/material').default} Material - */ /** * !#en Shadow projection mode @@ -103,9 +99,6 @@ export default class ModelComponent extends RenderableComponent { @property _receiveShadows = false; - /** - * @type {Material} - */ static _builtinMaterial = null; /** diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index 873270c9e4..29cff6644f 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -39,14 +39,14 @@ export class Component extends CCObject { public constructor(); - _getRenderScene(index?: number): RenderScene | undefined; - addComponent(typeOrClassName: Function | string): Component; - getComponent(typeOrClassName: Function | string): Component; - getComponents(typeOrClassName: Function | string): Component[]; - getComponentInChildren(typeOrClassName: Function | string): Component; - getComponentsInChildren(typeOrClassName: Function | string): Component[]; - schedule(callback: Function, interval: number, repeat: number, delay: number): void; - scheduleOnce(callback: Function, delay: number): void; - unschedule(callback: Function): void; - unscheduleAllCallbacks(): void; + protected _getRenderScene(index?: number): RenderScene; + public addComponent(typeOrClassName: Function | string): Component; + public getComponent(typeOrClassName: Function | string): Component; + public getComponents(typeOrClassName: Function | string): Component[]; + public getComponentInChildren(typeOrClassName: Function | string): Component; + public getComponentsInChildren(typeOrClassName: Function | string): Component[]; + public schedule(callback: Function, interval: number, repeat: number, delay: number): void; + public scheduleOnce(callback: Function, delay: number): void; + public unschedule(callback: Function): void; + public unscheduleAllCallbacks(): void; } diff --git a/cocos/core/data/instantiate.js b/cocos/core/data/instantiate.js index 77d1bbde6a..f86904a04e 100644 --- a/cocos/core/data/instantiate.js +++ b/cocos/core/data/instantiate.js @@ -25,8 +25,8 @@ ****************************************************************************/ import { CCObject } from './object'; -import ValueType from '../value-types/value-type'; -import {isDomNode} from '../utils/misc'; +import { ValueType } from '../value-types/value-type'; +import { isDomNode } from '../utils/misc'; const Destroyed = CCObject.Flags.Destroyed; const PersistentMask = CCObject.Flags.PersistentMask; diff --git a/cocos/core/value-types/color.js b/cocos/core/value-types/color.js index 76b09bb909..4f7909fe36 100644 --- a/cocos/core/value-types/color.js +++ b/cocos/core/value-types/color.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; /** diff --git a/cocos/core/value-types/index.js b/cocos/core/value-types/index.js index ad1de90e43..01e52b3897 100644 --- a/cocos/core/value-types/index.js +++ b/cocos/core/value-types/index.js @@ -25,7 +25,7 @@ ****************************************************************************/ export { default as Enum } from './enum'; -export { default as ValueType } from './value-type'; +export { ValueType } from './value-type'; export { default as Vec2} from './vec2'; export { default as Vec3} from './vec3'; export { default as Vec4} from './vec4'; @@ -34,4 +34,4 @@ export { default as Mat4} from './mat4'; export { default as AffineTransform} from './affine-transform'; export { default as Size} from './size'; export { default as Rect} from './rect'; -export { default as Color} from './color'; \ No newline at end of file +export { default as Color} from './color'; diff --git a/cocos/core/value-types/mat4.js b/cocos/core/value-types/mat4.js index 3342642a80..a3261a6f78 100644 --- a/cocos/core/value-types/mat4.js +++ b/cocos/core/value-types/mat4.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; import {mat4} from '../vmath'; diff --git a/cocos/core/value-types/quat.js b/cocos/core/value-types/quat.js index 30dcfc5f36..8e2199b427 100644 --- a/cocos/core/value-types/quat.js +++ b/cocos/core/value-types/quat.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; import quat from '../vmath/quat'; diff --git a/cocos/core/value-types/rect.js b/cocos/core/value-types/rect.js index dd8250d77e..1d55185d74 100644 --- a/cocos/core/value-types/rect.js +++ b/cocos/core/value-types/rect.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; /** @@ -420,4 +420,4 @@ cc.Rect = Rect; */ cc.rect = function rect (x, y, w, h) { return new Rect(x, y, w, h); -}; \ No newline at end of file +}; diff --git a/cocos/core/value-types/size.js b/cocos/core/value-types/size.js index d35ed6d8fe..7d09fb68ce 100644 --- a/cocos/core/value-types/size.js +++ b/cocos/core/value-types/size.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; /** diff --git a/cocos/core/value-types/value-type.js b/cocos/core/value-types/value-type.ts similarity index 84% rename from cocos/core/value-types/value-type.js rename to cocos/core/value-types/value-type.ts index 00efa08496..b1c16446a0 100644 --- a/cocos/core/value-types/value-type.js +++ b/cocos/core/value-types/value-type.ts @@ -32,26 +32,23 @@ import * as js from '../utils/js'; * @class ValueType * */ -export default class ValueType { +export class ValueType { /** * !#en This method returns an exact copy of current value. * !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。 * @method clone - * @return {ValueType} */ - clone () { + public clone (): this { cc.errorID('0100', js.getClassName(this) + '.clone'); - return null; + return this; } /** * !#en Compares this object with the other one. * !#zh 当前对象是否等于指定对象。 - * @method equals - * @param {ValueType} other - * @return {Boolean} + * @param other */ - equals (other) { + public equals (other: this) { cc.errorID('0100', js.getClassName(this) + '.equals'); return false; } @@ -63,12 +60,11 @@ export default class ValueType { * !#zh * 线性插值。
* 当 ratio = 0 时返回自身,ratio = 1 时返回目标,ratio = 0.5 返回自身和目标的平均值。。 - * @method lerp - * @param {ValueType} to - the to value - * @param {number} ratio - the interpolation coefficient - * @return {ValueType} + * @param to - the to value + * @param ratio - the interpolation coefficient + * @returns */ - lerp (to, ratio) { + public lerp (to: this, ratio: this) { cc.errorID('0100', js.getClassName(this) + '.lerp'); return this.clone(); } @@ -78,20 +74,17 @@ export default class ValueType { * Copys all the properties from another given object to this value. * !#zh * 从其它对象把所有属性复制到当前对象。 - * @method set - * @param {ValueType} source - the source to copy + * @param source - the source to copy */ - set (source) { + public set (source: this) { cc.errorID('0100', js.getClassName(this) + '.set'); } /** * !#en TODO * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} */ - toString () { + public toString () { return '' + {}; } } diff --git a/cocos/core/value-types/vec2.js b/cocos/core/value-types/vec2.js index f577484673..07f4cce5f0 100644 --- a/cocos/core/value-types/vec2.js +++ b/cocos/core/value-types/vec2.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; + import { ValueType } from './value-type'; import CCClass from '../data/class'; import {vec2} from '../vmath'; import {clampf} from '../utils/misc'; @@ -664,4 +664,4 @@ cc.Vec2 = Vec2; */ cc.v2 = function v2 (x, y) { return new Vec2(x, y); -}; \ No newline at end of file +}; diff --git a/cocos/core/value-types/vec3.js b/cocos/core/value-types/vec3.js index b11afc79e7..5c0a11c981 100644 --- a/cocos/core/value-types/vec3.js +++ b/cocos/core/value-types/vec3.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; import {vec3} from '../vmath'; import {clampf} from '../utils/misc'; @@ -469,4 +469,4 @@ cc.Vec3 = Vec3; */ cc.v3 = function v3 (x, y, z) { return new Vec3(x, y, z); -}; \ No newline at end of file +}; diff --git a/cocos/core/value-types/vec4.js b/cocos/core/value-types/vec4.js index 71de353c27..3402a7ba87 100644 --- a/cocos/core/value-types/vec4.js +++ b/cocos/core/value-types/vec4.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import ValueType from './value-type'; +import { ValueType } from './value-type'; import CCClass from '../data/class'; import {vec4} from '../vmath'; import {clampf} from '../utils/misc'; @@ -500,4 +500,4 @@ cc.Vec4 = Vec4; */ cc.v4 = function v4 (x, y, z, w) { return new Vec4(x, y, z, w); -}; \ No newline at end of file +}; diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 6e72fb3e4f..9f01b5b666 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -17,7 +17,6 @@ export class Camera { private _scene: RenderScene; private _name: string; - private _node: Node; private _proj: CameraProjection; private _width: number; private _height: number; @@ -36,11 +35,11 @@ export class Camera { private _matViewProj: mat4 = new Mat4(); private _matViewProjInv: mat4 = new Mat4(); private _frustum: frustum = new frustum(); + private _node: Node | null = null; constructor (scene: RenderScene, name: string) { this._scene = scene; this._name = name; - this._node = scene.createNode({ name: name + 'Node', isStatic: false }); this._proj = CameraProjection.PERSPECTIVE; const win = scene.root.mainWindow; @@ -70,6 +69,7 @@ export class Camera { } public update () { + if (!this._node) { return; } // view matrix this._node.getWorldRT(this._matView); mat4.invert(this._matView, this._matView); diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 2915cc3ed2..5b051de5ef 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -33,28 +33,28 @@ class Node extends BaseNode { } // local transform @property - public _lpos = new Vec3(); + protected _lpos = new Vec3(); @property - public _lrot = new Quat(); + protected _lrot = new Quat(); @property - public _lscale = new Vec3(1, 1, 1); + protected _lscale = new Vec3(1, 1, 1); @property - public _layer = Layers.Default; // the layer this node belongs to + protected _layer = Layers.Default; // the layer this node belongs to @property - public _euler = new Vec3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. + protected _euler = new Vec3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. // world transform - public _pos = new Vec3(); - public _rot = new Quat(); - public _scale = new Vec3(1, 1, 1); - public _mat = new Mat4(); + protected _pos = new Vec3(); + protected _rot = new Quat(); + protected _scale = new Vec3(1, 1, 1); + protected _mat = new Mat4(); - public _dirty = false; // does the world transform need to update? - public _hasChanged = false; // has the transform changed in this frame? + protected _dirty = false; // does the world transform need to update? + protected _hasChanged = false; // has the transform changed in this frame? - public _matDirty = false; - public _eulerDirty = false; + protected _matDirty = false; + protected _eulerDirty = false; @property({ type: Vec3, From 571f7b09476c20cb0fc82670f8d20fcd748aac25 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 10 Jan 2019 21:03:03 +0800 Subject: [PATCH 100/267] camera component test scene --- cocos/pipeline/render-pipeline.ts | 2 +- cocos/renderer/scene/camera.ts | 5 ++--- cocos/scene-graph/node.ts | 18 +++++++++--------- playground/simple.html | 21 ++++++++++++--------- 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index c77795a958..20d27a0cd2 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -328,7 +328,7 @@ export abstract class RenderPipeline { mat4.array(_mat4Array, camera.matViewProjInv); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); - vec3.array(_vec4Array, camera.position); + vec3.array(_vec4Array, camera.node && camera.node.getPosition()); _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 9f01b5b666..acbeb0a130 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -223,7 +223,6 @@ export class Camera { */ public screenPointToRay (x: number, y: number, out: ray): ray { out = out || ray.create(); - this.update(); const cx = this._viewport.x * this._width; const cy = this._viewport.y * this._height; @@ -236,7 +235,7 @@ export class Camera { if (this._proj === CameraProjection.PERSPECTIVE) { // camera origin - this._node.getWorldPosition(v_b); + if (this._node) { this._node.getWorldPosition(v_b); } } else { // near plane intersection vec3.set(v_b, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); @@ -267,7 +266,7 @@ export class Camera { vec3.transformMat4(out, out, this._matViewProjInv); // lerp to depth z - this._node.getWorldPosition(v_a); + if (this._node) { this._node.getWorldPosition(v_a); } vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z)); } else { diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 5b051de5ef..94ee9641a8 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -297,7 +297,7 @@ class Node extends BaseNode { * @param out the receiving vector * @returns the resulting vector */ - public getPosition (out: Vec3): Vec3 { + public getPosition (out?: Vec3): Vec3 { if (out) { return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); } else { @@ -346,7 +346,7 @@ class Node extends BaseNode { * @param out - the receiving quaternion * @returns the resulting quaternion */ - public getRotation (out: Quat): Quat { + public getRotation (out?: Quat): Quat { if (out) { return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w); } else { @@ -377,7 +377,7 @@ class Node extends BaseNode { * @param out - the receiving vector * @returns the resulting vector */ - public getScale (out: Vec3): Vec3 { + public getScale (out?: Vec3): Vec3 { if (out) { return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); } else { @@ -417,7 +417,7 @@ class Node extends BaseNode { * @param out - the receiving vector * @returns the resulting vector */ - public getWorldPosition (out: Vec3): Vec3 { + public getWorldPosition (out?: Vec3): Vec3 { this.updateWorldTransform(); if (out) { return vec3.copy(out, this._pos); @@ -477,7 +477,7 @@ class Node extends BaseNode { * @param out - the receiving quaternion * @returns the resulting quaternion */ - public getWorldRotation (out: Quat): Quat { + public getWorldRotation (out?: Quat): Quat { this.updateWorldTransform(); if (out) { return quat.copy(out, this._rot); @@ -514,7 +514,7 @@ class Node extends BaseNode { * @param out - the receiving vector * @returns the resulting vector */ - public getWorldScale (out: Vec3): Vec3 { + public getWorldScale (out?: Vec3): Vec3 { this.updateWorldTransform(); if (out) { return vec3.copy(out, this._scale); @@ -528,7 +528,7 @@ class Node extends BaseNode { * @param out - the receiving matrix * @returns the - resulting matrix */ - public getWorldMatrix (out: Mat4): Mat4 { + public getWorldMatrix (out?: Mat4): Mat4 { this.updateWorldTransformFull(); if (out) { return mat4.copy(out, this._mat); @@ -542,7 +542,7 @@ class Node extends BaseNode { * @param out - the receiving matrix * @returns the - resulting matrix */ - public getWorldRS (out: Mat4): Mat4 { + public getWorldRS (out?: Mat4): Mat4 { this.updateWorldTransformFull(); if (out) { mat4.copy(out, this._mat); @@ -558,7 +558,7 @@ class Node extends BaseNode { * @param out - the receiving matrix * @returns the - resulting matrix */ - public getWorldRT (out: Mat4): Mat4 { + public getWorldRT (out?: Mat4): Mat4 { this.updateWorldTransform(); if (!out) { out = new Mat4(); diff --git a/playground/simple.html b/playground/simple.html index 718538365e..d54ca1a78b 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -55,11 +55,13 @@ */ let root = cc.director.root; - let scene = root.createScene({ - name: "testScene", - }); + let scene = new cc.Scene(); + let cameraNode = new cc.Node(); + cameraNode.parent = scene; + let camComp = cameraNode.addComponent(cc.CameraComponent); let mainWindow = root.mainWindow; + cc.director.runSceneImmediate(scene); let view = root.createView({ name: "defaultView", @@ -69,12 +71,14 @@ width: mainWindow.width, height: mainWindow.height, }); - view.attach(scene.mainCamera); + view.attach(camComp._camera); - let camera = scene.mainCamera; - camera.position = { x: 0.0, y: 0.0, z: 3.0 }; - camera.direction = { x: 0.0, y: 0.0, z: -1.0 }; - camera.update(); + + + // let camera = scene.mainCamera; + // camera.position = { x: 0.0, y: 0.0, z: 3.0 }; + // camera.direction = { x: 0.0, y: 0.0, z: -1.0 }; + // camera.update(); //todo initialization /* @@ -106,7 +110,6 @@ mtl.setProperty('emissive', color); /**/ // model.material = mtl; - //cc.director.runSceneImmediate(scene); } cc.game.run({ id: 'canvas' }, onStart); From b50a21dcf7de416634d04850b3d7273da336c047 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 21:18:03 +0800 Subject: [PATCH 101/267] commit modified files --- cocos/pipeline/forward/forward-flow.ts | 5 ++--- cocos/pipeline/forward/test-model-stage.ts | 2 +- cocos/renderer/scene/camera.ts | 9 +-------- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index 0ecac2ee0f..7236dd4210 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -26,20 +26,19 @@ export class ForwardFlow extends RenderFlow { if (!mainWindow || !mainWindow.framebuffer) { return false; } - + /* this.createStage(ForwardStage, { name: 'ForwardStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); + */ - /* this.createStage(TestModelStage, { name: 'TestModelStage', priority: ForwardStagePriority.FORWARD, framebuffer: mainWindow.framebuffer, }); - */ /* this.createStage(TestStage, { diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts index f4119759c1..fc07b75916 100644 --- a/cocos/pipeline/forward/test-model-stage.ts +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -13,7 +13,7 @@ import { RenderView } from '../render-view'; export class TestModelStage extends RenderStage { - private _material: Material = new Material(); + private _material: Material = new Material("testMtrl"); private _model: Model; private _scene: Scene; private _init: boolean = false; diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 4bd1d8ee9a..4951c4786b 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -17,10 +17,6 @@ export class Camera { private _scene: RenderScene; private _name: string; -<<<<<<< HEAD - private _node: Node | null = null; -======= ->>>>>>> fa7ae3c2aa398dd9c26c8dea81cf8a2016083df8 private _proj: CameraProjection; private _width: number; private _height: number; @@ -39,11 +35,8 @@ export class Camera { private _matViewProj: mat4 = new Mat4(); private _matViewProjInv: mat4 = new Mat4(); private _frustum: frustum = new frustum(); -<<<<<<< HEAD - private _visibility: number; -======= private _node: Node | null = null; ->>>>>>> fa7ae3c2aa398dd9c26c8dea81cf8a2016083df8 + private _visibility: number; constructor (scene: RenderScene, name: string) { this._scene = scene; From 2b0a3321524e922d41fc695cdabaa9c9d012d3a3 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 10 Jan 2019 21:18:29 +0800 Subject: [PATCH 102/267] commit file --- playground/simple.html | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/playground/simple.html b/playground/simple.html index 6addcf5b12..decadec06e 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -46,21 +46,22 @@ let material = new cc.Material(); material.effectName = 'test'; // parsed-effect file is embedded in cocos/3d/builtin/effects.js material.setProperty('u_color', cc.color('#ff0000')); + material.passes[0].update(); let modelCom = scene.addComponent('cc.ModelComponent'); modelCom.material = material; - modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box({length: 1, width: 1, height: 1})); scene.setRotationFromEuler(45, 45, 45); scene._rot = scene._lrot; */ let root = cc.director.root; + let mainWindow = root.mainWindow; + let scene = root.createScene({ name: "testScene", }); - - let mainWindow = root.mainWindow; - + let view = root.createView({ name: "defaultView", window: mainWindow, From 5d46714c3d20642d1cbb9da66fca04b13bbc72a5 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 10 Jan 2019 21:43:13 +0800 Subject: [PATCH 103/267] camera with view --- cocos/3d/framework/camera-component.ts | 23 +++++----- cocos/core/root.ts | 4 ++ cocos/renderer/scene/camera.ts | 59 +++++++++++++++++++------- cocos/renderer/scene/render-scene.ts | 16 +++---- playground/simple.html | 12 ------ 5 files changed, 64 insertions(+), 50 deletions(-) diff --git a/cocos/3d/framework/camera-component.ts b/cocos/3d/framework/camera-component.ts index e23e1c7d11..e41313ff37 100644 --- a/cocos/3d/framework/camera-component.ts +++ b/cocos/3d/framework/camera-component.ts @@ -99,6 +99,8 @@ export class CameraComponent extends Component { protected _clearFlags = CameraClearFlag.SOLID_COLOR; @property protected _rect = new Rect(0, 0, 1, 1); + @property + protected _targetDisplay = 0; protected _camera: Camera | null = null; @@ -279,23 +281,20 @@ export class CameraComponent extends Component { if (this._camera) { this._camera.viewport = val; } } + @property + get targetDisplay () { + return this._targetDisplay; + } + set targetDisplay (val) { + this._targetDisplay = val; + } + public onLoad () { } public onEnable () { - this._camera = this._getRenderScene().createCamera(this.name); - this._camera.node = this.node; - this.projection = this._projection; - this.fov = this._fov; - this.orthoHeight = this._orthoHeight; - this.near = this._near; - this.far = this._far; - this.color = this._color; - this.depth = this._depth; - this.stencil = this._stencil; - this.clearFlags = this._clearFlags; - this.rect = this._rect; + this._camera = this._getRenderScene().createCamera(this); } public onDisable () { diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 4bf75dd063..3896c88d95 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -25,6 +25,10 @@ export class Root { return this._mainWindow; } + public get windows (): GFXWindow[] { + return this._windows; + } + public get pipeline (): RenderPipeline | null { return this._pipeline; } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index acbeb0a130..6af66580ac 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,13 +1,30 @@ import { frustum, ray } from '../../3d/geom-utils'; -import { Mat4, Rect } from '../../core/value-types'; -import { color4, lerp, mat4, vec3 } from '../../core/vmath'; +import { Color, Mat4, Rect } from '../../core/value-types'; +import { color4, lerp, mat4, toRadian, vec3 } from '../../core/vmath'; import { GFXClearFlag, IGFXColor } from '../../gfx/define'; +import { RenderView, RenderViewPriority } from '../../pipeline/render-view'; import { Node } from '../../scene-graph/node'; import { RenderScene } from './render-scene'; export enum CameraProjection { - PERSPECTIVE, ORTHO, + PERSPECTIVE, +} + +export interface ICameraInfo { + name: string; + node: Node; + projection: number; + fov: number; + orthoHeight: number; + near: number; + far: number; + color: Color; + depth: number; + stencil: number; + clearFlags: GFXClearFlag; + rect: Rect; + targetDisplay: number; } const v_a = cc.v3(); @@ -36,30 +53,42 @@ export class Camera { private _matViewProjInv: mat4 = new Mat4(); private _frustum: frustum = new frustum(); private _node: Node | null = null; + private _view: RenderView | null = null; - constructor (scene: RenderScene, name: string) { + constructor (scene: RenderScene, info: ICameraInfo) { this._scene = scene; this._name = name; - this._proj = CameraProjection.PERSPECTIVE; + this._node = info.node; + this._proj = info.projection; + this._fov = toRadian(info.fov); + this._orthoHeight = info.orthoHeight; + this._nearClip = info.near; + this._farClip = info.far; + this._viewport = info.rect; - const win = scene.root.mainWindow; + const c = info.color; + color4.set(this._clearColor, c.r / 255, c.g / 255, c.b / 255, c.a / 255); + this._clearDepth = info.depth; + this._clearStencil = info.stencil; + this._clearFlag = info.clearFlags; + + const win = scene.root.windows[info.targetDisplay - 1] || scene.root.mainWindow; if (win) { this._width = win.width; this._height = win.height; + const view = this._view = scene.root.createView({ + name: `${name}View`, + window: win, + priority: RenderViewPriority.GENERAL, + width: win.width, + height: win.height, + }); + if (view) { view.attach(this); } } else { this._width = 1; this._height = 1; } - this._aspect = this._width / this._height; - this._orthoHeight = 10; - this._fov = Math.PI / 4; - this._nearClip = 1.0; - this._farClip = 10000.0; - - this._clearDepth = 1; - this._clearStencil = 0; - this._clearFlag = GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL; } public resize (width: number, height: number) { diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index bc62661518..52fe7ba324 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,6 +1,7 @@ -import { Root, _createSceneFun } from '../../core/root'; +import { _createSceneFun, Root } from '../../core/root'; +import { IGFXColor } from '../../gfx/define'; import { Node } from '../../scene-graph/node'; -import { Camera } from './camera'; +import { Camera, ICameraInfo } from './camera'; import Light from './light'; import Model from './model'; @@ -28,10 +29,6 @@ export class RenderScene { return this._cameras; } - public get mainCamera (): Camera | null { - return this._mainCamera; - } - public get lights (): Light[] { return this._lights; } @@ -48,7 +45,6 @@ export class RenderScene { private _name: string = ''; private _nodes: Map = new Map(); private _cameras: Camera[] = []; - private _mainCamera: Camera | null = null; private _lights: Light[] = []; private _models: Model[] = []; private _modelId: number = 0; @@ -59,7 +55,6 @@ export class RenderScene { public initialize (info: IRenderSceneInfo): boolean { this._name = info.name; - this._mainCamera = this.createCamera('mainCamera'); return true; } @@ -94,8 +89,8 @@ export class RenderScene { } } - public createCamera (name: string): Camera { - const camera = new Camera(this, name); + public createCamera (info: ICameraInfo): Camera { + const camera = new Camera(this, info); this._cameras.push(camera); return camera; } @@ -111,7 +106,6 @@ export class RenderScene { public destroyCameras () { this._cameras = []; - this._mainCamera = null; } public getCamera (name: string): Camera | null { diff --git a/playground/simple.html b/playground/simple.html index d54ca1a78b..02559d6886 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -63,18 +63,6 @@ let mainWindow = root.mainWindow; cc.director.runSceneImmediate(scene); - let view = root.createView({ - name: "defaultView", - window: mainWindow, - //priority: cc.RenderViewPriority.GENERAL, - priority: 100, - width: mainWindow.width, - height: mainWindow.height, - }); - view.attach(camComp._camera); - - - // let camera = scene.mainCamera; // camera.position = { x: 0.0, y: 0.0, z: 3.0 }; // camera.direction = { x: 0.0, y: 0.0, z: -1.0 }; From 9520e3dc5d0c49c1578735c7a48438230823411b Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 11 Jan 2019 10:05:15 +0800 Subject: [PATCH 104/267] target display on camera-component --- cocos/3d/framework/camera-component.ts | 12 +--- cocos/3d/primitive/box.ts | 47 +++++++------- cocos/3d/primitive/defines.ts | 6 -- cocos/pipeline/render-view.ts | 18 +++--- cocos/renderer/scene/camera.ts | 39 ++++++------ playground/simple.html | 85 ++++++-------------------- 6 files changed, 80 insertions(+), 127 deletions(-) diff --git a/cocos/3d/framework/camera-component.ts b/cocos/3d/framework/camera-component.ts index e41313ff37..1ff29feb59 100644 --- a/cocos/3d/framework/camera-component.ts +++ b/cocos/3d/framework/camera-component.ts @@ -123,12 +123,7 @@ export class CameraComponent extends Component { set projection (val) { this._projection = val; - - let type = CameraProjection.PERSPECTIVE; - if (this._projection === ProjectionType.ORTHO) { - type = CameraProjection.ORTHO; - } - if (this._camera) { this._camera.projectionType = type; } + if (this._camera) { this._camera.projectionType = val; } } /** @@ -226,9 +221,7 @@ export class CameraComponent extends Component { set depth (val) { this._depth = val; - if (this._camera) { - this._camera.clearDepth = val; - } + if (this._camera) { this._camera.clearDepth = val; } } /** @@ -287,6 +280,7 @@ export class CameraComponent extends Component { } set targetDisplay (val) { this._targetDisplay = val; + if (this._camera) { this._camera.changeTargetDisplay(val); } } public onLoad () { diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts index 8d4661e587..19e604581f 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/3d/primitive/box.ts @@ -1,22 +1,23 @@ +import { Vec3 } from '../../core/value-types'; import { vec3 } from '../../core/vmath'; import { GFXPrimitiveMode } from '../../gfx/define'; -import { IGeometry, IGeometryOptions, normalizeGeometryOptions } from './defines'; +import { IGeometry, IGeometryOptions } from './defines'; interface IBoxOptions extends IGeometryOptions { /** * Box extent on X-axis. */ - width: number; + width?: number; /** * Box extent on Y-axis. */ - height: number; + height?: number; /** * Box extent on Z-axis. */ - length: number; + length?: number; /** * Segment count on X-axis. @@ -39,15 +40,15 @@ interface IBoxOptions extends IGeometryOptions { * but may emplaced through `center` option). * @param options Options. */ -export default function box (options: IBoxOptions): IGeometry { - normalizeGeometryOptions(options); +export default function box (options?: IBoxOptions): IGeometry { + options = options || {}; const ws = options.widthSegments || 1; const hs = options.heightSegments || 1; const ls = options.lengthSegments || 1; - const hw = options.width / 2; - const hh = options.height / 2; - const hl = options.length / 2; + const hw = (options.width || 1) / 2; + const hh = (options.height || 1) / 2; + const hl = (options.length || 1) / 2; const corners = [ vec3.set(c0, -hw, -hh, hl), @@ -82,8 +83,8 @@ export default function box (options: IBoxOptions): IGeometry { const normals: number[] = []; const uvs: number[] = []; const indices: number[] = []; - const minPos = vec3.create(-hw, -hh, -hl); - const maxPos = vec3.create(hw, hh, hl); + const minPos = new Vec3(-hw, -hh, -hl); + const maxPos = new Vec3(hw, hh, hl); const boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl); function _buildPlane (side: number, uSegments: number, vSegments: number) { @@ -142,15 +143,15 @@ export default function box (options: IBoxOptions): IGeometry { }; } -const temp1 = vec3.create(0, 0, 0); -const temp2 = vec3.create(0, 0, 0); -const temp3 = vec3.create(0, 0, 0); -const r = vec3.create(0, 0, 0); -const c0 = vec3.create(0, 0, 0); -const c1 = vec3.create(0, 0, 0); -const c2 = vec3.create(0, 0, 0); -const c3 = vec3.create(0, 0, 0); -const c4 = vec3.create(0, 0, 0); -const c5 = vec3.create(0, 0, 0); -const c6 = vec3.create(0, 0, 0); -const c7 = vec3.create(0, 0, 0); +const temp1 = new Vec3(); +const temp2 = new Vec3(); +const temp3 = new Vec3(); +const r = new Vec3(); +const c0 = new Vec3(); +const c1 = new Vec3(); +const c2 = new Vec3(); +const c3 = new Vec3(); +const c4 = new Vec3(); +const c5 = new Vec3(); +const c6 = new Vec3(); +const c7 = new Vec3(); diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts index c189b4c6d2..d6b6f43e20 100644 --- a/cocos/3d/primitive/defines.ts +++ b/cocos/3d/primitive/defines.ts @@ -7,12 +7,6 @@ export interface IGeometryOptions { includeNormal?: boolean; } -export function normalizeGeometryOptions (options: IGeometryOptions) { - options.includeNormal = options.includeNormal === undefined ? - true : options.includeNormal; - return options; -} - export interface IGeometry { /** * Topology of the geometry vertices. diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index 7f5978ca43..f413551b7f 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -15,30 +15,34 @@ export interface IRenderViewInfo { export class RenderView { - public get name (): string { + public get name () { return this._name; } - public get window (): GFXWindow | null { + public get window () { return this._window; } - public get priority (): number { + public set window (val) { + this._window = val; + } + + public get priority () { return this._priority; } - public set visibility (vis: number) { + public set visibility (vis) { this._visibility = vis; } - public get visibility (): number { + public get visibility () { return this._visibility; } - public get camera (): Camera { + public get camera () { return this._camera as Camera; } - public get scene (): RenderScene { + public get scene () { return this._scene as RenderScene; } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index b7d61a63f3..22ede78912 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -73,23 +73,8 @@ export class Camera { this._clearStencil = info.stencil; this._clearFlag = info.clearFlags; - const win = scene.root.windows[info.targetDisplay - 1] || scene.root.mainWindow; - if (win) { - this._width = win.width; - this._height = win.height; - const view = this._view = scene.root.createView({ - name: `${name}View`, - window: win, - priority: RenderViewPriority.GENERAL, - }); - if (view) { view.attach(this); } - } else { - this._width = 1; - this._height = 1; - } - this._aspect = this._width / this._height; - - this._visibility = 0; + this._aspect = this._width = this._height = 1; + this.changeTargetDisplay(info.targetDisplay); } public resize (width: number, height: number) { @@ -282,6 +267,26 @@ export class Camera { return ray.fromPoints(out, v_b, v_a); } + public changeTargetDisplay (val: number) { + const scene = this._scene; + const win = scene.root.windows[val - 1] || scene.root.mainWindow; + if (win) { + this._width = win.width; + this._height = win.height; + if (!this._view) { + this._view = scene.root.createView({ + name: this._name, + window: win, + priority: RenderViewPriority.GENERAL, + }); + if (this._view) { this._view.attach(this); } + } else { + this._view.window = win; + } + } + this._aspect = this._width / this._height; + } + /** * transform a screen position to world space */ diff --git a/playground/simple.html b/playground/simple.html index af943961a5..6df1de6b94 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -28,8 +28,14 @@ - From f717eefa6d54c642b87b0c4b650bcadc24663804 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Fri, 11 Jan 2019 14:26:12 +0800 Subject: [PATCH 105/267] add default vertex name --- cocos/3d/builtin/effects.js | 4 ++-- cocos/gfx/define.ts | 21 +++++++++++++++++++++ cocos/renderer/utils.js | 10 +++++----- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index a177314e50..3329793c89 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -8,12 +8,12 @@ export default [ "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", "vert": ` attribute vec3 a_position; - attribute vec2 a_uv0; + attribute vec2 a_texCoord; uniform mat4 cc_matWorld; varying vec2 v_texCoord; void main() { gl_Position = cc_matWorld*vec4(a_position, 1.0); - v_texCoord = a_uv0; + v_texCoord = a_texCoord; } `, "frag": ` diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 329b970485..264daa001f 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -65,6 +65,27 @@ export class GFXObject { } } +export enum GFXAttributeName { + ATTR_POSITION = 'a_position', + ATTR_NORMAL = 'a_normal', + ATTR_TANGENT = 'a_tangent', + ATTR_BITANGENT = 'a_bitangent', + ATTR_WEIGHTS = 'a_weights', + ATTR_JOINTS = 'a_joints', + ATTR_COLOR = 'a_color', + ATTR_COLOR1 = 'a_color1', + ATTR_COLOR2 = 'a_color2', + ATTR_TEX_COORD = 'a_texCoord', + ATTR_TEX_COORD1 = 'a_texCoord1', + ATTR_TEX_COORD2 = 'a_texCoord2', + ATTR_TEX_COORD3 = 'a_texCoord3', + ATTR_TEX_COORD4 = 'a_texCoord4', + ATTR_TEX_COORD5 = 'a_texCoord5', + ATTR_TEX_COORD6 = 'a_texCoord6', + ATTR_TEX_COORD7 = 'a_texCoord7', + ATTR_TEX_COORD8 = 'a_texCoord8', +} + export enum GFXType { UNKNOWN, BOOL, diff --git a/cocos/renderer/utils.js b/cocos/renderer/utils.js index a3821a8693..cc14870639 100644 --- a/cocos/renderer/utils.js +++ b/cocos/renderer/utils.js @@ -2,7 +2,7 @@ import gfx from './gfx'; import InputAssembler from './core/input-assembler'; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat } from '../gfx/define'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat, GFXAttributeName } from '../gfx/define'; /** * @param {gfx.Device} device @@ -32,15 +32,15 @@ export function createIA(device, data) { } let vfmt = []; - vfmt.push({ name: gfx.ATTR_POSITION, format: GFXFormat.RGB32F }); + vfmt.push({ name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }); if (data.normals) { - vfmt.push({ name: gfx.ATTR_NORMAL, format: GFXFormat.RGB32F }); + vfmt.push({ name: GFXAttributeName.ATTR_NORMAL, format: GFXFormat.RGB32F }); } if (data.uvs) { - vfmt.push({ name: gfx.ATTR_UV0, format: GFXFormat.RG32F }); + vfmt.push({ name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RG32F }); } if (data.colors) { - vfmt.push({ name: gfx.ATTR_COLOR, format: GFXFormat.RGB32F }); + vfmt.push({ name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGB32F }); } let vb = cc.director.root.device.createBuffer({ From 4110f91946a15d58b0e8a86e136b7f5a4c510507 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 11 Jan 2019 11:05:05 +0800 Subject: [PATCH 106/267] editor adapt --- cocos/3d/assets/material.ts | 4 + cocos/3d/assets/mesh.ts | 1 + cocos/3d/framework/camera-component.ts | 25 ++++++- cocos/3d/framework/model-component.js | 6 +- cocos/assets/raw-asset.d.ts | 1 + cocos/core/vmath/color4.ts | 2 +- cocos/gfx/define.ts | 1 + cocos/gfx/index.ts | 3 + cocos/gfx/webgl/webgl-commands.ts | 2 +- cocos/pipeline/forward/forward-flow.ts | 2 +- cocos/pipeline/forward/forward-stage.ts | 3 +- cocos/pipeline/forward/test-model-stage.ts | 4 +- cocos/pipeline/render-pipeline.ts | 29 ++++---- cocos/pipeline/render-queue.ts | 2 +- cocos/renderer/core/effect.ts | 1 + cocos/renderer/core/pass.ts | 6 +- cocos/renderer/index.js | 4 +- cocos/renderer/models/line-batch-model.js | 2 +- cocos/renderer/models/particle-batch-model.js | 2 +- cocos/renderer/models/skinning-model.js | 4 +- cocos/renderer/models/sprite-batch-model.js | 2 +- cocos/renderer/scene/camera.ts | 70 +++++++++--------- cocos/renderer/scene/light.js | 2 +- cocos/renderer/scene/model.ts | 43 ++++++----- cocos/renderer/scene/render-scene.ts | 74 ++++++++++++++++++- cocos/renderer/scene/scene.js | 58 --------------- cocos/renderer/utils.js | 6 -- cocos/scene-graph/node.ts | 3 +- playground/simple.html | 4 +- 29 files changed, 206 insertions(+), 160 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index af1138992f..578d4f8e46 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -74,6 +74,10 @@ export class Material extends Asset { @property set technique (val: number) { this._techIdx = val; + if (val !== this._techIdx) { + this._techIdx = val; + this.update(); + } } get technique () { return this._techIdx; diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 5ba28687e9..d2fb82746b 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -266,6 +266,7 @@ export interface IPrimitive { export interface IRenderingSubmesh { inputAssembler: GFXInputAssembler; primitiveMode: GFXPrimitiveMode; + doubleSided?: boolean; } export class RenderingMesh { diff --git a/cocos/3d/framework/camera-component.ts b/cocos/3d/framework/camera-component.ts index 1ff29feb59..e202ce06bb 100644 --- a/cocos/3d/framework/camera-component.ts +++ b/cocos/3d/framework/camera-component.ts @@ -22,12 +22,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +import { ray } from '../../3d/geom-utils'; import { Component } from '../../components/component'; import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; -import { Enum, Rect } from '../../core/value-types'; +import { Enum, Rect, Vec3 } from '../../core/value-types'; import { color4, toRadian } from '../../core/vmath'; import { GFXClearFlag } from '../../gfx/define'; -import { Camera, CameraProjection } from '../../renderer/scene/camera'; +import { Camera } from '../../renderer/scene/camera'; /** * !#en The light source type @@ -61,7 +62,7 @@ const CameraClearFlag = Enum({ SKYBOX: GFXClearFlag.SKYBOX | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, SOLID_COLOR: GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, DEPTH_ONLY: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, - DONT_CLEAR: 0, + DONT_CLEAR: GFXClearFlag.NONE, }); /** @@ -298,4 +299,22 @@ export class CameraComponent extends Component { public onDestroy () { } + + public screenPointToRay (x: number, y: number, out?: ray) { + if (!out) { out = ray.create(); } + if (this._camera) { this._camera.screenPointToRay(out, x, y); } + return out; + } + + public worldToScreen (worldPos: Vec3, out?: Vec3) { + if (!out) { out = new Vec3(); } + if (this._camera) { this._camera.worldToScreen(out, worldPos); } + return out; + } + + public screenToWorld (screenPos: Vec3, out?: Vec3) { + if (!out) { out = this.node.getWorldPosition(); } + if (this._camera) { this._camera.screenToWorld(out, screenPos); } + return out; + } } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index c55f399e76..7735de0780 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import Model from '../../renderer/scene/model'; +import { Model } from '../../renderer/scene/model'; import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator'; import { Mesh } from '../assets/mesh'; import Enum from '../../core/value-types/enum'; @@ -116,7 +116,6 @@ export default class ModelComponent extends RenderableComponent { set mesh(val) { this._mesh = val; - this._updateModels(); } /** @@ -185,8 +184,7 @@ export default class ModelComponent extends RenderableComponent { } _updateModels() { - if (!this.enabled) - return; + if (!this.enabled) return; let meshCount = this._mesh ? this._mesh.subMeshCount : 0; for (let i = 0; i < meshCount; ++i) { diff --git a/cocos/assets/raw-asset.d.ts b/cocos/assets/raw-asset.d.ts index 4c5fcf5fb0..a7d7b2e319 100644 --- a/cocos/assets/raw-asset.d.ts +++ b/cocos/assets/raw-asset.d.ts @@ -28,5 +28,6 @@ import { CCObject } from '../core/data/object'; export class RawAsset extends CCObject { _uuid: string; + public constructor(); static isRawAssetType(ctor: Function): boolean; } diff --git a/cocos/core/vmath/color4.ts b/cocos/core/vmath/color4.ts index 9438446489..13e1007529 100644 --- a/cocos/core/vmath/color4.ts +++ b/cocos/core/vmath/color4.ts @@ -222,7 +222,7 @@ class color4 { * @param a - The color. * @return out. */ - public static array (out: number[], a: color4) { + public static array> (out: Out, a: color4) { const scale = (a instanceof cc.Color || a.a > 1) ? 1 / 255 : 1; out[0] = a.r * scale; out[1] = a.g * scale; diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index ea3df1221a..a9ba2b7693 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -502,6 +502,7 @@ export interface IGFXColor { } export enum GFXClearFlag { + NONE = 0, COLOR = 1, DEPTH = 2, STENCIL = 4, diff --git a/cocos/gfx/index.ts b/cocos/gfx/index.ts index c29b229b47..f113ba14e1 100644 --- a/cocos/gfx/index.ts +++ b/cocos/gfx/index.ts @@ -1,5 +1,6 @@ import { GFXBuffer } from './buffer'; import { GFXCommandBuffer } from './command-buffer'; +import * as GFXDefines from './define'; import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; import { GFXInputAssembler } from './input-assembler'; @@ -27,3 +28,5 @@ cc.GFXPipelineState = GFXPipelineState; cc.GFXCommandBuffer = GFXCommandBuffer; cc.GFXQueue = GFXQueue; cc.WebGLGFXDevice = WebGLGFXDevice; + +Object.assign(cc, GFXDefines); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index bc49dfbd71..3e4ea40130 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,7 +1,7 @@ import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, GFXCullMode, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, GFXMemoryUsageBit, GFXShaderType, GFXTextureFlagBit, GFXTextureLayout, GFXTextureViewType, - GFXType, IGFXColor, IGFXRect, WebGLEXT} from '../define'; + GFXType, IGFXColor, IGFXRect, WebGLEXT } from '../define'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer, diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index e2f7f7050e..0ecac2ee0f 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -26,7 +26,7 @@ export class ForwardFlow extends RenderFlow { if (!mainWindow || !mainWindow.framebuffer) { return false; } - + this.createStage(ForwardStage, { name: 'ForwardStage', priority: ForwardStagePriority.FORWARD, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 39a12ff049..d87308fa98 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -48,7 +48,8 @@ export class ForwardStage extends RenderStage { this._renderArea.height = camera.height; cmdBuff.begin(); - cmdBuff.beginRenderPass( this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); + cmdBuff.beginRenderPass(this._framebuffer as GFXFramebuffer, this._renderArea, + [camera.clearColor], camera.clearDepth, camera.clearStencil); cmdBuff.execute(queue.opaqueCmdBuffs); cmdBuff.execute(queue.transparentCmdBuffs); diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/forward/test-model-stage.ts index 9ce1fcd5b2..1da32b2d3a 100644 --- a/cocos/pipeline/forward/test-model-stage.ts +++ b/cocos/pipeline/forward/test-model-stage.ts @@ -2,10 +2,10 @@ 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 { GFXCommandBufferType } from '../../gfx/define'; import { GFXFramebuffer } from '../../gfx/framebuffer'; import { Camera } from '../../renderer/scene/camera'; -import Model from '../../renderer/scene/model'; +import { Model } from '../../renderer/scene/model'; import { Scene } from '../../scene-graph'; import { RenderFlow } from '../render-flow'; import { IRenderStageInfo, RenderStage } from '../render-stage'; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 1210f9300a..e379543216 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -19,8 +19,6 @@ export enum RenderPassStage { DEFAULT = 100, } -const v_camPos = cc.v3(); - export class UBOGlobal { public static TIME_OFFSET: number = 0; public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; @@ -37,16 +35,16 @@ export class UBOGlobal { public static BLOCK: GFXUniformBlock = { binding: 30, name: 'CCGlobal', members: [ - { name: 'u_time', type: GFXType.FLOAT4, count: 1 }, - { name: 'u_screenSize', type: GFXType.FLOAT4, count: 1 }, - { name: 'u_screenScale', type: GFXType.FLOAT4, count: 1 }, - { name: 'u_matView', type: GFXType.MAT4, count: 1 }, - { name: 'u_matViewInv', type: GFXType.MAT4, count: 1 }, - { name: 'u_matProj', type: GFXType.MAT4, count: 1 }, - { name: 'u_matProjInv', type: GFXType.MAT4, count: 1 }, - { name: 'u_matViewProj', type: GFXType.MAT4, count: 1 }, - { name: 'u_matViewProjInv', type: GFXType.MAT4, count: 1 }, - { name: 'u_cameraPos', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_time', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_screenSize', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_screenScale', type: GFXType.FLOAT4, count: 1 }, + { name: 'cc_matView', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matViewInv', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matProj', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matProjInv', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matViewProj', type: GFXType.MAT4, count: 1 }, + { name: 'cc_matViewProjInv', type: GFXType.MAT4, count: 1 }, + { name: 'cc_cameraPos', type: GFXType.FLOAT4, count: 1 }, ], }; @@ -164,7 +162,10 @@ export abstract class RenderPipeline { this._renderPasses.clear(); } - public createFlow (clazz: new (pipeline: RenderPipeline) => T, info: IRenderFlowInfo): RenderFlow | null { + public createFlow ( + clazz: new (pipeline: RenderPipeline) => T, + info: IRenderFlowInfo, + ): RenderFlow | null { const flow: RenderFlow = new clazz(this); if (flow.initialize(info)) { this._flows.push(flow); @@ -353,7 +354,7 @@ export abstract class RenderPipeline { model._updateTransform(); // frustum culling - if (!intersect.aabb_frustum(model.boundingShape, camera.frustum)) { + if (model.worldBounds && !intersect.aabb_frustum(model.worldBounds, camera.frustum)) { // console.log('model is not in view frustum.'); continue; } diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index a444267db0..27a14a8bb2 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -2,7 +2,7 @@ import { vec3 } from '../core/vmath'; import { GFXCommandBuffer } from '../gfx/command-buffer'; import { Pass } from '../renderer/core/pass'; import { Camera } from '../renderer/scene/camera'; -import Model from '../renderer/scene/model'; +import { Model } from '../renderer/scene/model'; const _pos: vec3 = vec3.create(); const _cameraPos: vec3 = vec3.create(); diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 8dd033de8b..7169ad0e89 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -75,6 +75,7 @@ export class Effect { const prog = getProgram(passInfo.program); passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines || {}); passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); + passInfo.globals = cc.director.root.pipeline.globalUBO; passInfo.blocks = prog.blocks; passInfo.samplers = prog.samplers; const pass = new Pass(cc.game._gfxDevice); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 691f276973..23ce092133 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -21,6 +21,7 @@ export interface IPassInfoFull extends IPassInfo { samplers: ISamplerInfo[]; shader: GFXShader; renderPass: GFXRenderPass; + globals: GFXBuffer; } const _type2fn = { @@ -154,6 +155,9 @@ 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); const sampler = device.createSampler({ @@ -258,5 +262,5 @@ export class Pass { get programName () { return this._programName; } get pipelineState () { return this._pipelineState as GFXPipelineState; } get bindingLayout () { return this._bindingLayout as GFXBindingLayout; } - get primitive(): GFXPrimitiveMode { return this._primitive; } + get primitive (): GFXPrimitiveMode { return this._primitive; } } diff --git a/cocos/renderer/index.js b/cocos/renderer/index.js index 6aa2733c53..e48d87e0b2 100644 --- a/cocos/renderer/index.js +++ b/cocos/renderer/index.js @@ -8,9 +8,9 @@ import { Effect } from './core/effect'; import InputAssembler from './core/input-assembler'; import View from './core/view'; -import Light from './scene/light'; +import { Light } from './scene/light'; import { Camera } from './scene/camera'; -import Model from './scene/model'; +import { Model } from './scene/model'; import Scene from './scene/scene'; import LineBatchModel from './models/line-batch-model'; diff --git a/cocos/renderer/models/line-batch-model.js b/cocos/renderer/models/line-batch-model.js index cd414ba457..4f531e4221 100644 --- a/cocos/renderer/models/line-batch-model.js +++ b/cocos/renderer/models/line-batch-model.js @@ -3,7 +3,7 @@ import { vec3, color3 } from '../../core/vmath'; import { RecyclePool } from '../../3d/memop'; -import Model from '../scene/model'; +import { Model } from '../scene/model'; export default class LineBatchModel extends Model { constructor() { diff --git a/cocos/renderer/models/particle-batch-model.js b/cocos/renderer/models/particle-batch-model.js index 690f1ad5a3..92b9aeed59 100644 --- a/cocos/renderer/models/particle-batch-model.js +++ b/cocos/renderer/models/particle-batch-model.js @@ -3,7 +3,7 @@ import gfx from '../gfx'; import InputAssembler from '../core/input-assembler'; -import Model from '../scene/model'; +import { Model } from '../scene/model'; function _createInputAssembler(out) { let vb = new gfx.VertexBuffer( diff --git a/cocos/renderer/models/skinning-model.js b/cocos/renderer/models/skinning-model.js index 10fc84f14b..7239ecf85e 100644 --- a/cocos/renderer/models/skinning-model.js +++ b/cocos/renderer/models/skinning-model.js @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import Model from '../scene/model'; +import { Model } from '../scene/model'; export default class SkinningModel extends Model { constructor() { @@ -18,4 +18,4 @@ export default class SkinningModel extends Model { setJointsMatrixArray(a) { this._jointsMatrixArray = a; } -} \ No newline at end of file +} diff --git a/cocos/renderer/models/sprite-batch-model.js b/cocos/renderer/models/sprite-batch-model.js index 3eabd2740d..4c4525d714 100644 --- a/cocos/renderer/models/sprite-batch-model.js +++ b/cocos/renderer/models/sprite-batch-model.js @@ -2,7 +2,7 @@ import { RecyclePool } from '../../3d/memop'; -import Model from '../scene/model'; +import { Model } from '../scene/model'; export default class SpriteBatchModel extends Model { constructor() { diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 22ede78912..299307c783 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -54,7 +54,7 @@ export class Camera { private _frustum: frustum = new frustum(); private _node: Node | null = null; private _view: RenderView | null = null; - private _visibility: number; + private _visibility: number = 0; constructor (scene: RenderScene, info: ICameraInfo) { this._scene = scene; @@ -233,43 +233,16 @@ export class Camera { return this._frustum; } - public set visibility (vis: number) { + set visibility (vis) { this._visibility = vis; } - public get visibility (): number { + get visibility () { return this._visibility; } - /** - * transform a screen position to a world space ray - */ - public screenPointToRay (x: number, y: number, out: ray): ray { - out = out || ray.create(); - - const cx = this._viewport.x * this._width; - const cy = this._viewport.y * this._height; - const cw = this._viewport.w * this._width; - const ch = this._viewport.h * this._height; - - // far plane intersection - vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); - vec3.transformMat4(v_a, v_a, this._matViewProjInv); - - if (this._proj === CameraProjection.PERSPECTIVE) { - // camera origin - if (this._node) { this._node.getWorldPosition(v_b); } - } else { - // near plane intersection - vec3.set(v_b, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); - vec3.transformMat4(v_b, v_b, this._matViewProjInv); - } - - return ray.fromPoints(out, v_b, v_a); - } - public changeTargetDisplay (val: number) { const scene = this._scene; - const win = scene.root.windows[val - 1] || scene.root.mainWindow; + const win = scene.root.windows[val] || scene.root.mainWindow; if (win) { this._width = win.width; this._height = win.height; @@ -287,14 +260,41 @@ export class Camera { this._aspect = this._width / this._height; } + /** + * transform a screen position to a world space ray + */ + public screenPointToRay (x: number, y: number, out: ray): ray { + out = out || ray.create(); + + const cx = this._viewport.x * this._width; + const cy = this._viewport.y * this._height; + const cw = this._viewport.width * this._width; + const ch = this._viewport.height * this._height; + + // far plane intersection + vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, 1); + vec3.transformMat4(v_a, v_a, this._matViewProjInv); + + if (this._proj === CameraProjection.PERSPECTIVE) { + // camera origin + if (this._node) { this._node.getWorldPosition(v_b); } + } else { + // near plane intersection + vec3.set(v_b, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, -1); + vec3.transformMat4(v_b, v_b, this._matViewProjInv); + } + + return ray.fromPoints(out, v_b, v_a); + } + /** * transform a screen position to world space */ public screenToWorld (out: vec3, screenPos: vec3): vec3 { const cx = this._viewport.x * this._width; const cy = this._viewport.y * this._height; - const cw = this._viewport.w * this._width; - const ch = this._viewport.h * this._height; + const cw = this._viewport.width * this._width; + const ch = this._viewport.height * this._height; if (this._proj === CameraProjection.PERSPECTIVE) { // calculate screen pos in far clip plane @@ -331,8 +331,8 @@ export class Camera { public worldToScreen (out: vec3, worldPos: vec3): vec3 { const cx = this._viewport.x * this._width; const cy = this._viewport.y * this._height; - const cw = this._viewport.w * this._width; - const ch = this._viewport.h * this._height; + const cw = this._viewport.width * this._width; + const ch = this._viewport.height * this._height; vec3.transformMat4(out, worldPos, this.matViewProjInv); out.x = cx + (out.x + 1) * 0.5 * cw; diff --git a/cocos/renderer/scene/light.js b/cocos/renderer/scene/light.js index a9272f98d9..1236a98104 100644 --- a/cocos/renderer/scene/light.js +++ b/cocos/renderer/scene/light.js @@ -47,7 +47,7 @@ function _computePointLightViewProjMatrix(light, outView, outProj) { * A representation of a light source. * Could be a point light, a spot light or a directional light. */ -export default class Light { +export class Light { /** * Setup a default directional light with no shadows */ diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 252f28b80e..f519311f78 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,18 +1,17 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { Material } from '../../3d/assets/material'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; import { aabb } from '../../3d/geom-utils'; import { Vec3 } from '../../core/value-types'; -import { mat4, vec3 } from '../../core/vmath'; +import { mat4 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXBufferUsageBit, GFXCommandBufferType, GFXFormat, GFXMemoryUsageBit } from '../../gfx/define'; -import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { GFXBufferUsageBit, GFXCommandBufferType, GFXMemoryUsageBit } from '../../gfx/define'; import { UBOLocal } from '../../pipeline/render-pipeline'; import { Node } from '../../scene-graph'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; import { RenderScene } from './render-scene'; -import { IRenderingSubmesh } from '../../3d/assets/mesh'; const _temp_floatx16 = new Float32Array(16); const _temp_mat4 = mat4.create(); @@ -20,7 +19,7 @@ const _temp_mat4 = mat4.create(); /** * A representation of a model */ -export default class Model { +export class Model { private _scene: RenderScene | null; private _id: number; @@ -36,8 +35,8 @@ export default class Model { private _cameraID: number; private _userKey: number; private _castShadow: boolean; - private _boundingShape: aabb; - private _bsModelSpace: aabb; + private _worldBounds: aabb; + private _modelBounds: aabb; private _material: Material | null; private _cmdBuffers: GFXCommandBuffer[]; private _localUniforms: UBOLocal | null; @@ -61,7 +60,6 @@ export default class Model { this._cameraID = -1; this._userKey = -1; this._castShadow = false; - this._boundingShape = aabb.create(0, 0, 0, 50, 50, 50); this._material = null; this._cmdBuffers = new Array(); this._localUniforms = null; @@ -98,10 +96,10 @@ export default class Model { } public _updateTransform () { - if (!this._node._hasChanged || !this._boundingShape) { return; } + if (!this._node._hasChanged || !this._worldBounds) { return; } this._node.updateWorldTransformFull(); - this._bsModelSpace.transform(this._node._mat, this._node._pos, - this._node._rot, this._node._scale, this._boundingShape); + this._modelBounds.transform(this._node._mat, this._node._pos, + this._node._rot, this._node._scale, this._worldBounds); } public updateRenderData () { @@ -126,8 +124,8 @@ export default class Model { */ public createBoundingShape (minPos: Vec3, maxPos: Vec3) { if (!minPos || !maxPos) { return; } - this._bsModelSpace = aabb.fromPoints(aabb.create(), minPos, maxPos); - this._boundingShape = aabb.clone(this._bsModelSpace); + this._modelBounds = aabb.fromPoints(aabb.create(), minPos, maxPos); + this._worldBounds = aabb.clone(this._modelBounds); } public enable (isEnable: boolean) { @@ -158,12 +156,18 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - set subMeshData(sm: IRenderingSubmesh) { + set subMeshData (sm: IRenderingSubmesh | null) { this._subMeshObject = sm; } + get subMeshData () { + return this._subMeshObject; + } - get boundingShape (): aabb { - return this._boundingShape; + get worldBounds (): aabb { + return this._worldBounds; + } + get modelBounds (): aabb { + return this._modelBounds; } get viewID (): number { @@ -186,11 +190,12 @@ export default class Model { } } - set material(material: Material) { + set material (material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { - if (this._material.passes[i].primitive !== (this._subMeshObject as IRenderingSubmesh).primitiveMode) + if (this._material.passes[i].primitive !== (this._subMeshObject as IRenderingSubmesh).primitiveMode) { cc.error('the model(%d)\'s primitive type doesn\'t match its pass\'s'); + } this.recordCommandBuffer(i); } for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { @@ -213,7 +218,7 @@ export default class Model { if (this._localUBO) { pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO); } - pass.bindingLayout.update(); + pass.update(); this._cmdBuffers[index].begin(); this._cmdBuffers[index].bindPipelineState(pass.pipelineState); this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 78fd643c7b..ab3f5aa439 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -1,7 +1,12 @@ +import { intersect, ray, triangle } from '../../3d/geom-utils'; +import { RecyclePool } from '../../3d/memop'; import { _createSceneFun, Root } from '../../core/root'; +import { mat4, vec3 } from '../../core/vmath'; +import { Layers } from '../../scene-graph/layers'; import { Camera, ICameraInfo } from './camera'; -import Light from './light'; -import Model from './model'; +import { Light } from './light'; +import { Model } from './model'; +import { GFXPrimitiveMode } from '../../gfx/define'; export interface IRenderSceneInfo { name: string; @@ -13,6 +18,11 @@ export interface ISceneNodeInfo { // parent: Node; } +export interface IRaycastResult { + node: Node; + distance: number; +} + export class RenderScene { public get root (): Root { @@ -144,4 +154,64 @@ export class RenderScene { public generateModelId (): number { return this._modelId++; } + + /** + * Cast a ray into the scene, record all the intersected models in the result array + * @param worldRay - the testing ray + * @param mask - the layer mask to filter the models + * @return the results array + */ + public raycast (worldRay: ray, mask: number = Layers.RaycastMask): IRaycastResult[] { + pool.reset(); + for (const m of this._models) { + const node = m.node; + if (!cc.Layers.check(node.layer, mask) || !m.modelBounds) { continue; } + // transform ray back to model space + mat4.invert(m4, node.getWorldMatrix(m4)); + vec3.transformMat4(modelRay.o, worldRay.o, m4); + vec3.normalize(modelRay.d, vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); + // broadphase + distance = intersect.ray_aabb(modelRay, m.modelBounds); + if (distance <= 0) { continue; } + const subModel = m.subMeshData; + if (!subModel || subModel.primitiveMode !== GFXPrimitiveMode.TRIANGLE_LIST) { continue; } + const vbuffer = subModel.inputAssembler.getVertexBuffer(0); + const ibuffer = subModel.inputAssembler.indexBuffer; + if (!vbuffer || !vbuffer.buffer || !ibuffer || !ibuffer.buffer) { continue; } + // narrowphase + distance = Infinity; + const vb = new Float32Array(vbuffer.buffer); + const ib = new Uint16Array(ibuffer.buffer); + const sides = subModel.doubleSided; + for (let j = 0; j < ib.length; j += 3) { + const i0 = ib[j] * 3; + const i1 = ib[j + 1] * 3; + const i2 = ib[j + 2] * 3; + vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]); + vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); + vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); + const dist = intersect.ray_triangle(modelRay, tri, sides); + if (dist <= 0 || dist > distance) { continue; } + distance = dist; + } + if (distance < Infinity) { + const r = pool.add(); + r.node = node; + r.distance = distance * vec3.magnitude(vec3.mul(v3, modelRay.d, node._scale)); + results[pool.length - 1] = r; + } + } + results.length = pool.length; + return results; + } } + +const modelRay = ray.create(); +const v3 = vec3.create(); +const m4 = mat4.create(); +let distance = Infinity; +const tri = triangle.create(); +const pool = new RecyclePool(() => { + return { node: null, distance: Infinity }; +}, 8); +const results: IRaycastResult[] = []; diff --git a/cocos/renderer/scene/scene.js b/cocos/renderer/scene/scene.js index 39899fbb0c..444603f306 100644 --- a/cocos/renderer/scene/scene.js +++ b/cocos/renderer/scene/scene.js @@ -199,62 +199,4 @@ class Scene { } } -if (CC_EDITOR) { - /** - * Cast a ray into the scene, record all the intersected models in the result array - * @param {Ray} worldRay the testing ray - * @param {Object[]} results the results array - * @param {number} mask the layer mask to filter the models - * @return {Object[]} the results array - */ - Scene.prototype.raycast = (function() { - let modelRay = ray.create(); - let v3 = vec3.create(); - let m4 = mat4.create(); - let distance = Infinity; - let tri = triangle.create(); - let pool = new RecyclePool(() => { - return { node: null, distance: Infinity }; - }, 8); - let results = []; - return function(worldRay, mask = Layers.RaycastMask) { - pool.reset(); - for (let i = 0; i < this._models.length; i++) { - let m = this._models.data[i], node = m._node; - if (!cc.Layers.check(node.layer, mask) || !m._bsModelSpace) continue; - // transform ray back to model space - mat4.invert(m4, node.getWorldMatrix(m4)); - vec3.transformMat4(modelRay.o, worldRay.o, m4); - vec3.normalize(modelRay.d, vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); - // broadphase - if ((distance = intersect.ray_aabb(modelRay, m._bsModelSpace)) <= 0) continue; - let ia = m._inputAssembler; - if (ia._primitiveType == gfx.PT_TRIANGLES) { - // narrowphase - distance = Infinity; - let vb = ia._vertexBuffer[gfx.ATTR_POSITION]; - let ib = ia._indexBuffer._data, sides = ia.doubleSided; - for (let j = 0; j < ib.length; j += 3) { - let i0 = ib[j] * 3, i1 = ib[j + 1] * 3, i2 = ib[j + 2] * 3; - vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]); - vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); - vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); - let dist = intersect.ray_triangle(modelRay, tri, sides); - if (dist <= 0 || dist > distance) continue; - distance = dist; - } - } - if (distance < Infinity) { - let r = pool.add(); - r.node = node; - r.distance = distance * vec3.magnitude(vec3.mul(v3, modelRay.d, node._scale)); - results[pool.length - 1] = r; - } - } - results.length = pool.length; - return results; - }; - })(); -} - export default Scene; diff --git a/cocos/renderer/utils.js b/cocos/renderer/utils.js index cc14870639..e437a9c6d4 100644 --- a/cocos/renderer/utils.js +++ b/cocos/renderer/utils.js @@ -1,13 +1,7 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import gfx from './gfx'; -import InputAssembler from './core/input-assembler'; import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXFormat, GFXAttributeName } from '../gfx/define'; -/** - * @param {gfx.Device} device - * @param {Object} data - */ export function createIA(device, data) { if (!data.positions) { console.error('The data must have positions field'); diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 94ee9641a8..fd94bd538c 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -41,8 +41,9 @@ class Node extends BaseNode { @property protected _layer = Layers.Default; // the layer this node belongs to + // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. @property - protected _euler = new Vec3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree. + protected _euler = new Vec3(); // world transform protected _pos = new Vec3(); diff --git a/playground/simple.html b/playground/simple.html index 6df1de6b94..b2e57b0d8f 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -53,8 +53,6 @@ const camComp = cameraNode.addComponent(cc.CameraComponent); const mainWindow = root.mainWindow; - cc.director.runSceneImmediate(scene); - const material = new cc.Material(); material.effectName = 'test'; // parsed effect file is embedded in cocos/3d/builtin/effects.js material.setProperty('u_color', cc.color('#ff0000')); @@ -67,6 +65,8 @@ modelCom.material = material; modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); modelNode.setRotationFromEuler(45, 45, 45); + + cc.director.runSceneImmediate(scene); } cc.game.run({ id: 'canvas' }, onStart); From a653dfeae8944b7cef3ecd96ce1845097c24e7f0 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 11 Jan 2019 18:35:35 +0800 Subject: [PATCH 107/267] fix render queue clear bug --- cocos/core/root.ts | 4 +-- cocos/gfx/buffer.ts | 1 - cocos/gfx/command-buffer.ts | 11 ++++++- cocos/gfx/webgl/webgl-buffer.ts | 7 +---- cocos/gfx/webgl/webgl-command-buffer.ts | 2 +- cocos/gfx/webgl/webgl-commands.ts | 14 +++++---- cocos/gfx/webgl/webgl-device.ts | 18 +++++++----- cocos/gfx/webgl/webgl-gpu-objects.ts | 1 - cocos/pipeline/forward/forward-flow.ts | 4 +-- cocos/pipeline/forward/forward-stage.ts | 18 ++++++++++-- cocos/pipeline/render-pipeline.ts | 9 +++++- cocos/pipeline/render-queue.ts | 21 ++++++++++---- .../test-material-stage.ts | 0 .../{forward => testcase}/test-model-stage.ts | 0 .../{forward => testcase}/test-stage.ts | 0 cocos/renderer/scene/model.ts | 29 +++++++++---------- playground/simple.html | 13 +++++++++ 17 files changed, 100 insertions(+), 52 deletions(-) rename cocos/pipeline/{forward => testcase}/test-material-stage.ts (100%) rename cocos/pipeline/{forward => testcase}/test-model-stage.ts (100%) rename cocos/pipeline/{forward => testcase}/test-stage.ts (100%) diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 3896c88d95..f5170420a8 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -183,8 +183,8 @@ export class Root { } public destroyViews () { - for (let i = 0; i < this._views.length; ++i) { - this._views[i].destroy(); + for (const view of this._views) { + view.destroy(); } this._views = []; } diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 627a9e231e..7fc6c7f047 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -36,7 +36,6 @@ export abstract class GFXBuffer extends GFXObject { protected _size: number = 0; protected _stride: number = 1; protected _buffer: ArrayBuffer | null = null; - protected _bufferView: Uint8Array | null = null; constructor (device: GFXDevice) { super(GFXObjectType.BUFFER); diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index 7f7f25276f..28388d51fe 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -1,7 +1,15 @@ import { GFXBindingLayout } from './binding-layout'; import { GFXBuffer } from './buffer'; import { GFXCommandAllocator } from './command-allocator'; -import { GFXBufferTextureCopy, GFXCommandBufferType, GFXObject, GFXObjectType, GFXTextureLayout, IGFXColor, IGFXRect } from './define'; +import { + GFXBufferTextureCopy, + GFXCommandBufferType, + GFXObject, + GFXObjectType, + GFXTextureLayout, + IGFXColor, + IGFXRect, +} from './define'; import { GFXDevice } from './device'; import { GFXFramebuffer } from './framebuffer'; import { GFXInputAssembler } from './input-assembler'; @@ -13,6 +21,7 @@ export interface IGFXCommandBufferInfo { type: GFXCommandBufferType; } +// tslint:disable: max-line-length export abstract class GFXCommandBuffer extends GFXObject { public get type (): number { diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index ac7c889c94..33243d3099 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -33,7 +33,6 @@ export class WebGLGFXBuffer extends GFXBuffer { if (this._memUsage & GFXMemoryUsageBit.HOST) { this._buffer = new ArrayBuffer(this._size); - this._bufferView = new Uint8Array(this._buffer); } // this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; @@ -50,16 +49,12 @@ export class WebGLGFXBuffer extends GFXBuffer { } this._buffer = null; - this._bufferView = null; this._status = GFXStatus.UNREADY; } public update (buffer: ArrayBuffer, offset?: number, size?: number) { - const isUniformBuffer = (this._usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; - if (this._bufferView && !isUniformBuffer) { - this._bufferView.set(new Uint8Array(buffer, 0, size), offset); - } + // const isUniformBuffer = (this._usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; this.webGLDevice.emitCmdUpdateGPUBuffer( this._gpuBuffer as WebGLGPUBuffer, diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 7c3b2363b7..16d255a8f9 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -124,7 +124,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { const cmd = ( this._allocator as WebGLGFXCommandAllocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { cmd.gpuBuffer = gpuBuffer; - cmd.buffer = data; + cmd.buffer = data.slice(0); cmd.offset = (offset !== undefined ? offset : 0); this.cmdPackage.updateBufferCmds.push(cmd); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index bc49dfbd71..b0de68901b 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1929,8 +1929,10 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web const cmd6 = cmdPackage.updateBufferCmds[cmdId]; if (cmd6.gpuBuffer) { - if (cmd6.buffer && cmd6.gpuBuffer.viewUI8) { - cmd6.gpuBuffer.viewUI8.set(new Uint8Array(cmd6.buffer), cmd6.offset); + if (cmd6.buffer) { + if (cmd6.gpuBuffer.viewF32) { + cmd6.gpuBuffer.viewF32.set(new Float32Array(cmd6.buffer), cmd6.offset); + } } switch (cmd6.gpuBuffer.glTarget) { @@ -1964,8 +1966,8 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { const cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; - if (cmd7.gpuBuffer && cmd7.gpuBuffer.viewUI8 && cmd7.gpuTexture) { - WebGLCmdFuncCopyBufferToTexture(device, cmd7.gpuBuffer.viewUI8, cmd7.gpuTexture, cmd7.regions); + if (cmd7.gpuBuffer && cmd7.gpuBuffer.buffer && cmd7.gpuTexture) { + WebGLCmdFuncCopyBufferToTexture(device, cmd7.gpuBuffer.buffer, cmd7.gpuTexture, cmd7.regions); } break; @@ -1976,12 +1978,14 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web export function WebGLCmdFuncCopyBufferToTexture ( device: WebGLGFXDevice, - bufferView: Uint8Array, + buffer: ArrayBuffer, gpuTexture: WebGLGPUTexture, regions: GFXBufferTextureCopy[]) { const gl = device.gl; + const bufferView = new Uint8Array(buffer); + switch (gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { const glTexUnit = device.stateCache.glTex2DUnits[device.stateCache.texUnit]; diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 9d8604c6bd..148492ed7e 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -448,9 +448,11 @@ export class WebGLGFXDevice extends GFXDevice { } public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { - - const bufferView = new Uint8Array(buffer); - WebGLCmdFuncCopyBufferToTexture(this as WebGLGFXDevice, bufferView, (texture as WebGLGFXTexture).gpuTexture, regions); + WebGLCmdFuncCopyBufferToTexture( + this as WebGLGFXDevice, + buffer, + (texture as WebGLGFXTexture).gpuTexture, + regions); } public copyImageSourceToTexture (source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { @@ -464,9 +466,11 @@ export class WebGLGFXDevice extends GFXDevice { context.drawImage(source, 0, 0); const imgData = context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height); - const bufferView = new Uint8Array(imgData.data); - - WebGLCmdFuncCopyBufferToTexture(this as WebGLGFXDevice, bufferView, (texture as WebGLGFXTexture).gpuTexture, regions); + WebGLCmdFuncCopyBufferToTexture( + this as WebGLGFXDevice, + imgData.data, + (texture as WebGLGFXTexture).gpuTexture, + regions); } } } @@ -511,7 +515,6 @@ export class WebGLGFXDevice extends GFXDevice { size: info.size, stride: info.stride ? info.stride : 1, buffer: null, - viewUI8: null, viewF32: null, glTarget: 0, glBuffer: 0, @@ -519,7 +522,6 @@ export class WebGLGFXDevice extends GFXDevice { if (buffer) { gpuBuffer.buffer = buffer; - gpuBuffer.viewUI8 = new Uint8Array(gpuBuffer.buffer); } // let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index ef868b0b02..790440838e 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -36,7 +36,6 @@ export class WebGLGPUBuffer extends WebGLGPUObject { public glTarget: GLenum = 0; public glBuffer: WebGLBuffer = 0; public buffer: ArrayBuffer | null = null; - public viewUI8: Uint8Array | null = null; public viewF32: Float32Array | null = null; constructor () { diff --git a/cocos/pipeline/forward/forward-flow.ts b/cocos/pipeline/forward/forward-flow.ts index e2f7f7050e..fff7ab07d8 100644 --- a/cocos/pipeline/forward/forward-flow.ts +++ b/cocos/pipeline/forward/forward-flow.ts @@ -1,7 +1,7 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { RenderPipeline } from '../render-pipeline'; // import { TestStage } from "./test-stage"; -import { TestModelStage } from './test-model-stage'; +import { TestModelStage } from '../testcase/test-model-stage'; import { ForwardStage } from './forward-stage'; export enum ForwardStagePriority { @@ -26,7 +26,7 @@ export class ForwardFlow extends RenderFlow { if (!mainWindow || !mainWindow.framebuffer) { return false; } - + this.createStage(ForwardStage, { name: 'ForwardStage', priority: ForwardStagePriority.FORWARD, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 39a12ff049..d6c032dede 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -48,10 +48,22 @@ export class ForwardStage extends RenderStage { this._renderArea.height = camera.height; cmdBuff.begin(); - cmdBuff.beginRenderPass( this._framebuffer as GFXFramebuffer, this._renderArea, this._clearColors, this._clearDepth, this._clearStencil); + cmdBuff.beginRenderPass( + this._framebuffer as GFXFramebuffer, + this._renderArea, + this._clearColors, + this._clearDepth, + this._clearStencil); - cmdBuff.execute(queue.opaqueCmdBuffs); - cmdBuff.execute(queue.transparentCmdBuffs); + for (const item of queue.opaques) { + cmdBuff.updateBuffer(item.model.localUBO, item.model.localUniforms.view); + cmdBuff.execute([item.cmdBuff]); + } + + for (const item of queue.transparents) { + cmdBuff.updateBuffer(item.model.localUBO, item.model.localUniforms.view); + cmdBuff.execute([item.cmdBuff]); + } cmdBuff.endRenderPass(); cmdBuff.end(); diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 1210f9300a..ec9685c156 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -139,6 +139,8 @@ export abstract class RenderPipeline { for (const flow of this._flows) { flow.render(view); } + + // TODO : add ui render pipeline } public addRenderPass (stage: number, renderPass: GFXRenderPass) { @@ -164,7 +166,10 @@ export abstract class RenderPipeline { this._renderPasses.clear(); } - public createFlow (clazz: new (pipeline: RenderPipeline) => T, info: IRenderFlowInfo): RenderFlow | null { + public createFlow ( + clazz: new (pipeline: RenderPipeline) => T, + info: IRenderFlowInfo): RenderFlow | null { + const flow: RenderFlow = new clazz(this); if (flow.initialize(info)) { this._flows.push(flow); @@ -343,6 +348,8 @@ export abstract class RenderPipeline { const scene = view.scene; const camera = view.camera; + this._queue.clear(); + for (const model of scene.models) { // filter model by view visibility diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index a444267db0..d42eabf2e6 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -24,9 +24,9 @@ export class RenderItem { export class RenderQueue { public opaques: RenderItem[] = []; - public opaqueCmdBuffs: GFXCommandBuffer[] = []; + // public opaqueCmdBuffs: GFXCommandBuffer[] = []; public transparents: RenderItem[] = []; - public transparentCmdBuffs: GFXCommandBuffer[] = []; + // public transparentCmdBuffs: GFXCommandBuffer[] = []; private _buffer: ArrayBuffer; private _f32View: Float32Array; private _ui32View: Uint32Array; @@ -37,13 +37,20 @@ export class RenderQueue { this._ui32View = new Uint32Array(this._buffer); } + public clear () { + this.opaques = []; + this.transparents = []; + } + public add (model: Model, camera: Camera) { model.node.getPosition(_pos); camera.node.getPosition(_cameraPos); this._f32View[0] = vec3.distance(_cameraPos, _pos); - const ui32Depth: number = this._ui32View[0]; - const ui32DepthInv = (ui32Depth ^ 0xffffffff); + let ui32Depth: number = this._ui32View[0]; + const mask = -(ui32Depth >> 31) | 0x8000000000000000; + ui32Depth = (ui32Depth ^ mask); + const ui32DepthInv = (ui32Depth ^ 0xffffffffffffffff); for (let i = 0; i < model.passes.length; ++i) { const pass = model.passes[i]; @@ -59,12 +66,12 @@ export class RenderQueue { if (!isTransparent) { // Opaque objects are sorted by depth front to back -> pass priority -> shader id. - const hash = (0 << 63) | (i << 47) | (ui32Depth << 15) | pso.shader.id; + const hash = (0 << 61) | (i << 45) | (ui32Depth << 13) | pso.shader.id; this.opaques.push({hash, model, pass, cmdBuff}); } else { // Transparent objects are sorted by depth back to front -> pass priority -> shader id. - const hash = (1 << 63) | (i << 47) | (ui32DepthInv << 15) | pso.shader.id; + const hash = (1 << 61) | (i << 45) | (ui32DepthInv << 13) | pso.shader.id; this.transparents.push({hash, model, pass, cmdBuff}); } @@ -81,6 +88,7 @@ export class RenderQueue { return a.hash - b.hash; }); + /* this.opaqueCmdBuffs = new Array(this.opaques.length); for (let i = 0; i < this.opaques.length; ++i) { this.opaqueCmdBuffs[i] = this.opaques[i].cmdBuff; @@ -90,5 +98,6 @@ export class RenderQueue { for (let i = 0; i < this.transparents.length; ++i) { this.transparentCmdBuffs[i] = this.transparents[i].cmdBuff; } + */ } } diff --git a/cocos/pipeline/forward/test-material-stage.ts b/cocos/pipeline/testcase/test-material-stage.ts similarity index 100% rename from cocos/pipeline/forward/test-material-stage.ts rename to cocos/pipeline/testcase/test-material-stage.ts diff --git a/cocos/pipeline/forward/test-model-stage.ts b/cocos/pipeline/testcase/test-model-stage.ts similarity index 100% rename from cocos/pipeline/forward/test-model-stage.ts rename to cocos/pipeline/testcase/test-model-stage.ts diff --git a/cocos/pipeline/forward/test-stage.ts b/cocos/pipeline/testcase/test-stage.ts similarity index 100% rename from cocos/pipeline/forward/test-stage.ts rename to cocos/pipeline/testcase/test-stage.ts diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 252f28b80e..65731ae39e 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -1,5 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { Material } from '../../3d/assets/material'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; import { aabb } from '../../3d/geom-utils'; import { Vec3 } from '../../core/value-types'; import { mat4, vec3 } from '../../core/vmath'; @@ -12,7 +13,6 @@ import { Node } from '../../scene-graph'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; import { RenderScene } from './render-scene'; -import { IRenderingSubmesh } from '../../3d/assets/mesh'; const _temp_floatx16 = new Float32Array(16); const _temp_mat4 = mat4.create(); @@ -114,9 +114,12 @@ export default class Model { if (this._localUniforms) { this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); } + + /* if (this._localUBO) { this._localUBO.update(this._localUniforms.view); } + */ } /** @@ -158,7 +161,7 @@ export default class Model { * Set the input assembler * @param {InputAssembler} ia */ - set subMeshData(sm: IRenderingSubmesh) { + set subMeshData (sm: IRenderingSubmesh) { this._subMeshObject = sm; } @@ -186,11 +189,12 @@ export default class Model { } } - set material(material: Material) { + set material (material: Material) { this._material = material; for (let i = 0; i < this._material.passes.length; i++) { - if (this._material.passes[i].primitive !== (this._subMeshObject as IRenderingSubmesh).primitiveMode) + if (this._material.passes[i].primitive !== (this._subMeshObject as IRenderingSubmesh).primitiveMode) { cc.error('the model(%d)\'s primitive type doesn\'t match its pass\'s'); + } this.recordCommandBuffer(i); } for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { @@ -238,16 +242,11 @@ export default class Model { return this._cmdBuffers; } - /** - * Extract a drawing item - * @param {Object} out the receiving item - */ - public extractDrawItem (out) { - out.model = this; - out.node = this._node; - out.ia = this._inputAssembler; - out.effect = this._effect; - // out.defines = this._effect ? this._effect.extractDefines(this._defines) : this._defines; - // out.dependencies = this._effect ? this._effect.extractDependencies(this._dependencies) : this._dependencies; + get localUniforms (): UBOLocal { + return this._localUniforms as UBOLocal; + } + + get localUBO (): GFXBuffer { + return this._localUBO as GFXBuffer; } } diff --git a/playground/simple.html b/playground/simple.html index 6df1de6b94..9a097bd31b 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -67,6 +67,19 @@ modelCom.material = material; modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); modelNode.setRotationFromEuler(45, 45, 45); + + /* + const modelNode2 = new cc.Node(); + modelNode2.parent = scene; + const modelCom2 = modelNode2.addComponent('cc.ModelComponent'); + modelCom2.material = material; + modelCom2.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + + let vPos = modelNode2.getPosition(); + vPos.x += 0.7; + + modelNode2.setPosition(vPos); + */ } cc.game.run({ id: 'canvas' }, onStart); From 12772e287f3fc8689965d83e07c1826e26601ff6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 11 Jan 2019 18:48:54 +0800 Subject: [PATCH 108/267] fix render stage --- cocos/pipeline/forward/forward-stage.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index c685dfb9b8..65e427c81d 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -51,6 +51,11 @@ export class ForwardStage extends RenderStage { cmdBuff.beginRenderPass(this._framebuffer as GFXFramebuffer, this._renderArea, [camera.clearColor], camera.clearDepth, camera.clearStencil); + for (const item of queue.opaques) { + cmdBuff.updateBuffer(item.model.localUBO, item.model.localUniforms.view); + cmdBuff.execute([item.cmdBuff]); + } + for (const item of queue.transparents) { cmdBuff.updateBuffer(item.model.localUBO, item.model.localUniforms.view); cmdBuff.execute([item.cmdBuff]); From b5182469e9b5c934785b7a99f6d97f4d467a5c66 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Sat, 12 Jan 2019 15:45:21 +0800 Subject: [PATCH 109/267] optimize command buffer package --- cocos/gfx/webgl/webgl-command-allocator.ts | 16 +-- cocos/gfx/webgl/webgl-command-buffer.ts | 100 +++++++++++------ cocos/gfx/webgl/webgl-commands.ts | 124 +++++++-------------- 3 files changed, 117 insertions(+), 123 deletions(-) diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index d103695b51..60cf4275dc 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -1,7 +1,13 @@ import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; -import { WebGLCmdBeginRenderPass, WebGLCmdBindBindingLayout, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdCopyBufferToTexture, WebGLCmdDraw, WebGLCmdUpdateBuffer } from './webgl-commands'; +import { + WebGLCmdBeginRenderPass, + WebGLCmdBindStates, + WebGLCmdCopyBufferToTexture, + WebGLCmdDraw, + WebGLCmdUpdateBuffer, +} from './webgl-commands'; export class WebGLGFXCommandPool { @@ -51,9 +57,7 @@ export class WebGLGFXCommandPool { export class WebGLGFXCommandAllocator extends GFXCommandAllocator { public beginRenderPassCmdPool: WebGLGFXCommandPool; - public bindPipelineStateCmdPool: WebGLGFXCommandPool; - public bindBindingLayoutCmdPool: WebGLGFXCommandPool; - public bindInputAssemblerCmdPool: WebGLGFXCommandPool; + public bindStatesCmdPool: WebGLGFXCommandPool; public drawCmdPool: WebGLGFXCommandPool; public updateBufferCmdPool: WebGLGFXCommandPool; public copyBufferToTextureCmdPool: WebGLGFXCommandPool; @@ -61,9 +65,7 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { constructor (device: GFXDevice) { super(device); this.beginRenderPassCmdPool = new WebGLGFXCommandPool(WebGLCmdBeginRenderPass, 64, 32); - this.bindPipelineStateCmdPool = new WebGLGFXCommandPool(WebGLCmdBindPipelineState, 64, 32); - this.bindBindingLayoutCmdPool = new WebGLGFXCommandPool(WebGLCmdBindBindingLayout, 64, 32); - this.bindInputAssemblerCmdPool = new WebGLGFXCommandPool(WebGLCmdBindInputAssembler, 64, 32); + this.bindStatesCmdPool = new WebGLGFXCommandPool(WebGLCmdBindStates, 64, 32); this.drawCmdPool = new WebGLGFXCommandPool(WebGLCmdDraw, 64, 32); this.updateBufferCmdPool = new WebGLGFXCommandPool(WebGLCmdUpdateBuffer, 64, 32); this.copyBufferToTextureCmdPool = new WebGLGFXCommandPool(WebGLCmdCopyBufferToTexture, 64, 32); diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 16d255a8f9..8e7136bf87 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -10,9 +10,18 @@ import { GFXTexture } from '../texture'; import { WebGLGFXBindingLayout } from './webgl-binding-layout'; import { WebGLGFXBuffer } from './webgl-buffer'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; -import { WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdBindBindingLayout, WebGLCmdBindInputAssembler, WebGLCmdBindPipelineState, WebGLCmdCopyBufferToTexture, WebGLCmdDraw, WebGLCmdPackage, WebGLCmdUpdateBuffer, WebGLGFXBufferTextureCopy } from './webgl-commands'; +import { + WebGLCmd, + WebGLCmdBeginRenderPass, + WebGLCmdBindStates, + WebGLCmdCopyBufferToTexture, + WebGLCmdDraw, + WebGLCmdPackage, + WebGLCmdUpdateBuffer, +} from './webgl-commands'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGFXFramebuffer } from './webgl-framebuffer'; +import { WebGLGPUBindingLayout, WebGLGPUInputAssembler, WebGLGPUPipelineState } from './webgl-gpu-objects'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { WebGLGFXPipelineState } from './webgl-pipeline-state'; import { WebGLGFXTexture } from './webgl-texture'; @@ -20,6 +29,10 @@ import { WebGLGFXTexture } from './webgl-texture'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); + private _curGPUPipelineState: WebGLGPUPipelineState | null = null; + private _curGPUBindingLayout: WebGLGPUBindingLayout | null = null; + private _curGPUInputAssembler: WebGLGPUInputAssembler | null = null; + private _isStateInvalied: boolean = false; constructor (device: GFXDevice) { super(device); @@ -52,14 +65,24 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public end () { + if (this._isStateInvalied) { + this.bindStates(); + } } - public beginRenderPass (framebuffer: GFXFramebuffer, renderArea: IGFXRect, clearColors: IGFXColor[], clearDepth: number, clearStencil: number) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator).beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); + public beginRenderPass ( + framebuffer: GFXFramebuffer, + renderArea: IGFXRect, + clearColors: IGFXColor[], + clearDepth: number, + clearStencil: number) { + const cmd = ( this._allocator as WebGLGFXCommandAllocator). + beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); if (cmd) { cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; cmd.renderArea = renderArea; cmd.clearColors = clearColors.slice(); + cmd.clearDepth = clearDepth; cmd.clearStencil = clearStencil; this.cmdPackage.beginRenderPassCmds.push(cmd); @@ -71,38 +94,28 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public bindPipelineState (pipelineState: GFXPipelineState) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator).bindPipelineStateCmdPool.alloc(WebGLCmdBindPipelineState); - if (cmd) { - cmd.gpuPipelineState = ( pipelineState as WebGLGFXPipelineState).gpuPipelineState; - this.cmdPackage.bindPipelineStateCmds.push(cmd); - - this.cmdPackage.cmds.push(WebGLCmd.BIND_PIPELINE_STATE); - } + this._curGPUPipelineState = (pipelineState as WebGLGFXPipelineState).gpuPipelineState; + this._isStateInvalied = true; } public bindBindingLayout (bindingLayout: GFXBindingLayout) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator).bindBindingLayoutCmdPool.alloc(WebGLCmdBindBindingLayout); - if (cmd) { - cmd.gpuBindingLayout = ( bindingLayout as WebGLGFXBindingLayout).gpuBindingLayout; - this.cmdPackage.bindBindingLayoutCmds.push(cmd); - - this.cmdPackage.cmds.push(WebGLCmd.BIND_BINDING_LAYOUT); - } + this._curGPUBindingLayout = (bindingLayout as WebGLGFXBindingLayout).gpuBindingLayout; + this._isStateInvalied = true; } public bindInputAssembler (inputAssembler: GFXInputAssembler) { - - const cmd = ( this._allocator as WebGLGFXCommandAllocator).bindInputAssemblerCmdPool.alloc(WebGLCmdBindInputAssembler); - if (cmd) { - cmd.gpuInputAssembler = ( inputAssembler as WebGLGFXInputAssembler).gpuInputAssembler; - this.cmdPackage.bindInputAssemblerCmds.push(cmd); - - this.cmdPackage.cmds.push(WebGLCmd.BIND_INPUT_ASSEMBLER); - } + this._curGPUInputAssembler = (inputAssembler as WebGLGFXInputAssembler).gpuInputAssembler; + this._isStateInvalied = true; } public draw (inputAssembler: GFXInputAssembler) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator).drawCmdPool.alloc(WebGLCmdDraw); + + if (this._isStateInvalied) { + this.bindStates(); + } + + const cmd = ( this._allocator as WebGLGFXCommandAllocator). + drawCmdPool.alloc(WebGLCmdDraw); if (cmd) { cmd.vertexCount = inputAssembler.vertexCount; cmd.firstVertex = inputAssembler.firstVertex; @@ -119,9 +132,10 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public updateBuffer (buffer: GFXBuffer, data: ArrayBuffer, offset?: number) { - const gpuBuffer = ( buffer as WebGLGFXBuffer).gpuBuffer; + const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; if (gpuBuffer) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator).updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); + const cmd = (this._allocator as WebGLGFXCommandAllocator). + updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { cmd.gpuBuffer = gpuBuffer; cmd.buffer = data.slice(0); @@ -133,11 +147,16 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } - public copyBufferToTexture (srcBuff: GFXBuffer, dstTex: GFXTexture, dstLayout: GFXTextureLayout, regions: GFXBufferTextureCopy[]) { + public copyBufferToTexture ( + srcBuff: GFXBuffer, + dstTex: GFXTexture, + dstLayout: GFXTextureLayout, + regions: GFXBufferTextureCopy[]) { const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; if (gpuBuffer && gpuTexture) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator).copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); + const cmd = (this._allocator as WebGLGFXCommandAllocator). + copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); if (cmd) { cmd.gpuBuffer = gpuBuffer; cmd.gpuTexture = gpuTexture; @@ -150,15 +169,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } } + // tslint:disable: max-line-length public execute (cmdBuffs: GFXCommandBuffer[]) { for (const cmdBuff of cmdBuffs) { const webGLCmdBuff = cmdBuff as WebGLGFXCommandBuffer; this.cmdPackage.beginRenderPassCmds = this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); - this.cmdPackage.bindPipelineStateCmds = this.cmdPackage.bindPipelineStateCmds.concat(webGLCmdBuff.cmdPackage.bindPipelineStateCmds); - this.cmdPackage.bindBindingLayoutCmds = this.cmdPackage.bindBindingLayoutCmds.concat(webGLCmdBuff.cmdPackage.bindBindingLayoutCmds); - this.cmdPackage.bindInputAssemblerCmds = this.cmdPackage.bindInputAssemblerCmds.concat(webGLCmdBuff.cmdPackage.bindInputAssemblerCmds); + this.cmdPackage.bindStatesCmds = this.cmdPackage.bindStatesCmds.concat(webGLCmdBuff.cmdPackage.bindStatesCmds); this.cmdPackage.drawCmds = this.cmdPackage.drawCmds.concat(webGLCmdBuff.cmdPackage.drawCmds); this.cmdPackage.updateBufferCmds = this.cmdPackage.updateBufferCmds.concat(webGLCmdBuff.cmdPackage.updateBufferCmds); this.cmdPackage.copyBufferToTextureCmds = this.cmdPackage.copyBufferToTextureCmds.concat(webGLCmdBuff.cmdPackage.copyBufferToTextureCmds); @@ -169,4 +187,20 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public get webGLDevice (): WebGLGFXDevice { return this._device as WebGLGFXDevice; } + + private bindStates () { + const bindStatesCmd = ( this._allocator as WebGLGFXCommandAllocator). + bindStatesCmdPool.alloc(WebGLCmdBindStates); + + if (bindStatesCmd) { + bindStatesCmd.gpuPipelineState = this._curGPUPipelineState; + bindStatesCmd.gpuBindingLayout = this._curGPUBindingLayout; + bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler; + + this.cmdPackage.bindStatesCmds.push(bindStatesCmd); + this.cmdPackage.cmds.push(WebGLCmd.BIND_STATES); + + this._isStateInvalied = false; + } + } } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index c52380bbee..c869964ff8 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -341,9 +341,7 @@ const WebGLBlendFactors: GLenum[] = [ export enum WebGLCmd { BEGIN_RENDER_PASS, END_RENDER_PASS, - BIND_PIPELINE_STATE, - BIND_BINDING_LAYOUT, - BIND_INPUT_ASSEMBLER, + BIND_STATES, DRAW, UPDATE_BUFFER, COPY_BUFFER_TO_TEXTURE, @@ -371,30 +369,14 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject { } } -export class WebGLCmdBindPipelineState extends WebGLCmdObject { +export class WebGLCmdBindStates extends WebGLCmdObject { public gpuPipelineState: WebGLGPUPipelineState | null = null; - - constructor () { - super(WebGLCmd.BIND_PIPELINE_STATE); - } -} - -export class WebGLCmdBindInputAssembler extends WebGLCmdObject { - + public gpuBindingLayout: WebGLGPUBindingLayout | null = null; public gpuInputAssembler: WebGLGPUInputAssembler | null = null; constructor () { - super(WebGLCmd.BIND_INPUT_ASSEMBLER); - } -} - -export class WebGLCmdBindBindingLayout extends WebGLCmdObject { - - public gpuBindingLayout: WebGLGPUBindingLayout | null = null; - - constructor () { - super(WebGLCmd.BIND_BINDING_LAYOUT); + super(WebGLCmd.BIND_STATES); } } @@ -457,9 +439,7 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { export class WebGLCmdPackage { public cmds: WebGLCmd[] = []; public beginRenderPassCmds: WebGLCmdBeginRenderPass[] = []; - public bindPipelineStateCmds: WebGLCmdBindPipelineState[] = []; - public bindBindingLayoutCmds: WebGLCmdBindBindingLayout[] = []; - public bindInputAssemblerCmds: WebGLCmdBindInputAssembler[] = []; + public bindStatesCmds: WebGLCmdBindStates[] = []; public drawCmds: WebGLCmdDraw[] = []; public updateBufferCmds: WebGLCmdUpdateBuffer[] = []; public copyBufferToTextureCmds: WebGLCmdCopyBufferToTexture[] = []; @@ -473,25 +453,11 @@ export class WebGLCmdPackage { this.beginRenderPassCmds = []; } - if (this.bindPipelineStateCmds.length) { - for (const bindPipelineStateCmd of this.bindPipelineStateCmds) { - allocator.bindPipelineStateCmdPool.free(bindPipelineStateCmd); + if (this.bindStatesCmds.length) { + for (const bindStatesCmd of this.bindStatesCmds) { + allocator.bindStatesCmdPool.free(bindStatesCmd); } - this.bindPipelineStateCmds = []; - } - - if (this.bindBindingLayoutCmds.length) { - for (const bindBindingLayoutCmd of this.bindBindingLayoutCmds) { - allocator.bindBindingLayoutCmdPool.free(bindBindingLayoutCmd); - } - this.bindBindingLayoutCmds = []; - } - - if (this.bindInputAssemblerCmds.length) { - for (const bindInputAssemblerCmd of this.bindInputAssemblerCmds) { - allocator.bindInputAssemblerCmdPool.free(bindInputAssemblerCmd); - } - this.bindInputAssemblerCmds = []; + this.bindStatesCmds = []; } if (this.drawCmds.length) { @@ -1105,7 +1071,7 @@ export function WebGLCmdFuncDestroyInputAssembler (device: WebGLGFXDevice, gpuIn export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { const gl = device.gl; - const cmdIds = [0, 0, 0, 0, 0, 0, 0, 0]; // 8 + const cmdIds = [0, 0, 0, 0, 0, 0]; // 6 let gpuShader: WebGLGPUShader | null = null; let gpuInputAssembler: WebGLGPUInputAssembler | null = null; @@ -1286,9 +1252,9 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web // GFXStoreOp.Store is the default GL behaviour. break; } - case WebGLCmd.BIND_PIPELINE_STATE: { + case WebGLCmd.BIND_STATES: { - const cmd2 = cmdPackage.bindPipelineStateCmds[cmdId]; + const cmd2 = cmdPackage.bindStatesCmds[cmdId]; if (cmd2.gpuPipelineState) { glPrimitive = cmd2.gpuPipelineState.glPrimitive; @@ -1535,13 +1501,8 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } // blend state } - break; - } - case WebGLCmd.BIND_BINDING_LAYOUT: { - - const cmd3 = cmdPackage.bindBindingLayoutCmds[cmdId]; - if (cmd3.gpuBindingLayout && gpuShader) { - for (const gpuBinding of cmd3.gpuBindingLayout.gpuBindings) { + if (cmd2.gpuBindingLayout && gpuShader) { + for (const gpuBinding of cmd2.gpuBindingLayout.gpuBindings) { switch (gpuBinding.type) { case GFXBindingType.UNIFORM_BUFFER: { @@ -1854,17 +1815,14 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } } - } + } // bind binding layout + + gpuInputAssembler = cmd2.gpuInputAssembler; break; } - case WebGLCmd.BIND_INPUT_ASSEMBLER: { - const cmd4 = cmdPackage.bindInputAssemblerCmds[cmdId]; - gpuInputAssembler = cmd4.gpuInputAssembler; - break; - } case WebGLCmd.DRAW: { - const cmd5: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; + const cmd3: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; if (gpuInputAssembler && gpuShader) { for (let a = 0; a < device.maxVertexAttributes; ++a) { @@ -1902,7 +1860,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } // if - if (gpuInputAssembler.gpuIndexBuffer && cmd5.indexCount > 0) { + if (gpuInputAssembler.gpuIndexBuffer && cmd3.indexCount > 0) { const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { @@ -1910,10 +1868,10 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - const offset = cmd5.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, cmd5.indexCount, gpuInputAssembler.glIndexType, offset); + const offset = cmd3.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, cmd3.indexCount, gpuInputAssembler.glIndexType, offset); } else { - gl.drawArrays(glPrimitive, cmd5.firstVertex, cmd5.vertexCount); + gl.drawArrays(glPrimitive, cmd3.firstVertex, cmd3.vertexCount); } for (let a = 0; a < device.maxVertexAttributes; ++a) { @@ -1926,35 +1884,35 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web break; } case WebGLCmd.UPDATE_BUFFER: { - const cmd6 = cmdPackage.updateBufferCmds[cmdId]; - if (cmd6.gpuBuffer) { + const cmd4 = cmdPackage.updateBufferCmds[cmdId]; + if (cmd4.gpuBuffer) { - if (cmd6.buffer) { - if (cmd6.gpuBuffer.viewF32) { - cmd6.gpuBuffer.viewF32.set(new Float32Array(cmd6.buffer), cmd6.offset); + if (cmd4.buffer) { + if (cmd4.gpuBuffer.viewF32) { + cmd4.gpuBuffer.viewF32.set(new Float32Array(cmd4.buffer), cmd4.offset); } } - switch (cmd6.gpuBuffer.glTarget) { + switch (cmd4.gpuBuffer.glTarget) { case WebGLRenderingContext.ARRAY_BUFFER: { - if (device.stateCache.glArrayBuffer !== cmd6.gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, cmd6.gpuBuffer.glBuffer); - device.stateCache.glArrayBuffer = cmd6.gpuBuffer.glBuffer; + if (device.stateCache.glArrayBuffer !== cmd4.gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, cmd4.gpuBuffer.glBuffer); + device.stateCache.glArrayBuffer = cmd4.gpuBuffer.glBuffer; } - if (cmd6.buffer) { - gl.bufferSubData(cmd6.gpuBuffer.glTarget, cmd6.offset, cmd6.buffer); + if (cmd4.buffer) { + gl.bufferSubData(cmd4.gpuBuffer.glTarget, cmd4.offset, cmd4.buffer); } break; } case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { - if (device.stateCache.glElementArrayBuffer !== cmd6.gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, cmd6.gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = cmd6.gpuBuffer.glBuffer; + if (device.stateCache.glElementArrayBuffer !== cmd4.gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, cmd4.gpuBuffer.glBuffer); + device.stateCache.glElementArrayBuffer = cmd4.gpuBuffer.glBuffer; } - if (cmd6.buffer) { - gl.bufferSubData(cmd6.gpuBuffer.glTarget, cmd6.offset, cmd6.buffer); + if (cmd4.buffer) { + gl.bufferSubData(cmd4.gpuBuffer.glTarget, cmd4.offset, cmd4.buffer); } break; } @@ -1965,9 +1923,9 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web break; } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { - const cmd7 = cmdPackage.copyBufferToTextureCmds[cmdId]; - if (cmd7.gpuBuffer && cmd7.gpuBuffer.buffer && cmd7.gpuTexture) { - WebGLCmdFuncCopyBufferToTexture(device, cmd7.gpuBuffer.buffer, cmd7.gpuTexture, cmd7.regions); + const cmd5 = cmdPackage.copyBufferToTextureCmds[cmdId]; + if (cmd5.gpuBuffer && cmd5.gpuBuffer.buffer && cmd5.gpuTexture) { + WebGLCmdFuncCopyBufferToTexture(device, cmd5.gpuBuffer.buffer, cmd5.gpuTexture, cmd5.regions); } break; From 93e1769f0efac03ff1a5b336cead1453dc815787 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 14 Jan 2019 10:28:31 +0800 Subject: [PATCH 110/267] add indirect buffer feature --- cocos/gfx/buffer.ts | 31 ++++- cocos/gfx/define.ts | 1 + cocos/gfx/input-assembler.ts | 21 +++- cocos/gfx/webgl/webgl-buffer.ts | 23 +++- cocos/gfx/webgl/webgl-command-buffer.ts | 51 +++++--- cocos/gfx/webgl/webgl-commands.ts | 153 ++++++++++++----------- cocos/gfx/webgl/webgl-device.ts | 8 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 15 ++- cocos/gfx/webgl/webgl-input-assembler.ts | 18 +++ 9 files changed, 214 insertions(+), 107 deletions(-) diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 7fc6c7f047..a0139dcf38 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -1,6 +1,29 @@ -import { GFXBufferUsage, GFXBufferUsageBit, GFXMemoryUsage, GFXMemoryUsageBit, GFXObject, GFXObjectType } from './define'; +import { + GFXBufferUsage, + GFXBufferUsageBit, + GFXMemoryUsage, + GFXMemoryUsageBit, + GFXObject, + GFXObjectType, +} from './define'; import { GFXDevice } from './device'; +export interface IGFXDrawInfo { + vertexCount: number; + firstVertex: number; + indexCount: number; + firstIndex: number; + vertexOffset: number; + instanceCount: number; + firstInstance: number; +} + +export interface IGFXIndirectBuffer { + drawInfos: IGFXDrawInfo[]; +} + +export type GFXBufferSource = ArrayBuffer | IGFXIndirectBuffer; + export interface IGFXBufferInfo { usage: GFXBufferUsage; memUsage: GFXMemoryUsage; @@ -26,7 +49,7 @@ export abstract class GFXBuffer extends GFXObject { return this._stride; } - public get buffer (): ArrayBuffer | null { + public get buffer (): GFXBufferSource | null { return this._buffer; } @@ -35,7 +58,7 @@ export abstract class GFXBuffer extends GFXObject { protected _memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; protected _size: number = 0; protected _stride: number = 1; - protected _buffer: ArrayBuffer | null = null; + protected _buffer: GFXBufferSource | null = null; constructor (device: GFXDevice) { super(GFXObjectType.BUFFER); @@ -44,5 +67,5 @@ export abstract class GFXBuffer extends GFXObject { public abstract initialize (info: IGFXBufferInfo): boolean; public abstract destroy (): void; - public abstract update (buffer: ArrayBuffer, offset?: number, size?: number); + public abstract update (buffer: GFXBufferSource, offset?: number, size?: number); } diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index a9ba2b7693..bdd39ff117 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -253,6 +253,7 @@ export enum GFXBufferUsageBit { VERTEX = 0x8, UNIFORM = 0x10, STORAGE = 0x20, + INDIRECT = 0x40, } export type GFXBufferUsage = GFXBufferUsageBit; diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 1baca3e5e0..9061730b13 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,4 +1,4 @@ -import { GFXBuffer } from './buffer'; +import { GFXBuffer, IGFXDrawInfo } from './buffer'; import { GFXFormat, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; @@ -16,6 +16,7 @@ export interface IGFXInputAssemblerInfo { vertexBuffers: GFXBuffer[]; indexBuffer?: GFXBuffer; isIndirect?: boolean; + indirectBuffer?: GFXBuffer; } export abstract class GFXInputAssembler extends GFXObject { @@ -88,6 +89,22 @@ export abstract class GFXInputAssembler extends GFXObject { this._firstInstance = first; } + public get isIndirect (): boolean { + return this._isIndirect; + } + + public set indirects (drawInfos: IGFXDrawInfo[]) { + this.indirects = drawInfos; + } + + public get indirects (): IGFXDrawInfo[] { + return this._indirects; + } + + public get indirectBuffer (): GFXBuffer | null { + return this._indirectBuffer; + } + protected _device: GFXDevice; protected _attributes: IGFXInputAttribute[] = []; protected _vertexBuffers: GFXBuffer[] = []; @@ -100,6 +117,8 @@ export abstract class GFXInputAssembler extends GFXObject { protected _instanceCount: number = 0; protected _firstInstance: number = 0; protected _isIndirect: boolean = false; + protected _indirects: IGFXDrawInfo[] = []; + protected _indirectBuffer: GFXBuffer | null = null; constructor (device: GFXDevice) { super(GFXObjectType.INPUT_ASSEMBLER); diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 33243d3099..04fe330f9a 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,5 +1,5 @@ -import { GFXBuffer, IGFXBufferInfo } from '../buffer'; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXStatus } from '../define'; +import { GFXBuffer, IGFXBufferInfo, GFXBufferSource } from '../buffer'; +import { GFXMemoryUsageBit, GFXStatus, GFXBufferUsageBit } from '../define'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; @@ -32,7 +32,12 @@ export class WebGLGFXBuffer extends GFXBuffer { this._stride = Math.max(this._stride, 1); if (this._memUsage & GFXMemoryUsageBit.HOST) { - this._buffer = new ArrayBuffer(this._size); + + if (!(this._usage & GFXBufferUsageBit.INDIRECT)) { + this._buffer = new ArrayBuffer(this._size); + } else { + this._buffer = { drawInfos: [] }; + } } // this._isSimulate = (this._usage & GFXBufferUsageBit.TRANSFER_SRC) != GFXBufferUsageBit.NONE; @@ -52,14 +57,22 @@ export class WebGLGFXBuffer extends GFXBuffer { this._status = GFXStatus.UNREADY; } - public update (buffer: ArrayBuffer, offset?: number, size?: number) { + public update (buffer: GFXBufferSource, offset?: number, size?: number) { // const isUniformBuffer = (this._usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; + let buffSize; + if (size !== undefined ) { + buffSize = size; + } else if (this._usage & GFXBufferUsageBit.INDIRECT) { + buffSize = 0; + } else { + buffSize = (buffer as ArrayBuffer).byteLength; + } this.webGLDevice.emitCmdUpdateGPUBuffer( this._gpuBuffer as WebGLGPUBuffer, buffer, offset !== undefined ? offset : 0, - size !== undefined ? size : buffer.byteLength); + buffSize); } } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 8e7136bf87..74486d1f12 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,7 +1,7 @@ import { GFXBindingLayout } from '../binding-layout'; -import { GFXBuffer } from '../buffer'; +import { GFXBuffer, GFXBufferSource } from '../buffer'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; -import { GFXBufferTextureCopy, GFXStatus, GFXTextureLayout, IGFXColor, IGFXRect } from '../define'; +import { GFXBufferTextureCopy, GFXStatus, GFXTextureLayout, IGFXColor, IGFXRect, GFXBufferUsageBit } from '../define'; import { GFXDevice } from '../device'; import { GFXFramebuffer } from '../framebuffer'; import { GFXInputAssembler } from '../input-assembler'; @@ -94,18 +94,27 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public bindPipelineState (pipelineState: GFXPipelineState) { - this._curGPUPipelineState = (pipelineState as WebGLGFXPipelineState).gpuPipelineState; - this._isStateInvalied = true; + const gpuPipelineState = (pipelineState as WebGLGFXPipelineState).gpuPipelineState; + if (this._curGPUPipelineState !== gpuPipelineState) { + this._curGPUPipelineState = gpuPipelineState; + this._isStateInvalied = true; + } } public bindBindingLayout (bindingLayout: GFXBindingLayout) { - this._curGPUBindingLayout = (bindingLayout as WebGLGFXBindingLayout).gpuBindingLayout; - this._isStateInvalied = true; + const gpuBindingLayout = (bindingLayout as WebGLGFXBindingLayout).gpuBindingLayout; + if (this._curGPUBindingLayout !== gpuBindingLayout) { + this._curGPUBindingLayout = gpuBindingLayout; + this._isStateInvalied = true; + } } public bindInputAssembler (inputAssembler: GFXInputAssembler) { - this._curGPUInputAssembler = (inputAssembler as WebGLGFXInputAssembler).gpuInputAssembler; - this._isStateInvalied = true; + const gpuInputAssembler = (inputAssembler as WebGLGFXInputAssembler).gpuInputAssembler; + if (this._curGPUInputAssembler !== gpuInputAssembler) { + this._curGPUInputAssembler = gpuInputAssembler; + this._isStateInvalied = true; + } } public draw (inputAssembler: GFXInputAssembler) { @@ -117,29 +126,35 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { const cmd = ( this._allocator as WebGLGFXCommandAllocator). drawCmdPool.alloc(WebGLCmdDraw); if (cmd) { - cmd.vertexCount = inputAssembler.vertexCount; - cmd.firstVertex = inputAssembler.firstVertex; - cmd.indexCount = inputAssembler.indexCount; - cmd.firstIndex = inputAssembler.firstIndex; - cmd.vertexOffset = inputAssembler.vertexOffset; - cmd.instanceCount = inputAssembler.instanceCount; - cmd.firstInstance = inputAssembler.firstInstance; - + (inputAssembler as WebGLGFXInputAssembler).extractCmdDraw(cmd); this.cmdPackage.drawCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.DRAW); } } - public updateBuffer (buffer: GFXBuffer, data: ArrayBuffer, offset?: number) { + public updateBuffer (buffer: GFXBuffer, data: GFXBufferSource, offset?: number, size?: number) { const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; if (gpuBuffer) { const cmd = (this._allocator as WebGLGFXCommandAllocator). updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { + + let buffSize; + if (size !== undefined ) { + buffSize = size; + } else if (buffer.usage & GFXBufferUsageBit.INDIRECT) { + buffSize = 0; + } else { + buffSize = (data as ArrayBuffer).byteLength; + } + + const buff = data as ArrayBuffer; + cmd.gpuBuffer = gpuBuffer; - cmd.buffer = data.slice(0); + cmd.buffer = buff.slice(0); cmd.offset = (offset !== undefined ? offset : 0); + cmd.size = buffSize; this.cmdPackage.updateBufferCmds.push(cmd); this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index c869964ff8..9310c3b284 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,3 +1,4 @@ +import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, GFXCullMode, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, GFXMemoryUsageBit, GFXShaderType, GFXTextureFlagBit, GFXTextureLayout, GFXTextureViewType, @@ -382,15 +383,18 @@ export class WebGLCmdBindStates extends WebGLCmdObject { export class WebGLCmdDraw extends WebGLCmdObject { - public vertexCount: number = 0; - public firstVertex: number = 0; + public drawInfo: IGFXDrawInfo = { + vertexCount: 0, + firstVertex: 0, + indexCount: 0, + firstIndex: 0, + vertexOffset: 0, + instanceCount: 0, + firstInstance: 0, + }; - public indexCount: number = 0; - public firstIndex: number = 0; - public vertexOffset: number = 0; - - public instanceCount: number = 0; - public firstInstance: number = 0; + public isIndirect: boolean = false; + public gpuIndirectBuffer: WebGLGPUBuffer | null = null; constructor () { super(WebGLCmd.DRAW); @@ -400,8 +404,9 @@ export class WebGLCmdDraw extends WebGLCmdObject { export class WebGLCmdUpdateBuffer extends WebGLCmdObject { public gpuBuffer: WebGLGPUBuffer | null = null; - public buffer: ArrayBuffer | null = null; + public buffer: GFXBufferSource | null = null; public offset: number = 0; + public size: number = 0; constructor () { super(WebGLCmd.UPDATE_BUFFER); @@ -530,9 +535,10 @@ export function WebGLCmdFuncCreateBuffer (device: WebGLGFXDevice, gpuBuffer: Web gpuBuffer.glTarget = WebGLRenderingContext.NONE; if (gpuBuffer.buffer) { - gpuBuffer.viewF32 = new Float32Array(gpuBuffer.buffer); + gpuBuffer.viewF32 = new Float32Array(gpuBuffer.buffer as ArrayBuffer); } - + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_DST) { gpuBuffer.glTarget = WebGLRenderingContext.NONE; } else if (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) { @@ -550,13 +556,16 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: We } } -export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: ArrayBuffer, offset: number, size: number) { +export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { if (gpuBuffer.viewF32 && buffer) { - gpuBuffer.viewF32.set(new Float32Array(buffer, 0, size / 4), offset); + gpuBuffer.viewF32.set(new Float32Array(buffer as ArrayBuffer, 0, size / 4), offset); } + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { + gpuBuffer.buffer = buffer; } else { + const buff = buffer as ArrayBuffer; const gl = device.gl; switch (gpuBuffer.glTarget) { @@ -566,10 +575,10 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: Web device.stateCache.glArrayBuffer = gpuBuffer.glBuffer; } - if (size === buffer.byteLength) { - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buffer, 0, size)); + gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buff, 0, size)); } break; @@ -580,10 +589,10 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: Web device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - if (size === buffer.byteLength) { - gl.bufferSubData(gpuBuffer.glTarget, offset, buffer); + if (size === buff.byteLength) { + gl.bufferSubData(gpuBuffer.glTarget, offset, buff); } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buffer, 0, size)); + gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buff, 0, size)); } break; @@ -1499,7 +1508,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web catchTarget0.blendColorMask = target0.blendColorMask; } } // blend state - } + } // bind pso if (cmd2.gpuBindingLayout && gpuShader) { for (const gpuBinding of cmd2.gpuBindingLayout.gpuBindings) { @@ -1817,14 +1826,9 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } // bind binding layout - gpuInputAssembler = cmd2.gpuInputAssembler; + if (cmd2.gpuInputAssembler && gpuShader) { + gpuInputAssembler = cmd2.gpuInputAssembler; - break; - } - case WebGLCmd.DRAW: { - const cmd3: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; - - if (gpuInputAssembler && gpuShader) { for (let a = 0; a < device.maxVertexAttributes; ++a) { device.stateCache.glCurrentAttribLocs[a] = false; } @@ -1858,20 +1862,14 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset); } } - } // if - - if (gpuInputAssembler.gpuIndexBuffer && cmd3.indexCount > 0) { - const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + } // for + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + if (gpuBuffer) { if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer; } - - const offset = cmd3.firstIndex * gpuBuffer.stride; - gl.drawElements(glPrimitive, cmd3.indexCount, gpuInputAssembler.glIndexType, offset); - } else { - gl.drawArrays(glPrimitive, cmd3.firstVertex, cmd3.vertexCount); } for (let a = 0; a < device.maxVertexAttributes; ++a) { @@ -1881,52 +1879,57 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } } + + break; + } + case WebGLCmd.DRAW: { + const cmd3: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; + if (gpuInputAssembler && gpuShader) { + if (!cmd3.isIndirect) { + const drawInfo = cmd3.drawInfo as IGFXDrawInfo; + + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + if (gpuBuffer && drawInfo.indexCount > 0) { + const offset = drawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); + } + } else { + if (cmd3.gpuIndirectBuffer) { + const drawInfos = (cmd3.gpuIndirectBuffer.buffer as IGFXIndirectBuffer).drawInfos; + for (const drawInfo of drawInfos) { + const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; + if (gpuBuffer && drawInfo.indexCount > 0) { + const offset = drawInfo.firstIndex * gpuBuffer.stride; + gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); + } else { + gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount); + } + } + } + } + } break; } case WebGLCmd.UPDATE_BUFFER: { const cmd4 = cmdPackage.updateBufferCmds[cmdId]; - if (cmd4.gpuBuffer) { - - if (cmd4.buffer) { - if (cmd4.gpuBuffer.viewF32) { - cmd4.gpuBuffer.viewF32.set(new Float32Array(cmd4.buffer), cmd4.offset); - } - } - - switch (cmd4.gpuBuffer.glTarget) { - case WebGLRenderingContext.ARRAY_BUFFER: { - if (device.stateCache.glArrayBuffer !== cmd4.gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, cmd4.gpuBuffer.glBuffer); - device.stateCache.glArrayBuffer = cmd4.gpuBuffer.glBuffer; - } - - if (cmd4.buffer) { - gl.bufferSubData(cmd4.gpuBuffer.glTarget, cmd4.offset, cmd4.buffer); - } - break; - } - case WebGLRenderingContext.ELEMENT_ARRAY_BUFFER: { - if (device.stateCache.glElementArrayBuffer !== cmd4.gpuBuffer.glBuffer) { - gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, cmd4.gpuBuffer.glBuffer); - device.stateCache.glElementArrayBuffer = cmd4.gpuBuffer.glBuffer; - } - - if (cmd4.buffer) { - gl.bufferSubData(cmd4.gpuBuffer.glTarget, cmd4.offset, cmd4.buffer); - } - break; - } - default: - } - } + WebGLCmdFuncUpdateBuffer( + device, + cmd4.gpuBuffer as WebGLGPUBuffer, + cmd4.buffer as GFXBufferSource, + cmd4.offset, + cmd4.size); break; } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { const cmd5 = cmdPackage.copyBufferToTextureCmds[cmdId]; - if (cmd5.gpuBuffer && cmd5.gpuBuffer.buffer && cmd5.gpuTexture) { - WebGLCmdFuncCopyBufferToTexture(device, cmd5.gpuBuffer.buffer, cmd5.gpuTexture, cmd5.regions); - } + WebGLCmdFuncCopyBufferToTexture( + device, + (cmd5.gpuBuffer as WebGLGPUBuffer).buffer as GFXBufferSource, + cmd5.gpuTexture as WebGLGPUTexture, + cmd5.regions); break; } @@ -1936,13 +1939,13 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web export function WebGLCmdFuncCopyBufferToTexture ( device: WebGLGFXDevice, - buffer: ArrayBuffer, + buffer: GFXBufferSource, gpuTexture: WebGLGPUTexture, regions: GFXBufferTextureCopy[]) { const gl = device.gl; - const bufferView = new Uint8Array(buffer); + const bufferView = new Uint8Array(buffer as ArrayBuffer); switch (gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 148492ed7e..1fb69c7897 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,5 +1,5 @@ import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; -import { GFXBuffer, IGFXBufferInfo } from '../buffer'; +import { GFXBuffer, IGFXBufferInfo, GFXBufferSource } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXFilter, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXQueueType, GFXTextureFlagBit, GFXTextureType, GFXTextureViewType } from '../define'; @@ -506,7 +506,7 @@ export class WebGLGFXDevice extends GFXDevice { } } - public emitCmdCreateGPUBuffer (info: IGFXBufferInfo, buffer: ArrayBuffer | null): WebGLGPUBuffer | null { + public emitCmdCreateGPUBuffer (info: IGFXBufferInfo, buffer: GFXBufferSource | null): WebGLGPUBuffer | null { const gpuBuffer: WebGLGPUBuffer = { objType: WebGLGPUObjectType.BUFFER, @@ -539,7 +539,7 @@ export class WebGLGFXDevice extends GFXDevice { WebGLCmdFuncDestroyBuffer(this as WebGLGFXDevice, gpuBuffer); } - public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: ArrayBuffer, offset: number, size: number) { + public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { // TODO: Async const isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; if (!isStagingBuffer) { @@ -934,6 +934,8 @@ export class WebGLGFXDevice extends GFXDevice { attributes: info.attributes, gpuVertexBuffers, gpuIndexBuffer, + isIndirect: (info.isIndirect !== undefined ? info.isIndirect : false), + gpuIndirectBuffers: [], glAttribs: [], glIndexType, diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 790440838e..0f4956c057 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -3,6 +3,7 @@ import { IGFXInputAttribute } from '../input-assembler'; import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../pipeline-state'; import { GFXColorAttachment, GFXDepthStencilAttachment } from '../render-pass'; import { GFXUniformBlock, GFXUniformSampler, IGFXShaderMacro } from '../shader'; +import { GFXBufferSource } from '../buffer'; export enum WebGLGPUObjectType { UNKNOWN, @@ -27,6 +28,16 @@ export class WebGLGPUObject { } } +export interface IWebGLIndirectBuffer { + vertexCount: number; + firstVertex: number; + indexCount: number; + firstIndex: number; + vertexOffset: number; + instanceCount: number; + firstInstance: number; +} + export class WebGLGPUBuffer extends WebGLGPUObject { public usage: GFXBufferUsage = GFXBufferUsageBit.NONE; public memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; @@ -35,7 +46,7 @@ export class WebGLGPUBuffer extends WebGLGPUObject { public glTarget: GLenum = 0; public glBuffer: WebGLBuffer = 0; - public buffer: ArrayBuffer | null = null; + public buffer: GFXBufferSource | null = null; public viewF32: Float32Array | null = null; constructor () { @@ -244,6 +255,8 @@ export class WebGLGPUInputAssembler extends WebGLGPUObject { public attributes: IGFXInputAttribute[] = []; public gpuVertexBuffers: WebGLGPUBuffer[] = []; public gpuIndexBuffer: WebGLGPUBuffer | null = null; + public isIndirect: boolean = false; + public gpuIndirectBuffers: IWebGLIndirectBuffer[] = []; public glAttribs: WebGLAttrib[] = []; public glIndexType: GLenum = 0; diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index 6da551bc93..4551e19ce2 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -1,6 +1,8 @@ import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; +import { WebGLGFXBuffer } from './webgl-buffer'; +import { WebGLCmdDraw } from './webgl-commands'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUInputAssembler } from './webgl-gpu-objects'; @@ -55,4 +57,20 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { } this._status = GFXStatus.UNREADY; } + + public extractCmdDraw (cmd: WebGLCmdDraw) { + cmd.isIndirect = this._isIndirect; + if (!this._isIndirect) { + cmd.drawInfo.vertexCount = this._vertexCount; + cmd.drawInfo.firstVertex = this._firstVertex; + cmd.drawInfo.indexCount = this._indexCount; + cmd.drawInfo.firstIndex = this._firstIndex; + cmd.drawInfo.vertexOffset = this._vertexOffset; + cmd.drawInfo.instanceCount = this._instanceCount; + cmd.drawInfo.firstInstance = this._firstInstance; + cmd.isIndirect = this._isIndirect; + } else { + cmd.gpuIndirectBuffer = (this._indirectBuffer as WebGLGFXBuffer).gpuBuffer; + } + } } From 150a01168f93268b78ca4b226aff29c3b240e101 Mon Sep 17 00:00:00 2001 From: Leslie Date: Fri, 11 Jan 2019 16:46:51 +0800 Subject: [PATCH 111/267] misc/utils.js: rename to ts; apply tslint autofmt --- cocos/3d/misc/utils.js | 69 ------------------------------------------ cocos/3d/misc/utils.ts | 69 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 69 deletions(-) delete mode 100644 cocos/3d/misc/utils.js create mode 100644 cocos/3d/misc/utils.ts diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js deleted file mode 100644 index d74cafab42..0000000000 --- a/cocos/3d/misc/utils.js +++ /dev/null @@ -1,69 +0,0 @@ -import { renderer } from '../../renderer'; -import find from '../../scene-graph/find'; -import { Mesh, RenderingMesh } from '../assets/mesh'; -import gfx from '../../renderer/gfx/index'; -import { GFXPrimitiveMode } from '../../gfx/define'; - -/** - * - * @param {import("../assets/skeleton").default} skinning - */ -function createJointsTexture(skinning) { - const jointCount = skinning.joints.length; - - // Set jointsTexture. - // A squared texture with side length N(N > 1) multiples of 2 can store - // 2 ^ (2 * N - 2) matrices. - // We support most 1024 joints. - let size; - if (jointCount > 1024) { - throw "To many joints(more than 1024)."; - } else if (jointCount > 256) { - size = 64; - } else if (jointCount > 64) { - size = 32; - } else if (jointCount > 16) { - size = 16; - } else if (jointCount > 4) { - size = 8; - } else { - size = 4; - } - - return new gfx.Texture2D(cc.game._renderContext, { - width: size, - height: size, - format: gfx.TEXTURE_FMT_RGBA32F, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - mipmap: false - }); -} - -function createMesh(context, data) { - let ia = renderer.createIA(context, data); - let meshAsset = new Mesh(); - const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; - meshAsset._renderingMesh = new RenderingMesh([{inputAssembler: ia, primitiveMode}], [], []); - meshAsset._minPosition = data.minPos; - meshAsset._maxPosition = data.maxPos; - - return meshAsset; -} - -/** - * @param {Uint8Array} buffer - */ -function toPPM(buffer, w, h) { - return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; -} - -export default { - createJointsTexture, - createMesh, - - find, - toPPM -}; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts new file mode 100644 index 0000000000..9d1a4b42f0 --- /dev/null +++ b/cocos/3d/misc/utils.ts @@ -0,0 +1,69 @@ +import { GFXPrimitiveMode } from '../../gfx/define'; +import * as renderer from '../../renderer'; +import gfx from '../../renderer/gfx/index'; +import find from '../../scene-graph/find'; +import { Mesh, RenderingMesh } from '../assets/mesh'; + +/** + * + * @param {import("../assets/skeleton").default} skinning + */ +function createJointsTexture (skinning) { + const jointCount = skinning.joints.length; + + // Set jointsTexture. + // A squared texture with side length N(N > 1) multiples of 2 can store + // 2 ^ (2 * N - 2) matrices. + // We support most 1024 joints. + let size; + if (jointCount > 1024) { + throw new Error('To many joints(more than 1024).'); + } else if (jointCount > 256) { + size = 64; + } else if (jointCount > 64) { + size = 32; + } else if (jointCount > 16) { + size = 16; + } else if (jointCount > 4) { + size = 8; + } else { + size = 4; + } + + return new gfx.Texture2D(cc.game._renderContext, { + width: size, + height: size, + format: gfx.TEXTURE_FMT_RGBA32F, + minFilter: gfx.FILTER_NEAREST, + magFilter: gfx.FILTER_NEAREST, + wrapS: gfx.WRAP_CLAMP, + wrapT: gfx.WRAP_CLAMP, + mipmap: false, + }); +} + +function createMesh (context, data) { + const ia = renderer.createIA(context, data); + const meshAsset = new Mesh(); + const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; + meshAsset._renderingMesh = new RenderingMesh([{ inputAssembler: ia, primitiveMode }], [], []); + meshAsset._minPosition = data.minPos; + meshAsset._maxPosition = data.maxPos; + + return meshAsset; +} + +/** + * @param {Uint8Array} buffer + */ +function toPPM (buffer, w, h) { + return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; +} + +export default { + createJointsTexture, + createMesh, + + find, + toPPM, +}; From c3be94b6c6c37a938efb10e7809b4fdbf37e9ee5 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 10:45:28 +0800 Subject: [PATCH 112/267] adjust texture assets' struct, put most create logic to texture-base --- cocos/3d/assets/texture-cube.ts | 45 ++++++--------- .../3d/framework/skinning-model-component.js | 2 +- cocos/3d/index.js | 2 +- cocos/3d/misc/utils.ts | 39 +++++-------- cocos/assets/texture-2d.ts | 35 ++---------- cocos/assets/texture-base.ts | 55 ++++++++++++++----- 6 files changed, 76 insertions(+), 102 deletions(-) diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 02468a164b..9b508c941e 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -27,8 +27,7 @@ import { Texture2D } from '../../assets'; import ImageAsset from '../../assets/image-asset'; import TextureBase from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; -import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType, GFXTextureFlagBit } from '../../gfx/define'; -import { GFXDevice } from '../../gfx/device'; +import { GFXTextureFlagBit, GFXTextureViewType } from '../../gfx/define'; interface ITextureCubeMipmap { front: ImageAsset; @@ -54,9 +53,11 @@ export default class TextureCube extends TextureBase { */ set mipmaps (value) { this._mipmaps = value; - this._potientialWidth = value.length === 0 ? 0 : value[0].front.width; - this._potientialHeight = value.length === 0 ? 0 : value[0].front.height; - this._recreateTexture(); + this.create( + value.length === 0 ? 0 : value[0].front.width, + value.length === 0 ? 0 : value[0].front.height, + undefined, + this._mipmaps.length); this._mipmaps.forEach((mipmap, level) => { _forEachFace(mipmap, (face, faceIndex) => { this._assignImage(face, level, faceIndex); @@ -171,32 +172,18 @@ export default class TextureCube extends TextureBase { } } - protected _createTextureImpl (gfxDevice: GFXDevice) { - this._texture = gfxDevice.createTexture({ - type: GFXTextureType.TEX2D, - /* tslint:disable:no-bitwise */ - usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, - /* tslint:enable:no-bitwise */ - format: this._getGfxFormat(), - width: this._potientialWidth, - height: this._potientialHeight, - mipLevel: this._mipmaps.length, - arrayLayer: 6, - flags: GFXTextureFlagBit.CUBEMAP, - }); + protected _getTextureCreateInfo () { + const result = super._getTextureCreateInfo(); + result.arrayLayer = 6; + result.flags = result.flags | GFXTextureFlagBit.CUBEMAP; + return result; } - protected _createTextureViewImpl (gfxDevice: GFXDevice) { - if (!this._texture) { - return; - } - - this._textureView = gfxDevice.createTextureView({ - texture: this._texture, - type: GFXTextureViewType.CUBE, - format: this._getGfxFormat(), - layerCount: 6, - }); + protected _getTextureViewCreateInfo () { + const result = super._getTextureViewCreateInfo(); + result.type = GFXTextureViewType.CUBE; + result.layerCount = 6; + return result; } } diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js index c170eb5617..858acd6ddb 100644 --- a/cocos/3d/framework/skinning-model-component.js +++ b/cocos/3d/framework/skinning-model-component.js @@ -28,7 +28,7 @@ import { mat4 } from '../../core/vmath'; import ModelComponent from './model-component'; import { renderer } from '../../renderer/index'; import { ccclass, property, executionOrder, menu,executeInEditMode } from '../../core/data/class-decorator'; -import utils from '../misc/utils'; +import * as utils from '../misc/utils'; import Skeleton from '../assets/skeleton'; import { Node } from '../../scene-graph/node'; diff --git a/cocos/3d/index.js b/cocos/3d/index.js index 8f70aeeed1..32a86b567a 100644 --- a/cocos/3d/index.js +++ b/cocos/3d/index.js @@ -27,7 +27,7 @@ export * from './assets'; export * from './builtin'; export * from './framework'; export * from './memop'; -import utils from './misc/utils'; +import * as utils from './misc/utils'; import * as primitives from './primitive'; import * as geometry from './geom-utils'; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 9d1a4b42f0..46c82198a9 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -1,21 +1,21 @@ import { GFXPrimitiveMode } from '../../gfx/define'; import * as renderer from '../../renderer'; -import gfx from '../../renderer/gfx/index'; -import find from '../../scene-graph/find'; +export { default as find } from '../../scene-graph/find'; +import Texture2D from '../../assets/texture-2d'; +import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; import { Mesh, RenderingMesh } from '../assets/mesh'; /** * - * @param {import("../assets/skeleton").default} skinning */ -function createJointsTexture (skinning) { +export function createJointsTexture (skinning: { joints: any[]; }) { const jointCount = skinning.joints.length; // Set jointsTexture. // A squared texture with side length N(N > 1) multiples of 2 can store // 2 ^ (2 * N - 2) matrices. // We support most 1024 joints. - let size; + let size = 0; if (jointCount > 1024) { throw new Error('To many joints(more than 1024).'); } else if (jointCount > 256) { @@ -30,19 +30,14 @@ function createJointsTexture (skinning) { size = 4; } - return new gfx.Texture2D(cc.game._renderContext, { - width: size, - height: size, - format: gfx.TEXTURE_FMT_RGBA32F, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - mipmap: false, - }); + const texture = new Texture2D(); + texture.create(size, size, PixelFormat.RGBA32F); + texture.setFilters(Filter.NEAREST, Filter.NEAREST); + texture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return texture; } -function createMesh (context, data) { +export function createMesh (context, data) { const ia = renderer.createIA(context, data); const meshAsset = new Mesh(); const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; @@ -54,16 +49,8 @@ function createMesh (context, data) { } /** - * @param {Uint8Array} buffer + * */ -function toPPM (buffer, w, h) { +export function toPPM (buffer: Uint8Array, w: number, h: number) { return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; } - -export default { - createJointsTexture, - createMesh, - - find, - toPPM, -}; diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index 4cc7b76b9c..30c621caef 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -25,8 +25,6 @@ ****************************************************************************/ // @ts-check import { ccclass, property } from '../core/data/class-decorator'; -import { GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; -import { GFXDevice } from '../gfx/device'; import ImageAsset from './image-asset'; import TextureBase from './texture-base'; @@ -48,9 +46,11 @@ export default class Texture2D extends TextureBase { */ set mipmaps (value) { this._mipmaps = value; - this._potientialWidth = value.length === 0 ? 0 : value[0].width; - this._potientialHeight = value.length === 0 ? 0 : value[0].height; - this._recreateTexture(); + this.create( + value.length === 0 ? 0 : value[0].width, + value.length === 0 ? 0 : value[0].height, + undefined, + this._mipmaps.length); this._mipmaps.forEach((mipmap, level) => { this._assignImage(mipmap, level); }); @@ -180,31 +180,6 @@ export default class Texture2D extends TextureBase { handle.result.push(this._mipmaps, `${i}`, mipmapUUID); } } - - protected _createTextureImpl (gfxDevice: GFXDevice) { - this._texture = gfxDevice.createTexture({ - type: GFXTextureType.TEX2D, - /* tslint:disable:no-bitwise */ - usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, - /* tslint:enable:no-bitwise */ - format: this._getGfxFormat(), - width: this._potientialWidth, - height: this._potientialHeight, - mipLevel: this._mipmaps.length, - }); - } - - protected _createTextureViewImpl (gfxDevice: GFXDevice) { - if (!this._texture) { - return; - } - - this._textureView = gfxDevice.createTextureView({ - texture: this._texture, - type: GFXTextureViewType.TV2D, - format: this._getGfxFormat(), - }); - } } /* tslint:disable:no-string-literal */ diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 2b4ab8881b..33450e9cff 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -29,11 +29,12 @@ import EventTarget from '../core/event/event-target'; import IDGenerator from '../core/utils/id-generator'; import {addon} from '../core/utils/js'; import { ccenum } from '../core/value-types/enum'; -import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat } from '../gfx/define'; +import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat, + GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; import { GFXSampler } from '../gfx/sampler'; -import { GFXTexture } from '../gfx/texture'; -import { GFXTextureView } from '../gfx/texture-view'; +import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; +import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; import { Asset } from './asset'; import ImageAsset from './image-asset'; @@ -200,9 +201,11 @@ export default class TextureBase extends Asset { protected _textureView: GFXTextureView | null = null; - protected _potientialWidth: number = 0; + private _potientialWidth: number = 0; - protected _potientialHeight: number = 0; + private _potientialHeight: number = 0; + + private _mipmapLevel: number = 1; @property private _genMipmap = false; @@ -260,6 +263,14 @@ export default class TextureBase extends Asset { this.loaded = false; } + public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1) { + this._potientialWidth = width; + this._potientialHeight = height; + this._format = format; + this._mipmapLevel = 1; + this._recreateTexture(); + } + /** * Gets the underlying texture object. * @deprecated Use getGfxTexture() instead. @@ -475,6 +486,7 @@ export default class TextureBase extends Asset { } protected _getGlobalDevice (): GFXDevice | null { + // @ts-ignore return cc.director.root.device; } @@ -543,6 +555,27 @@ export default class TextureBase extends Asset { } } + protected _getTextureCreateInfo (): IGFXTextureInfo { + return { + type: GFXTextureType.TEX2D, + /* tslint:disable:no-bitwise */ + usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, + /* tslint:enable:no-bitwise */ + format: toGfxFormat(this._format), + width: this._potientialWidth, + height: this._potientialHeight, + mipLevel: this._mipmapLevel, + }; + } + + protected _getTextureViewCreateInfo (): IGFXTextureViewInfo { + return { + texture: this._texture, + type: GFXTextureViewType.TV2D, + format: this._getGfxFormat(), + }; + } + protected _recreateTexture () { this._destroyTexture(); @@ -551,17 +584,9 @@ export default class TextureBase extends Asset { return; } - this._createTextureImpl(gfxDevice); + this._texture = gfxDevice.createTexture(this._getTextureCreateInfo()); - this._createTextureViewImpl(gfxDevice); - } - - protected _createTextureImpl (gfxDevice: GFXDevice) { - return; - } - - protected _createTextureViewImpl (gfxDevice: GFXDevice) { - return; + this._textureView = gfxDevice.createTextureView(this._getTextureViewCreateInfo()); } private _destroyTexture () { From 71e8d22c16d5e12e6f08a7915bdbac5effba020d Mon Sep 17 00:00:00 2001 From: Leslie Date: Fri, 11 Jan 2019 16:34:13 +0800 Subject: [PATCH 113/267] module exports --- cocos/3d/debugger/draw-mng.js | 2 +- cocos/3d/debugger/index.js | 2 +- cocos/3d/debugger/utils.js | 2 +- cocos/3d/framework/light-component.js | 2 +- .../renderer/particle-system-renderer.js | 2 +- cocos/3d/framework/render-system.js | 2 +- .../3d/framework/skinning-model-component.js | 2 +- cocos/3d/framework/skybox-component.js | 2 +- cocos/core/game.js | 2 +- cocos/renderer/core/array-buffer-helper.js | 2 +- cocos/renderer/core/base-renderer.js | 2 +- cocos/renderer/core/buffer-pool.js | 2 +- cocos/renderer/core/dynamic-ia-pool.js | 2 +- cocos/renderer/core/view.js | 2 +- cocos/renderer/enums.js | 82 +++++++++---------- cocos/renderer/index.js | 69 +++++----------- cocos/renderer/renderers/forward-renderer.js | 2 +- cocos/renderer/scene/light.js | 2 +- index.js | 4 +- 19 files changed, 78 insertions(+), 109 deletions(-) diff --git a/cocos/3d/debugger/draw-mng.js b/cocos/3d/debugger/draw-mng.js index e4e211cea3..590b0e53e8 100644 --- a/cocos/3d/debugger/draw-mng.js +++ b/cocos/3d/debugger/draw-mng.js @@ -2,7 +2,7 @@ import { vec3, color3, mat4 } from '../vmath'; import { LinkedArray } from '../memop'; import { Node } from '../scene-graph'; import gfx from '../gfx'; -import { renderer } from '../renderer'; +import * as renderer from '../renderer'; import { sphere, wireframe } from '../primitives'; let _right = vec3.create(1, 0, 0); diff --git a/cocos/3d/debugger/index.js b/cocos/3d/debugger/index.js index 0cf5cfbaf5..eb7518cfe3 100644 --- a/cocos/3d/debugger/index.js +++ b/cocos/3d/debugger/index.js @@ -1,4 +1,4 @@ -import { renderer } from '../../renderer'; +import * as renderer from '../../renderer'; import OrbitCamera from './orbit-camera'; import DrawMng from './draw-mng'; import { createGrid } from './utils'; diff --git a/cocos/3d/debugger/utils.js b/cocos/3d/debugger/utils.js index d42febdbca..a84285605f 100644 --- a/cocos/3d/debugger/utils.js +++ b/cocos/3d/debugger/utils.js @@ -1,4 +1,4 @@ -import { renderer } from '../renderer'; +import * as renderer from '../renderer'; import { vec3, color3 } from '../vmath'; import { Node } from '../scene-graph'; diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js index 01493bba33..c971d73853 100644 --- a/cocos/3d/framework/light-component.js +++ b/cocos/3d/framework/light-component.js @@ -24,7 +24,7 @@ ****************************************************************************/ // @ts-check import RenderSystemActor from './renderSystemActor'; -import { renderer } from '../../renderer/index'; +import * as renderer from '../../renderer/index'; import { Color, Enum } from '../../core/value-types'; import { toRadian } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-renderer.js index 6af38c78ee..64d3415226 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.js +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.js @@ -1,4 +1,4 @@ -import { renderer } from '../../../../renderer'; +import * as renderer from '../../../../renderer'; import { vec3, vec4, vec2, mat4 } from '../../../../core/vmath'; import gfx from '../../../../renderer/gfx'; import { Material } from '../../../assets/material'; diff --git a/cocos/3d/framework/render-system.js b/cocos/3d/framework/render-system.js index d51bd637bb..424e3f5006 100644 --- a/cocos/3d/framework/render-system.js +++ b/cocos/3d/framework/render-system.js @@ -1,4 +1,4 @@ -import { renderer } from '../../renderer'; +import * as renderer from '../../renderer'; export default class RenderSystem { constructor () { this._scene = new renderer.Scene(); diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js index 858acd6ddb..46aaf107f3 100644 --- a/cocos/3d/framework/skinning-model-component.js +++ b/cocos/3d/framework/skinning-model-component.js @@ -26,7 +26,7 @@ // @ts-check import { mat4 } from '../../core/vmath'; import ModelComponent from './model-component'; -import { renderer } from '../../renderer/index'; +import * as renderer from '../../renderer/index'; import { ccclass, property, executionOrder, menu,executeInEditMode } from '../../core/data/class-decorator'; import * as utils from '../misc/utils'; import Skeleton from '../assets/skeleton'; diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js index 37e73dcb8a..a913871413 100644 --- a/cocos/3d/framework/skybox-component.js +++ b/cocos/3d/framework/skybox-component.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import { renderer } from '../../renderer/index'; +import * as renderer from '../../renderer/index'; import { box } from '../primitive/index'; import { Material } from '../assets/material'; import { ccclass, property, menu, executeInEditMode } from '../../core/data/class-decorator'; diff --git a/cocos/core/game.js b/cocos/core/game.js index d2e9bfc0ef..ac46a63bec 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -29,7 +29,7 @@ import inputManager from './platform/event-manager/CCInputManager'; import debug from './platform/CCDebug'; import { addon } from './utils/js'; -import { renderer } from '../renderer'; +import * as renderer from '../renderer'; import gfx from '../renderer/gfx'; import builtinResMgr from '../3d/builtin/init'; import { ProgramLib } from '../renderer/core/program-lib'; diff --git a/cocos/renderer/core/array-buffer-helper.js b/cocos/renderer/core/array-buffer-helper.js index c419e17031..bb660772d4 100644 --- a/cocos/renderer/core/array-buffer-helper.js +++ b/cocos/renderer/core/array-buffer-helper.js @@ -1,6 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import enums from '../enums'; +import * as enums from '../enums'; function _defineProperty(target, name, internalName, arrayFn) { target[internalName] = new arrayFn(target._data); diff --git a/cocos/renderer/core/base-renderer.js b/cocos/renderer/core/base-renderer.js index 7a74ba46f6..9f8fa041cf 100644 --- a/cocos/renderer/core/base-renderer.js +++ b/cocos/renderer/core/base-renderer.js @@ -4,7 +4,7 @@ import { RecyclePool } from '../../3d/memop'; import { vec2, vec3, vec4, mat2, mat3, mat4, color3, color4 } from '../../core/vmath'; import { intersect } from '../../3d/geom-utils'; -import enums from '../enums'; +import * as enums from '../enums'; import View from './view'; import { ProgramLib } from './program-lib'; import { RenderQueue } from './constants'; diff --git a/cocos/renderer/core/buffer-pool.js b/cocos/renderer/core/buffer-pool.js index d9d7052574..c0868f631b 100644 --- a/cocos/renderer/core/buffer-pool.js +++ b/cocos/renderer/core/buffer-pool.js @@ -2,7 +2,7 @@ import { bits } from '../../core/vmath'; import ArrayBufferHelper from './array-buffer-helper'; -import enums from '../enums'; +import * as enums from '../enums'; const _DEFAULT_MAX_BATCH_BYTES = 512000; // 500 kb const _MIN_BATCH_BYTES = 64; diff --git a/cocos/renderer/core/dynamic-ia-pool.js b/cocos/renderer/core/dynamic-ia-pool.js index c2e6529c7f..70bfa85ecd 100644 --- a/cocos/renderer/core/dynamic-ia-pool.js +++ b/cocos/renderer/core/dynamic-ia-pool.js @@ -4,7 +4,7 @@ import gfx from '../gfx'; import { CircularPool } from '../../3d/memop'; import InputAssembler from './input-assembler'; import BufferPool from './buffer-pool'; -import enums from '../enums'; +import * as enums from '../enums'; let _attr2bufviewType = {}; _attr2bufviewType[gfx.ATTR_TYPE_INT8] = enums.BUFFER_VIEW_INT8; diff --git a/cocos/renderer/core/view.js b/cocos/renderer/core/view.js index c4e0c707ad..a9bc6af502 100644 --- a/cocos/renderer/core/view.js +++ b/cocos/renderer/core/view.js @@ -1,7 +1,7 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { vec3, color4, mat4 } from '../../core/vmath'; -import enums from '../enums'; +import * as enums from '../enums'; import { frustum } from '../../3d/geom-utils'; let _m4_tmp = mat4.create(); diff --git a/cocos/renderer/enums.js b/cocos/renderer/enums.js index 4dd45af301..80737d1aa9 100644 --- a/cocos/renderer/enums.js +++ b/cocos/renderer/enums.js @@ -1,49 +1,47 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -export default { - // projection - PROJ_PERSPECTIVE: 0, - PROJ_ORTHO: 1, +// projection +export const PROJ_PERSPECTIVE = 0; +export const PROJ_ORTHO = 1; - // lights - LIGHT_DIRECTIONAL: 0, - LIGHT_POINT: 1, - LIGHT_SPOT: 2, +// lights +export const LIGHT_DIRECTIONAL = 0; +export const LIGHT_POINT = 1; +export const LIGHT_SPOT = 2; - // shadows - SHADOW_NONE: 0, - SHADOW_HARD: 1, - SHADOW_SOFT: 2, +// shadows +export const SHADOW_NONE = 0; +export const SHADOW_HARD = 1; +export const SHADOW_SOFT = 2; - // parameter type - PARAM_INT: 0, - PARAM_INT2: 1, - PARAM_INT3: 2, - PARAM_INT4: 3, - PARAM_FLOAT: 4, - PARAM_FLOAT2: 5, - PARAM_FLOAT3: 6, - PARAM_FLOAT4: 7, - PARAM_COLOR3: 8, - PARAM_COLOR4: 9, - PARAM_MAT2: 10, - PARAM_MAT3: 11, - PARAM_MAT4: 12, - PARAM_TEXTURE_2D: 13, - PARAM_TEXTURE_CUBE: 14, +// parameter type +export const PARAM_INT = 0; +export const PARAM_INT2 = 1; +export const PARAM_INT3 = 2; +export const PARAM_INT4 = 3; +export const PARAM_FLOAT = 4; +export const PARAM_FLOAT2 = 5; +export const PARAM_FLOAT3 = 6; +export const PARAM_FLOAT4 = 7; +export const PARAM_COLOR3 = 8; +export const PARAM_COLOR4 = 9; +export const PARAM_MAT2 = 10; +export const PARAM_MAT3 = 11; +export const PARAM_MAT4 = 12; +export const PARAM_TEXTURE_2D = 13; +export const PARAM_TEXTURE_CUBE = 14; - // clear flags - CLEAR_COLOR: 1, - CLEAR_DEPTH: 2, - CLEAR_STENCIL: 4, - CLEAR_SKYBOX: 8, +// clear flags +export const CLEAR_COLOR = 1; +export const CLEAR_DEPTH = 2; +export const CLEAR_STENCIL = 4; +export const CLEAR_SKYBOX = 8; - // - BUFFER_VIEW_INT8: 0, - BUFFER_VIEW_UINT8: 1, - BUFFER_VIEW_INT16: 2, - BUFFER_VIEW_UINT16: 3, - BUFFER_VIEW_INT32: 4, - BUFFER_VIEW_UINT32: 5, - BUFFER_VIEW_FLOAT32: 6, -}; +// +export const BUFFER_VIEW_INT8 = 0; +export const BUFFER_VIEW_UINT8 = 1; +export const BUFFER_VIEW_INT16 = 2; +export const BUFFER_VIEW_UINT16 = 3; +export const BUFFER_VIEW_INT32 = 4; +export const BUFFER_VIEW_UINT32 = 5; +export const BUFFER_VIEW_FLOAT32 = 6; diff --git a/cocos/renderer/index.js b/cocos/renderer/index.js index e48d87e0b2..ab3d39982a 100644 --- a/cocos/renderer/index.js +++ b/cocos/renderer/index.js @@ -1,56 +1,25 @@ -import enums from './enums'; -import { createIA } from './utils'; +export * from './enums'; + +export { createIA } from './utils'; import config from './config'; -import { RenderQueue, PassStage } from './core/constants'; -import { Pass } from './core/pass'; -import { Effect } from './core/effect'; -import InputAssembler from './core/input-assembler'; -import View from './core/view'; +const addStage = config.addStage; +export { addStage }; -import { Light } from './scene/light'; -import { Camera } from './scene/camera'; -import { Model } from './scene/model'; -import Scene from './scene/scene'; +export { RenderQueue, PassStage } from './core/constants'; +export { Pass } from './core/pass'; +export { Effect } from './core/effect'; +export { default as InputAssembler } from './core/input-assembler'; +export { default as View } from './core/view'; -import LineBatchModel from './models/line-batch-model'; -import SpriteBatchModel from './models/sprite-batch-model'; -import ParticleBatchModel from './models/particle-batch-model'; -import SkinningModel from './models/skinning-model'; +export { Light } from './scene/light'; +export { Camera } from './scene/camera'; +export { Model } from './scene/model'; +export { default as Scene } from './scene/scene'; -import ForwardRenderer from './renderers/forward-renderer'; +export { default as LineBatchModel } from './models/line-batch-model'; +export { default as SpriteBatchModel } from './models/sprite-batch-model'; +export { default as ParticleBatchModel } from './models/particle-batch-model'; +export { default as SkinningModel } from './models/skinning-model'; -let renderer = { - // config - addStage: config.addStage, - - // utils - createIA, - - // core - RenderQueue, - PassStage, - Pass, - Effect, - InputAssembler, - View, - - // scene - Light, - Camera, - Model, - Scene, - - // models - LineBatchModel, - SpriteBatchModel, - ParticleBatchModel, - SkinningModel, - - // renderers - ForwardRenderer, -}; -Object.assign(renderer, enums); - -export { renderer }; -cc.renderer = renderer; +export { default as ForwardRenderer } from './renderers/forward-renderer'; diff --git a/cocos/renderer/renderers/forward-renderer.js b/cocos/renderer/renderers/forward-renderer.js index d27f320fc4..6d5cbb2924 100644 --- a/cocos/renderer/renderers/forward-renderer.js +++ b/cocos/renderer/renderers/forward-renderer.js @@ -5,7 +5,7 @@ import { vec3, mat4 } from '../../core/vmath'; import BaseRenderer from '../core/base-renderer'; import DynamicIAPool from '../core/dynamic-ia-pool'; -import enums from '../enums'; +import * as enums from '../enums'; import { PassStage } from '../core/constants'; // import GaussianBlur from './gaussian-blur'; diff --git a/cocos/renderer/scene/light.js b/cocos/renderer/scene/light.js index 1236a98104..fb79803202 100644 --- a/cocos/renderer/scene/light.js +++ b/cocos/renderer/scene/light.js @@ -3,7 +3,7 @@ import { color3, color4, mat4, mat3, vec3, toRadian } from '../../core/vmath'; import gfx from '../gfx'; -import enums from '../enums'; +import * as enums from '../enums'; const _forward = vec3.create(0, 0, -1); diff --git a/index.js b/index.js index bb1f4cb2c0..31c44b1770 100644 --- a/index.js +++ b/index.js @@ -31,7 +31,9 @@ import cc from './predefine'; // LOAD ENGINE CORE export * from './cocos/core'; export * from './cocos/scene-graph'; -export * from './cocos/renderer'; +import * as renderer from './cocos/renderer'; +export { renderer }; +cc.renderer = renderer; export * from './cocos/assets'; export * from './cocos/load-pipeline'; From 36f1d38e9d1d0b145e8c2b17f299b59dfec274b8 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 14 Jan 2019 15:51:12 +0800 Subject: [PATCH 114/267] add pass.update() to render pipeline --- cocos/gfx/webgl/webgl-buffer.ts | 4 +- cocos/gfx/webgl/webgl-command-buffer.ts | 108 ++++++++++++++---------- cocos/gfx/webgl/webgl-device.ts | 96 +++++++++++++++------ cocos/gfx/webgl/webgl-gpu-objects.ts | 19 ++++- cocos/pipeline/forward/forward-stage.ts | 2 - cocos/pipeline/render-pipeline.ts | 2 +- cocos/pipeline/render-queue.ts | 4 + cocos/renderer/scene/model.ts | 55 ++++++------ 8 files changed, 186 insertions(+), 104 deletions(-) diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 04fe330f9a..b23c3a6663 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,5 +1,5 @@ -import { GFXBuffer, IGFXBufferInfo, GFXBufferSource } from '../buffer'; -import { GFXMemoryUsageBit, GFXStatus, GFXBufferUsageBit } from '../define'; +import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer'; +import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 74486d1f12..1f64f68349 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,7 +1,7 @@ import { GFXBindingLayout } from '../binding-layout'; import { GFXBuffer, GFXBufferSource } from '../buffer'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; -import { GFXBufferTextureCopy, GFXStatus, GFXTextureLayout, IGFXColor, IGFXRect, GFXBufferUsageBit } from '../define'; +import { GFXBufferTextureCopy, GFXBufferUsageBit, GFXStatus, GFXTextureLayout, IGFXColor, IGFXRect, GFXCommandBufferType } from '../define'; import { GFXDevice } from '../device'; import { GFXFramebuffer } from '../framebuffer'; import { GFXInputAssembler } from '../input-assembler'; @@ -29,6 +29,7 @@ import { WebGLGFXTexture } from './webgl-texture'; export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); + private _isInRenderPass: boolean = false; private _curGPUPipelineState: WebGLGPUPipelineState | null = null; private _curGPUBindingLayout: WebGLGPUBindingLayout | null = null; private _curGPUInputAssembler: WebGLGPUInputAssembler | null = null; @@ -68,6 +69,8 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { if (this._isStateInvalied) { this.bindStates(); } + + this._isInRenderPass = false; } public beginRenderPass ( @@ -88,9 +91,12 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS); } + + this._isInRenderPass = true; } public endRenderPass () { + this._isInRenderPass = false; } public bindPipelineState (pipelineState: GFXPipelineState) { @@ -119,46 +125,55 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public draw (inputAssembler: GFXInputAssembler) { - if (this._isStateInvalied) { - this.bindStates(); - } + if (this._type === GFXCommandBufferType.PRIMARY && this._isInRenderPass || + this._type === GFXCommandBufferType.SECONDARY) { + if (this._isStateInvalied) { + this.bindStates(); + } - const cmd = ( this._allocator as WebGLGFXCommandAllocator). - drawCmdPool.alloc(WebGLCmdDraw); - if (cmd) { - (inputAssembler as WebGLGFXInputAssembler).extractCmdDraw(cmd); - this.cmdPackage.drawCmds.push(cmd); + const cmd = ( this._allocator as WebGLGFXCommandAllocator). + drawCmdPool.alloc(WebGLCmdDraw); + if (cmd) { + (inputAssembler as WebGLGFXInputAssembler).extractCmdDraw(cmd); + this.cmdPackage.drawCmds.push(cmd); - this.cmdPackage.cmds.push(WebGLCmd.DRAW); + this.cmdPackage.cmds.push(WebGLCmd.DRAW); + } + } else { + console.error('Command \'draw\' must be recorded inside a render pass.'); } } public updateBuffer (buffer: GFXBuffer, data: GFXBufferSource, offset?: number, size?: number) { - const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; - if (gpuBuffer) { - const cmd = (this._allocator as WebGLGFXCommandAllocator). - updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); - if (cmd) { + if (!this._isInRenderPass) { + const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; + if (gpuBuffer) { + const cmd = (this._allocator as WebGLGFXCommandAllocator). + updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); + if (cmd) { - let buffSize; - if (size !== undefined ) { - buffSize = size; - } else if (buffer.usage & GFXBufferUsageBit.INDIRECT) { - buffSize = 0; - } else { - buffSize = (data as ArrayBuffer).byteLength; + let buffSize; + if (size !== undefined ) { + buffSize = size; + } else if (buffer.usage & GFXBufferUsageBit.INDIRECT) { + buffSize = 0; + } else { + buffSize = (data as ArrayBuffer).byteLength; + } + + const buff = data as ArrayBuffer; + + cmd.gpuBuffer = gpuBuffer; + cmd.buffer = buff.slice(0); + cmd.offset = (offset !== undefined ? offset : 0); + cmd.size = buffSize; + this.cmdPackage.updateBufferCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); } - - const buff = data as ArrayBuffer; - - cmd.gpuBuffer = gpuBuffer; - cmd.buffer = buff.slice(0); - cmd.offset = (offset !== undefined ? offset : 0); - cmd.size = buffSize; - this.cmdPackage.updateBufferCmds.push(cmd); - - this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER); } + } else { + console.error('Command \'updateBuffer\' must be recorded outside a render pass.'); } } @@ -167,20 +182,25 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { dstTex: GFXTexture, dstLayout: GFXTextureLayout, regions: GFXBufferTextureCopy[]) { - const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; - const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; - if (gpuBuffer && gpuTexture) { - const cmd = (this._allocator as WebGLGFXCommandAllocator). - copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); - if (cmd) { - cmd.gpuBuffer = gpuBuffer; - cmd.gpuTexture = gpuTexture; - cmd.dstLayout = dstLayout; - cmd.regions = regions; - this.cmdPackage.copyBufferToTextureCmds.push(cmd); - this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE); + if (!this._isInRenderPass) { + const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; + const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; + if (gpuBuffer && gpuTexture) { + const cmd = (this._allocator as WebGLGFXCommandAllocator). + copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); + if (cmd) { + cmd.gpuBuffer = gpuBuffer; + cmd.gpuTexture = gpuTexture; + cmd.dstLayout = dstLayout; + cmd.regions = regions; + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + + this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE); + } } + } else { + console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.'); } } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 1fb69c7897..152f8c3bde 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,8 +1,20 @@ import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; -import { GFXBuffer, IGFXBufferInfo, GFXBufferSource } from '../buffer'; +import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; -import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXFilter, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXQueueType, GFXTextureFlagBit, GFXTextureType, GFXTextureViewType } from '../define'; +import { + GFXBindingType, + GFXBufferTextureCopy, + GFXBufferUsageBit, + GFXFilter, + GFXFormat, + GFXFormatInfos, + GFXFormatSize, + GFXQueueType, + GFXTextureFlagBit, + GFXTextureType, + GFXTextureViewType, +} from '../define'; import { GFXDevice, IGFXDeviceInfo } from '../device'; import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; @@ -19,9 +31,36 @@ import { WebGLGFXBindingLayout } from './webgl-binding-layout'; import { WebGLGFXBuffer } from './webgl-buffer'; import { WebGLGFXCommandAllocator } from './webgl-command-allocator'; import { WebGLGFXCommandBuffer } from './webgl-command-buffer'; -import { WebGLCmdFuncCopyBufferToTexture, WebGLCmdFuncCreateBuffer, WebGLCmdFuncCreateFramebuffer, WebGLCmdFuncCreateInputAssember, WebGLCmdFuncCreateShader, WebGLCmdFuncCreateTexture, WebGLCmdFuncDestroyBuffer, WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncDestroyShader, WebGLCmdFuncDestroyTexture, WebGLCmdFuncUpdateBuffer } from './webgl-commands'; +import { + WebGLCmdFuncCopyBufferToTexture, + WebGLCmdFuncCreateBuffer, + WebGLCmdFuncCreateFramebuffer, + WebGLCmdFuncCreateInputAssember, + WebGLCmdFuncCreateShader, + WebGLCmdFuncCreateTexture, + WebGLCmdFuncDestroyBuffer, + WebGLCmdFuncDestroyFramebuffer, + WebGLCmdFuncDestroyShader, + WebGLCmdFuncDestroyTexture, + WebGLCmdFuncUpdateBuffer, +} from './webgl-commands'; import { WebGLGFXFramebuffer } from './webgl-framebuffer'; -import { WebGLGPUBinding, WebGLGPUBindingLayout as WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer, WebGLGPUInputAssembler, WebGLGPUObjectType, WebGLGPUPipelineLayout, WebGLGPUPipelineState, WebGLGPURenderPass, WebGLGPUSampler, WebGLGPUShader, WebGLGPUShaderStage, WebGLGPUTexture, WebGLGPUTextureView } from './webgl-gpu-objects'; +import { + WebGLGPUBinding, + WebGLGPUBindingLayout, + WebGLGPUBuffer, + WebGLGPUFramebuffer, + WebGLGPUInputAssembler, + WebGLGPUObjectType, + WebGLGPUPipelineLayout, + WebGLGPUPipelineState, + WebGLGPURenderPass, + WebGLGPUSampler, + WebGLGPUShader, + WebGLGPUShaderStage, + WebGLGPUTexture, + WebGLGPUTextureView, +} from './webgl-gpu-objects'; import { WebGLGFXInputAssembler } from './webgl-input-assembler'; import { WebGLGFXPipelineLayout } from './webgl-pipeline-layout'; import { WebGLGFXPipelineState } from './webgl-pipeline-state'; @@ -475,7 +514,11 @@ export class WebGLGFXDevice extends GFXDevice { } } - public copyFramebufferToBuffer (srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]) { + public copyFramebufferToBuffer ( + srcFramebuffer: GFXFramebuffer, + dstBuffer: ArrayBuffer, + regions: GFXBufferTextureCopy[]) { + const gl = this._webGLRC as WebGLRenderingContext; const gpuFramebuffer = (srcFramebuffer as WebGLGFXFramebuffer).gpuFramebuffer; @@ -497,7 +540,8 @@ export class WebGLGFXDevice extends GFXDevice { const memSize = GFXFormatSize(GFXFormat.RGBA8, w, h, 1); const data = view.subarray(buffOffset, buffOffset + memSize); - gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, data); + gl.readPixels(region.texOffset.x, region.texOffset.y, w, h, + WebGLRenderingContext.RGBA, WebGLRenderingContext.UNSIGNED_BYTE, data); } if (this.stateCache.glFramebuffer !== curFBO) { @@ -955,37 +999,37 @@ export class WebGLGFXDevice extends GFXDevice { private initStates (gl: WebGLRenderingContext) { - gl.activeTexture(WebGLRenderingContext.TEXTURE0); - gl.pixelStorei(WebGLRenderingContext.PACK_ALIGNMENT, 1); - gl.pixelStorei(WebGLRenderingContext.UNPACK_ALIGNMENT, 1); + gl.activeTexture(gl.TEXTURE0); + gl.pixelStorei(gl.PACK_ALIGNMENT, 1); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); - gl.bindFramebuffer(WebGLRenderingContext.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); // rasteriazer state - gl.enable(WebGLRenderingContext.CULL_FACE); - gl.cullFace(WebGLRenderingContext.BACK); - gl.frontFace(WebGLRenderingContext.CCW); + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); gl.polygonOffset(0.0, 0.0); // depth stencil state - gl.enable(WebGLRenderingContext.DEPTH_TEST); + gl.enable(gl.DEPTH_TEST); gl.depthMask(true); - gl.depthFunc(WebGLRenderingContext.LESS); + gl.depthFunc(gl.LESS); - gl.stencilFuncSeparate(WebGLRenderingContext.FRONT, WebGLRenderingContext.ALWAYS, 1, 0xffffffff); - gl.stencilOpSeparate(WebGLRenderingContext.FRONT, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP); - gl.stencilMaskSeparate(WebGLRenderingContext.FRONT, 0xffffffff); - gl.stencilFuncSeparate(WebGLRenderingContext.BACK, WebGLRenderingContext.ALWAYS, 1, 0xffffffff); - gl.stencilOpSeparate(WebGLRenderingContext.BACK, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP, WebGLRenderingContext.KEEP); - gl.stencilMaskSeparate(WebGLRenderingContext.BACK, 0xffffffff); + gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffffffff); + gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP); + gl.stencilMaskSeparate(gl.FRONT, 0xffffffff); + gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffffffff); + gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP); + gl.stencilMaskSeparate(gl.BACK, 0xffffffff); - gl.disable(WebGLRenderingContext.STENCIL_TEST); + gl.disable(gl.STENCIL_TEST); // blend state - gl.disable(WebGLRenderingContext.SAMPLE_ALPHA_TO_COVERAGE); - gl.disable(WebGLRenderingContext.BLEND); - gl.blendEquationSeparate(WebGLRenderingContext.FUNC_ADD, WebGLRenderingContext.FUNC_ADD); - gl.blendFuncSeparate(WebGLRenderingContext.ONE, WebGLRenderingContext.ZERO, WebGLRenderingContext.ONE, WebGLRenderingContext.ZERO); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.disable(gl.BLEND); + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); gl.colorMask(true, true, true, true); gl.blendColor(0.0, 0.0, 0.0, 0.0); } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index 0f4956c057..71dcabef9e 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,9 +1,24 @@ -import { GFXBindingType, GFXBufferUsage, GFXBufferUsageBit, GFXFormat, GFXMemoryUsage, GFXMemoryUsageBit, GFXShaderType, GFXTextureFlagBit, GFXTextureFlags, GFXTextureType, GFXTextureUsage, GFXTextureUsageBit, GFXTextureViewType, GFXType } from '../define'; +import { GFXBufferSource } from '../buffer'; +import { + GFXBindingType, + GFXBufferUsage, + GFXBufferUsageBit, + GFXFormat, + GFXMemoryUsage, + GFXMemoryUsageBit, + GFXShaderType, + GFXTextureFlagBit, + GFXTextureFlags, + GFXTextureType, + GFXTextureUsage, + GFXTextureUsageBit, + GFXTextureViewType, + GFXType, +} from '../define'; import { IGFXInputAttribute } from '../input-assembler'; import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../pipeline-state'; import { GFXColorAttachment, GFXDepthStencilAttachment } from '../render-pass'; import { GFXUniformBlock, GFXUniformSampler, IGFXShaderMacro } from '../shader'; -import { GFXBufferSource } from '../buffer'; export enum WebGLGPUObjectType { UNKNOWN, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 65e427c81d..c0589212cd 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -52,12 +52,10 @@ export class ForwardStage extends RenderStage { [camera.clearColor], camera.clearDepth, camera.clearStencil); for (const item of queue.opaques) { - cmdBuff.updateBuffer(item.model.localUBO, item.model.localUniforms.view); cmdBuff.execute([item.cmdBuff]); } for (const item of queue.transparents) { - cmdBuff.updateBuffer(item.model.localUBO, item.model.localUniforms.view); cmdBuff.execute([item.cmdBuff]); } diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index e4efecb8db..94712630ce 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -363,7 +363,7 @@ export abstract class RenderPipeline { continue; } - model.updateRenderData(); + model.updateUBOs(); // add model pass to render queue this._queue.add(model, camera); diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index 8e75be0bb7..458f3b5ba8 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -54,6 +54,10 @@ export class RenderQueue { for (let i = 0; i < model.passes.length; ++i) { const pass = model.passes[i]; + + // update pass + pass.update(); + const cmdBuff = model.commandBuffers[i]; model.node.getWorldPosition(); diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 23bec24317..daf815ad94 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -39,7 +39,7 @@ export class Model { private _modelBounds: aabb; private _material: Material | null; private _cmdBuffers: GFXCommandBuffer[]; - private _localUniforms: UBOLocal | null; + private _uboLocal: UBOLocal; private _localUBO: GFXBuffer | null; /** * Setup a default empty model @@ -62,12 +62,11 @@ export class Model { this._castShadow = false; this._material = null; this._cmdBuffers = new Array(); - this._localUniforms = null; + this._uboLocal = new UBOLocal(); this._localUBO = null; } public initialize () { - this._localUniforms = new UBOLocal(); this._localUBO = cc.director.root.device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST, @@ -75,7 +74,7 @@ export class Model { stride: UBOLocal.SIZE, }); if (this._localUBO) { - this._localUBO.update(this._localUniforms.view); + this._localUBO.update(this._uboLocal.view); } } @@ -102,22 +101,20 @@ export class Model { this._node._rot, this._node._scale, this._worldBounds); } - public updateRenderData () { + public updateUBOs () { mat4.array(_temp_floatx16, this._node._mat); this._node._mat.invert(_temp_mat4); - if (this._localUniforms) { - this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); + if (this._uboLocal) { + this._uboLocal.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); } mat4.array(_temp_floatx16, _temp_mat4); - if (this._localUniforms) { - this._localUniforms.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); + if (this._uboLocal) { + this._uboLocal.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); } - /* if (this._localUBO) { - this._localUBO.update(this._localUniforms.view); + this._localUBO.update(this._uboLocal.view); } - */ } /** @@ -211,23 +208,27 @@ export class Model { public recordCommandBuffer (index: number) { const pass = (this._material as Material).passes[index]; - const cmdBufferInfo = { - allocator: cc.director.root.device.commandAllocator, - type: GFXCommandBufferType.SECONDARY, - }; if (this._cmdBuffers[index] == null) { + const cmdBufferInfo = { + allocator: cc.director.root.device.commandAllocator, + type: GFXCommandBufferType.SECONDARY, + }; this._cmdBuffers[index] = cc.director.root.device.createCommandBuffer(cmdBufferInfo); } - if (this._localUBO) { - pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO); - } + + const localUBO = this._localUBO as GFXBuffer; + const subMesh = this._subMeshObject as IRenderingSubmesh; + + pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, localUBO); pass.update(); - this._cmdBuffers[index].begin(); - this._cmdBuffers[index].bindPipelineState(pass.pipelineState); - this._cmdBuffers[index].bindBindingLayout(pass.bindingLayout); - this._cmdBuffers[index].bindInputAssembler((this._subMeshObject as IRenderingSubmesh).inputAssembler); - this._cmdBuffers[index].draw((this._subMeshObject as IRenderingSubmesh).inputAssembler); - this._cmdBuffers[index].end(); + + const cmdBuff = this._cmdBuffers[index]; + cmdBuff.begin(); + cmdBuff.bindPipelineState(pass.pipelineState); + cmdBuff.bindBindingLayout(pass.bindingLayout); + cmdBuff.bindInputAssembler(subMesh.inputAssembler); + cmdBuff.draw(subMesh.inputAssembler); + cmdBuff.end(); } /** @@ -246,8 +247,8 @@ export class Model { return this._cmdBuffers; } - get localUniforms (): UBOLocal { - return this._localUniforms as UBOLocal; + get uboLocal (): UBOLocal { + return this._uboLocal; } get localUBO (): GFXBuffer { From f274ff4cf9c2642e9d2a238dddc89a21f8be8624 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 16:29:42 +0800 Subject: [PATCH 115/267] createMesh now create serializable mesh asset --- cocos/3d/assets/mesh.ts | 154 +++++++++++++-------- cocos/3d/misc/utils.ts | 247 ++++++++++++++++++++++++++++++++-- cocos/3d/primitive/box.ts | 2 +- cocos/3d/primitive/defines.ts | 5 + playground/simple.html | 2 +- 5 files changed, 343 insertions(+), 67 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index d2fb82746b..983230fa12 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -32,7 +32,7 @@ import { Vec3 } from '../../core/value-types'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; -import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { GFXInputAssembler, IGFXInputAssemblerInfo, IGFXInputAttribute } from '../../gfx/input-assembler'; import { IBufferRange } from './utils/buffer-range'; export enum AttributeBaseType { @@ -247,15 +247,17 @@ export interface IPrimitive { */ vertexBundelIndices: number[]; - /** - * The indices data range of this primitive. - */ - indices: IBufferRange; + indices?: { + /** + * The indices data range of this primitive. + */ + range: IBufferRange; - /** - * The type of this primitive's indices. - */ - indexUnit: IndexUnit; + /** + * The type of this primitive's indices. + */ + indexUnit: IndexUnit; + }; /** * This primitive's topology. @@ -263,6 +265,31 @@ export interface IPrimitive { topology: Topology; } +/** + * Describes a mesh. + */ +export interface IMeshStruct { + /** + * The vertex bundles that this mesh owns. + */ + vertexBundles: IVertexBundle[]; + + /** + * The primitives that this mesh owns. + */ + primitives: IPrimitive[]; + + /** + * The min position of this mesh's vertices. + */ + minPosition: Vec3; + + /** + * The max position of this mesh's vertices. + */ + maxPosition: Vec3; +} + export interface IRenderingSubmesh { inputAssembler: GFXInputAssembler; primitiveMode: GFXPrimitiveMode; @@ -327,41 +354,29 @@ export class Mesh extends Asset { /** * Min position of this mesh. + * @deprecated Use this.struct.minPosition instead. */ get minPosition () { - return this._minPosition; + return this.struct.minPosition; } /** * Max position of this mesh. + * @deprecated Use this.struct.maxPosition instead. */ get maxPosition () { - return this._maxPosition; + return this.struct.maxPosition; } - /** - * The vertex bundles that this mesh owns. - */ - @property - public _vertexBundles: IVertexBundle[] = []; + get struct () { + return this._struct; + } - /** - * The primitives that this mesh owns. - */ - @property - public _primitives: IPrimitive[] = []; + get data () { + return this._data; + } - /** - * The min position of this mesh's vertices. - */ - @property(Vec3) - public _minPosition: Vec3 = new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - - /** - * The max position of this mesh's vertices. - */ - @property(Vec3) - public _maxPosition: Vec3 = new Vec3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + private _struct: IMeshStruct; private _data: Uint8Array | null = null; @@ -371,20 +386,34 @@ export class Mesh extends Asset { constructor () { super(); + + this._struct = { + vertexBundles: [], + primitives: [], + minPosition: new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), + maxPosition: new Vec3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE), + }; } /** - * Destory this mesh and immediately release its video memory. + * Destory this mesh and immediately release its GPU resources. */ public destroy () { - if (this._renderingMesh) { - this._renderingMesh.destroy(); - this._renderingMesh = null; - this._initialized = false; - } + this._tryDestroyRenderingMesh(); return super.destroy(); } + /** + * Assigns new mesh struct to this. + * @param struct The new mesh's struct. + * @param data The new mesh's data. + */ + public assign (struct: IMeshStruct, data: Uint8Array) { + this._struct = struct; + this._data = data; + this._tryDestroyRenderingMesh(); + } + /** * Gets the rendering mesh. */ @@ -423,24 +452,29 @@ export class Mesh extends Asset { const indexBuffers: GFXBuffer[] = []; - const renderingSubmeshes = this._primitives.map((primitive) => { + const renderingSubmeshes = this._struct.primitives.map((primitive) => { if (primitive.vertexBundelIndices.length === 0) { return null; } - const indexBuffer = gfxDevice.createBuffer({ - usage: GFXBufferUsageBit.INDEX, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: primitive.indices.length, - stride: getIndexUnitStride(primitive.indexUnit), - }); - indexBuffers.push(indexBuffer); + let indexBuffer: GFXBuffer | null = null; + if (primitive.indices) { + const indices = primitive.indices; - indexBuffer.update(buffer, primitive.indices.offset, primitive.indices.length); + indexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.INDEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: indices.range.length, + stride: getIndexUnitStride(indices.indexUnit), + }); + indexBuffers.push(indexBuffer); + + indexBuffer.update(new Uint8Array(buffer, indices.range.offset), 0, indices.range.length); + } const gfxAttributes: IGFXInputAttribute[] = []; primitive.vertexBundelIndices.forEach((iVertexBundle) => { - const vertexBundle = this._vertexBundles[iVertexBundle]; + const vertexBundle = this._struct.vertexBundles[iVertexBundle]; vertexBundle.attributes.forEach((attribute) => { const gfxAttribute: IGFXInputAttribute = { name: attribute.name, @@ -457,13 +491,17 @@ export class Mesh extends Asset { const referedVertexBuffers = primitive.vertexBundelIndices.map( (i) => vertexBuffers[i]); + const inputAssemblerInfo: IGFXInputAssemblerInfo = { + attributes: gfxAttributes, + vertexBuffers: referedVertexBuffers, + }; + if (indexBuffer) { + inputAssemblerInfo.indexBuffer = indexBuffer; + } + return { primitiveMode: toGFXTopology(primitive.topology), - inputAssembler: gfxDevice.createInputAssembler({ - attributes: gfxAttributes, - vertexBuffers: referedVertexBuffers, - indexBuffer, - }), + inputAssembler: gfxDevice.createInputAssembler(inputAssemblerInfo), } as IRenderingSubmesh ; }); @@ -471,7 +509,7 @@ export class Mesh extends Asset { } private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer): GFXBuffer[] { - return this._vertexBundles.map((vertexBundle) => { + return this._struct.vertexBundles.map((vertexBundle) => { const vertexBuffer = gfxDevice.createBuffer({ usage: GFXBufferUsageBit.VERTEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, @@ -482,5 +520,13 @@ export class Mesh extends Asset { return vertexBuffer; }); } + + private _tryDestroyRenderingMesh () { + if (this._renderingMesh) { + this._renderingMesh.destroy(); + this._renderingMesh = null; + this._initialized = false; + } + } } cc.Mesh = Mesh; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 46c82198a9..073dd1abe9 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -1,9 +1,11 @@ -import { GFXPrimitiveMode } from '../../gfx/define'; -import * as renderer from '../../renderer'; +import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define'; export { default as find } from '../../scene-graph/find'; import Texture2D from '../../assets/texture-2d'; import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; -import { Mesh, RenderingMesh } from '../assets/mesh'; +import { Vec3 } from '../../core/value-types'; +import { AttributeBaseType, AttributeType, + IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh, Topology } from '../assets/mesh'; +import { IGeometry } from '../primitive/defines'; /** * @@ -37,15 +39,95 @@ export function createJointsTexture (skinning: { joints: any[]; }) { return texture; } -export function createMesh (context, data) { - const ia = renderer.createIA(context, data); - const meshAsset = new Mesh(); - const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; - meshAsset._renderingMesh = new RenderingMesh([{ inputAssembler: ia, primitiveMode }], [], []); - meshAsset._minPosition = data.minPos; - meshAsset._maxPosition = data.maxPos; +export function createMesh (geometry: IGeometry) { + // Collect attributes and calculate length of result vertex buffer. + const attributes: IVertexAttribute[] = []; + let stride = 0; + const channels: Array<{ offset: number; data: number[]; attribute: IVertexAttribute; }> = []; + let verticesCount = 0; + const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); + const addAttribute = (attribute: IVertexAttribute, data: number[]) => { + const componentCount = _getComponentCount(attribute); + const componentBytesLength = _getComponentByteLength(attribute); + const bytesLength = componentBytesLength * componentCount; + attributes.push(attribute); + channels.push({ offset: stride, data, attribute }); + stride += bytesLength; + verticesCount = Math.max(verticesCount, Math.floor(data.length / componentCount)); + }; + addAttribute(copyAttribute(predefinedAttributes.positions), geometry.positions); + if (geometry.normals) { + addAttribute(copyAttribute(predefinedAttributes.normals), geometry.normals); + } + if (geometry.uvs) { + addAttribute(copyAttribute(predefinedAttributes.uvs), geometry.uvs); + } + if (geometry.colors) { + addAttribute(copyAttribute(predefinedAttributes.colors), geometry.colors); + } - return meshAsset; + // Use this to generate final merged buffer. + const bufferBlob = new BufferBlob(); + + // Fill vertex buffer. + const vertexBuffer = new ArrayBuffer(verticesCount * stride); + const vertexBufferView = new DataView(vertexBuffer); + for (const channel of channels) { + _writeVertices(vertexBufferView, channel.offset, stride, channel.attribute, channel.data); + } + const vertexBundle: IVertexBundle = { + verticesCount, + attributes, + data: { + offset: bufferBlob.getLength(), + length: vertexBuffer.byteLength, + }, + }; + bufferBlob.addBuffer(vertexBuffer); + + // Fill index buffer. + let indexBuffer: ArrayBuffer | null = null; + const targetIndexUnit = IndexUnit.UINT16; + if (geometry.indices) { + const { indices } = geometry; + const indexUnitBytesLength = 2; + indexBuffer = new ArrayBuffer(indexUnitBytesLength * indices.length); + const indexBufferView = new DataView(indexBuffer); + const writer = _getIndicesWriter(indexBufferView, targetIndexUnit); + for (let i = 0; i < indices.length; ++i) { + writer(indexUnitBytesLength * i, indices[i]); + } + } + + // Create primitive. + const primitive: IPrimitive = { + topology: _getTopology(geometry.primitiveMode), + vertexBundelIndices: [0], + }; + if (indexBuffer) { + primitive.indices = { + indexUnit: targetIndexUnit, + range: { + offset: bufferBlob.getLength(), + length: indexBuffer.byteLength, + }, + }; + bufferBlob.addBuffer(indexBuffer); + } + + // Create mesh struct. + const meshStruct: IMeshStruct = { + vertexBundles: [vertexBundle], + primitives: [primitive], + minPosition: new Vec3(geometry.minPos.x, geometry.minPos.y, geometry.minPos.z), + maxPosition: new Vec3(geometry.maxPos.x, geometry.maxPos.y, geometry.maxPos.z), + }; + + // Create mesh. + const mesh = new Mesh(); + mesh.assign(meshStruct, new Uint8Array(bufferBlob.getCombined())); + + return mesh; } /** @@ -54,3 +136,146 @@ export function createMesh (context, data) { export function toPPM (buffer: Uint8Array, w: number, h: number) { return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; } + +const predefinedAttributes = { + positions: { + name: GFXAttributeName.ATTR_POSITION, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC3, + normalize: false, + }, + normals: { + name: GFXAttributeName.ATTR_NORMAL, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC3, + normalize: false, + }, + uvs: { + name: GFXAttributeName.ATTR_TEX_COORD, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC2, + normalize: false, + }, + colors: { + name: GFXAttributeName.ATTR_COLOR, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC4, + normalize: false, + }, +}; + +class BufferBlob { + private _arrayBuffers: ArrayBuffer[] = []; + private _length = 0; + + public addBuffer (arrayBuffer: ArrayBuffer) { + const result = this._length; + this._arrayBuffers.push(arrayBuffer); + this._length += arrayBuffer.byteLength; + return result; + } + + public getLength () { + return this._length; + } + + public getCombined () { + let length = 0; + this._arrayBuffers.forEach((arrayBuffer) => length += arrayBuffer.byteLength); + const result = new Uint8Array(length); + let counter = 0; + this._arrayBuffers.forEach((arrayBuffer) => { + result.set(new Uint8Array(arrayBuffer), counter); + counter += arrayBuffer.byteLength; + }); + return result.buffer; + } +} + +function _getTopology (primitiveMode: GFXPrimitiveMode) { + switch (primitiveMode) { + case GFXPrimitiveMode.POINT_LIST: + return Topology.POINT_LIST; + case GFXPrimitiveMode.LINE_LIST: + return Topology.LINE_LIST; + case GFXPrimitiveMode.TRIANGLE_LIST: + return Topology.TRIANGLE_LIST; + } + return Topology.POINT_LIST; +} + +function _writeVertices ( + target: DataView, offset: number, stride: number, attribute: IVertexAttribute, data: number[]) { + const writer = _getVerticesWriter(target, attribute.baseType); + const componentCount = _getComponentCount(attribute); + const componentBytesLength = _getComponentByteLength(attribute); + const nVertices = Math.floor(data.length / componentCount); + + for (let iVertex = 0; iVertex < nVertices; ++iVertex) { + const x = offset + stride * iVertex; + for (let iComponent = 0; iComponent < componentCount; ++iComponent) { + const y = x + componentBytesLength * iComponent; + writer(y, data[componentCount * iVertex + iComponent]); + } + } +} + +function _getComponentByteLength (vertexAttribute: IVertexAttribute) { + switch (vertexAttribute.baseType) { + case AttributeBaseType.INT8: + case AttributeBaseType.UINT8: + return 1; + case AttributeBaseType.INT16: + case AttributeBaseType.UINT16: + return 2; + case AttributeBaseType.INT32: + case AttributeBaseType.UINT32: + case AttributeBaseType.FLOAT32: + return 4; + } + return 1; +} + +function _getComponentCount (vertexAttribute: IVertexAttribute) { + switch (vertexAttribute.type) { + case AttributeType.SCALAR: return 1; + case AttributeType.VEC2: return 2; + case AttributeType.VEC3: return 3; + case AttributeType.VEC4: return 4; + } + return 1; +} + +function _getVerticesWriter (dataView: DataView, baseType: AttributeBaseType) { + switch (baseType) { + case AttributeBaseType.INT8: + return (offset: number, value: number) => dataView.setInt8(offset, value); + case AttributeBaseType.UINT8: + return (offset: number, value: number) => dataView.setUint8(offset, value); + case AttributeBaseType.INT16: + return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); + case AttributeBaseType.UINT16: + return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case AttributeBaseType.INT32: + return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); + case AttributeBaseType.UINT32: + return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); + case AttributeBaseType.FLOAT32: + return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + } + return (offset: number, value: number) => dataView.setUint8(offset, value); +} + +function _getIndicesWriter (dataView: DataView, indexUnit: IndexUnit) { + switch (indexUnit) { + case IndexUnit.UINT8: + return (offset: number, value: number) => dataView.setUint8(offset, value); + case IndexUnit.UINT16: + return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case IndexUnit.UINT32: + return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); + } + return (offset: number, value: number) => dataView.setUint8(offset, value); +} + +const isLittleEndian = true; diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts index 19e604581f..574e2da293 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/3d/primitive/box.ts @@ -37,7 +37,7 @@ interface IBoxOptions extends IGeometryOptions { /** * This function generates a box with specified extents and centered at origin, - * but may emplaced through `center` option). + * but may be repositioned through `center` option). * @param options Options. */ export default function box (options?: IBoxOptions): IGeometry { diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts index d6b6f43e20..fbb6b0c2e0 100644 --- a/cocos/3d/primitive/defines.ts +++ b/cocos/3d/primitive/defines.ts @@ -55,4 +55,9 @@ export interface IGeometry { * Texture coordinates. */ uvs?: number[]; + + /** + * Vertex colors. + */ + colors?: number[]; } diff --git a/playground/simple.html b/playground/simple.html index b2e57b0d8f..62dd098689 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -63,7 +63,7 @@ modelNode.parent = scene; const modelCom = modelNode.addComponent('cc.ModelComponent'); modelCom.material = material; - modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + modelCom.mesh = cc.utils.createMesh(cc.primitives.box()); modelNode.setRotationFromEuler(45, 45, 45); cc.director.runSceneImmediate(scene); From 7b603046eb89171df3eeeb3f3677540988fc3f65 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 16:43:57 +0800 Subject: [PATCH 116/267] skeleton.js: rename autofmt --- cocos/3d/assets/{skeleton.js => skeleton.ts} | 73 ++++++++++---------- 1 file changed, 36 insertions(+), 37 deletions(-) rename cocos/3d/assets/{skeleton.js => skeleton.ts} (69%) diff --git a/cocos/3d/assets/skeleton.js b/cocos/3d/assets/skeleton.ts similarity index 69% rename from cocos/3d/assets/skeleton.js rename to cocos/3d/assets/skeleton.ts index a7679f2906..400b58a1d0 100644 --- a/cocos/3d/assets/skeleton.js +++ b/cocos/3d/assets/skeleton.ts @@ -23,11 +23,10 @@ THE SOFTWARE. ****************************************************************************/ -// @ts-check -import { _decorator } from "../../core/data"; +import { _decorator } from '../../core/data'; const { ccclass, property } = _decorator; -import { Asset } from "../../assets/asset"; -import { Mat4 } from "../../core/value-types"; +import { Asset } from '../../assets/asset'; +import { Mat4 } from '../../core/value-types'; /** * CLASS Skeleton @@ -40,42 +39,42 @@ import { Mat4 } from "../../core/value-types"; */ @ccclass('cc.Skeleton') export default class Skeleton extends Asset { - /** - * The path of joints. - * @type {string[]} - */ - @property([String]) - _joints = []; + /** + * The path of joints. + * @type {string[]} + */ + @property([String]) + public _joints = []; - /** - * The inverse bind matrices of joints. - * @type {Mat4[]} - */ - @property([Mat4]) - _inverseBindMatrices = []; + /** + * The inverse bind matrices of joints. + * @type {Mat4[]} + */ + @property([Mat4]) + public _inverseBindMatrices = []; - /** - * Gets the bind pose matrices of joints. - * @type {Mat4[]} - */ - get bindposes() { - return this._inverseBindMatrices; - } + /** + * Gets the bind pose matrices of joints. + * @type {Mat4[]} + */ + get bindposes () { + return this._inverseBindMatrices; + } - /** - * Sets the bind pose matrices of joints. - * @type {Mat4[]} - */ - set bindposes(value) { - this._inverseBindMatrices = value; - } + /** + * Sets the bind pose matrices of joints. + * @type {Mat4[]} + */ + set bindposes (value) { + this._inverseBindMatrices = value; + } - /** - * Gets the paths of joints. - * @type {string[]} - */ - get joints() { - return this._joints; - } + /** + * Gets the paths of joints. + * @type {string[]} + */ + get joints () { + return this._joints; + } } cc.Skeleton = Skeleton; From 2a8a98762475dfe8fa2228eaa2d2f228db8dbfeb Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 16:48:12 +0800 Subject: [PATCH 117/267] ts-ing skeleton --- cocos/3d/assets/skeleton.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/cocos/3d/assets/skeleton.ts b/cocos/3d/assets/skeleton.ts index 400b58a1d0..e3d9d5806d 100644 --- a/cocos/3d/assets/skeleton.ts +++ b/cocos/3d/assets/skeleton.ts @@ -41,21 +41,18 @@ import { Mat4 } from '../../core/value-types'; export default class Skeleton extends Asset { /** * The path of joints. - * @type {string[]} */ @property([String]) - public _joints = []; + private _joints: string[] = []; /** * The inverse bind matrices of joints. - * @type {Mat4[]} */ @property([Mat4]) - public _inverseBindMatrices = []; + private _inverseBindMatrices: Mat4[] = []; /** * Gets the bind pose matrices of joints. - * @type {Mat4[]} */ get bindposes () { return this._inverseBindMatrices; @@ -63,7 +60,6 @@ export default class Skeleton extends Asset { /** * Sets the bind pose matrices of joints. - * @type {Mat4[]} */ set bindposes (value) { this._inverseBindMatrices = value; @@ -71,10 +67,18 @@ export default class Skeleton extends Asset { /** * Gets the paths of joints. - * @type {string[]} */ get joints () { return this._joints; } + + /** + * Sets the paths of joints. + */ + set joints (value) { + this._joints = value; + } } -cc.Skeleton = Skeleton; + +// tslint:disable-next-line +cc['Skeleton'] = Skeleton; From 9553577a6dd73e3daf4c1fc8c41394e445ead5bb Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 17:01:32 +0800 Subject: [PATCH 118/267] optimize cc.Node api --- cocos/scene-graph/node.ts | 93 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 88 insertions(+), 5 deletions(-) diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index fd94bd538c..454cf8e880 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -275,6 +275,21 @@ class Node extends BaseNode { // transform // =============================== + /** + * Sets local position. + * @param position - The new local position. + */ + public setPosition (position: Vec3): void; + + /** + * Sets local position. + * @param x - The x component of the new local position. + * @param y - The y component of the new local position. + * @param z - The z component of the new local position. + * @param w - The w component of the new local position. + */ + public setPosition (x: number, y?: number, z?: number, w?: number): void; + /** * set local position * @param val - the new local position, or the x component of it @@ -307,12 +322,20 @@ class Node extends BaseNode { } /** - * set local rotation - * @param val - the new local rotation, or the x component of it - * @param y - the y component of the new local rotation - * @param z - the z component of the new local rotation - * @param w - the w component of the new local rotation + * Sets local rotation. + * @param rotation - The new local rotation. */ + public setRotation (rotation: Quat): void; + + /** + * Sets local rotation. + * @param x - The x component of the new local rotation. + * @param y - The y component of the new local rotation. + * @param z - The z component of the new local rotation. + * @param w - The w component of the new local rotation. + */ + public setRotation (x: number, y?: number, z?: number, w?: number): void; + public setRotation (val: Quat | number, y?: number, z?: number, w?: number) { if (y === undefined || z === undefined || w === undefined) { quat.copy(this._lrot, val); @@ -355,6 +378,21 @@ class Node extends BaseNode { } } + /** + * Sets local scale. + * @param scale - The new local scale. + */ + public setScale (scale: Vec3): void; + + /** + * Sets local scale. + * @param x - The x component of the new local scale. + * @param y - The y component of the new local scale. + * @param z - The z component of the new local scale. + * @param w - The w component of the new local scale. + */ + public setScale (x: number, y?: number, z?: number, w?: number): void; + /** * set local scale * @param val - the new local scale, or the x component of it @@ -386,6 +424,21 @@ class Node extends BaseNode { } } + /** + * Sets world position. + * @param position - The new world position. + */ + public setWorldPosition (position: Vec3): void; + + /** + * Sets world position. + * @param x - The x component of the new world position. + * @param y - The y component of the new world position. + * @param z - The z component of the new world position. + * @param w - The w component of the new world position. + */ + public setWorldPosition (x: number, y?: number, z?: number, w?: number): void; + /** * set world position * @param val - the new world position, or the x component of it @@ -427,6 +480,21 @@ class Node extends BaseNode { } } + /** + * Sets world rotation. + * @param rotation - The new world rotation. + */ + public setWorldRotation (rotation: Quat): void; + + /** + * Sets world rotation. + * @param x - The x component of the new world rotation. + * @param y - The y component of the new world rotation. + * @param z - The z component of the new world rotation. + * @param w - The w component of the new world rotation. + */ + public setWorldRotation (x: number, y?: number, z?: number, w?: number): void; + /** * set world rotation * @param val - the new world rotation, or the x component of it @@ -487,6 +555,21 @@ class Node extends BaseNode { } } + /** + * Sets world scale. + * @param scale - The new world scale. + */ + public setWorldScale (scale: Vec3): void; + + /** + * Sets world scale. + * @param x - The x component of the new world scale. + * @param y - The y component of the new world scale. + * @param z - The z component of the new world scale. + * @param w - The w component of the new world scale. + */ + public setWorldScale (x: number, y?: number, z?: number, w?: number): void; + /** * set world scale * @param val - the new world scale, or the x component of it From b6ecf7ee5dd7a511c022568d376fcf08a650cb1a Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 17:05:21 +0800 Subject: [PATCH 119/267] get endianness dynamically --- cocos/3d/misc/utils.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 073dd1abe9..09db9ade47 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -278,4 +278,9 @@ function _getIndicesWriter (dataView: DataView, indexUnit: IndexUnit) { return (offset: number, value: number) => dataView.setUint8(offset, value); } -const isLittleEndian = true; +const isLittleEndian = (() => { + const buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] === 256; +})(); From 08552687664c641351ce911c51d8e8ac5b7c33e0 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 14 Jan 2019 15:26:26 +0800 Subject: [PATCH 120/267] pass: rebuild with overrides --- cocos/3d/assets/material.ts | 16 ++++- cocos/3d/framework/model-component.js | 3 +- .../renderer/particle-system-renderer.js | 2 +- .../3d/framework/skinning-model-component.js | 2 +- cocos/3d/framework/skybox-component.js | 2 +- cocos/3d/misc/utils.js | 69 +++++++++++++++++++ cocos/gfx/webgl/webgl-device.ts | 2 +- cocos/pipeline/testcase/test-model-stage.ts | 2 +- cocos/renderer/core/effect.ts | 6 +- cocos/renderer/core/pass.ts | 27 ++++++-- cocos/renderer/scene/render-scene.ts | 2 +- cocos/renderer/utils.js | 6 +- playground/simple.html | 2 +- 13 files changed, 122 insertions(+), 19 deletions(-) create mode 100644 cocos/3d/misc/utils.js diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 578d4f8e46..cfc9f86801 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -26,8 +26,8 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { GFXBindingType } from '../../gfx/define'; import { Effect } from '../../renderer/core/effect'; -import { Pass } from '../../renderer/core/pass'; -import { EffectAsset } from './effect-asset'; +import { Pass, IPassOverrides } from '../../renderer/core/pass'; +import { EffectAsset, IPassInfo, ITechniqueInfo } from './effect-asset'; @ccclass('cc.Material') export class Material extends Asset { @@ -133,6 +133,18 @@ export class Material extends Asset { this.update(); } + public rebuildWithOverrides (overrides: IPassOverrides, idx?: number) { + 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); + } + } + public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) { // get effect asset if (typeof asset === 'string') { diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 7735de0780..66dc454c29 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -116,6 +116,7 @@ export default class ModelComponent extends RenderableComponent { set mesh(val) { this._mesh = val; + this._updateModels(); } /** @@ -184,7 +185,7 @@ export default class ModelComponent extends RenderableComponent { } _updateModels() { - if (!this.enabled) return; + if (!this.node._scene) return; let meshCount = this._mesh ? this._mesh.subMeshCount : 0; for (let i = 0; i < meshCount; ++i) { diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-renderer.js index 64d3415226..1a15a0a7e6 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.js +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.js @@ -89,7 +89,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { this.frameTile = cc.v2(1, 1); this.attrs = new Array(5); - this.device = cc.game._renderContext; + this.device = cc.game._gfxDevice; } onInit() { diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js index 46aaf107f3..07295e2d30 100644 --- a/cocos/3d/framework/skinning-model-component.js +++ b/cocos/3d/framework/skinning-model-component.js @@ -187,7 +187,7 @@ export default class SkinningModelComponent extends ModelComponent { return; } - if (cc.game._renderContext.allowFloatTexture()) { + if (cc.game._gfxDevice.allowFloatTexture()) { this._jointsTexture = utils.createJointsTexture(this._skeleton); this._jointMatricesData = new Float32Array(this._jointsTexture._width * this._jointsTexture._height * 4); } else { diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js index a913871413..13cf122025 100644 --- a/cocos/3d/framework/skybox-component.js +++ b/cocos/3d/framework/skybox-component.js @@ -82,7 +82,7 @@ export default class SkyboxComponent extends Component { onLoad() { this._model.setNode(this.node); - let ia = renderer.createIA(cc.game._renderContext, box(2, 2, 2)); + let ia = renderer.createIA(cc.game._gfxDevice, box(2, 2, 2)); this._model.setInputAssembler(ia); if (!this._material) { diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js new file mode 100644 index 0000000000..a6256437a4 --- /dev/null +++ b/cocos/3d/misc/utils.js @@ -0,0 +1,69 @@ +import { renderer } from '../../renderer'; +import find from '../../scene-graph/find'; +import { Mesh, RenderingMesh } from '../assets/mesh'; +import gfx from '../../renderer/gfx/index'; +import { GFXPrimitiveMode } from '../../gfx/define'; + +/** + * + * @param {import("../assets/skeleton").default} skinning + */ +function createJointsTexture(skinning) { + const jointCount = skinning.joints.length; + + // Set jointsTexture. + // A squared texture with side length N(N > 1) multiples of 2 can store + // 2 ^ (2 * N - 2) matrices. + // We support most 1024 joints. + let size; + if (jointCount > 1024) { + throw "To many joints(more than 1024)."; + } else if (jointCount > 256) { + size = 64; + } else if (jointCount > 64) { + size = 32; + } else if (jointCount > 16) { + size = 16; + } else if (jointCount > 4) { + size = 8; + } else { + size = 4; + } + + return new gfx.Texture2D(cc.game._gfxDevice, { + width: size, + height: size, + format: gfx.TEXTURE_FMT_RGBA32F, + minFilter: gfx.FILTER_NEAREST, + magFilter: gfx.FILTER_NEAREST, + wrapS: gfx.WRAP_CLAMP, + wrapT: gfx.WRAP_CLAMP, + mipmap: false + }); +} + +function createMesh(context, data) { + let ia = renderer.createIA(context, data); + let meshAsset = new Mesh(); + const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; + meshAsset._renderingMesh = new RenderingMesh([{inputAssembler: ia, primitiveMode}], [], []); + meshAsset._minPosition = data.minPos; + meshAsset._maxPosition = data.maxPos; + + return meshAsset; +} + +/** + * @param {Uint8Array} buffer + */ +function toPPM(buffer, w, h) { + return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; +} + +export default { + createJointsTexture, + createMesh, + + find, + toPPM +}; diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 152f8c3bde..d27b91aabf 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -199,7 +199,7 @@ export class WebGLGFXDevice extends GFXDevice { private _webGLRC: WebGLRenderingContext | null = null; private _isAntialias: boolean = true; - private _isPremultipliedAlpha: boolean = false; + private _isPremultipliedAlpha: boolean = true; private _extensions: string[] | null = null; private _EXT_texture_filter_anisotropic: EXT_texture_filter_anisotropic | null = null; diff --git a/cocos/pipeline/testcase/test-model-stage.ts b/cocos/pipeline/testcase/test-model-stage.ts index 1da32b2d3a..742bdb6fab 100644 --- a/cocos/pipeline/testcase/test-model-stage.ts +++ b/cocos/pipeline/testcase/test-model-stage.ts @@ -85,7 +85,7 @@ export class TestModelStage extends RenderStage { this._scene._scene = this._scene; const modelCom = this._scene.addComponent('cc.ModelComponent'); modelCom.material = this._material; - modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box({length: 1, width: 1, height: 1})); + 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; diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 7169ad0e89..00e88c5f9c 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -64,9 +64,13 @@ const getDefines = (name: string, prog: IShaderInfo) => { }; export class Effect { + public static getPassInfos (effect: EffectAsset, techIdx: number) { + return effect.techniques[techIdx].passes; + } + public static parseEffect (effect: EffectAsset, info?: IEffectInfo) { // techniques - const { techIdx, defines } = info || {} as IEffectInfo; + const { techIdx, defines } = info || {} as IEffectInfo; const tech = effect.techniques[techIdx || 0]; const passNum = tech.passes.length; const passes: Pass[] = new Array(passNum); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 23ce092133..c89a96c36e 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 } from '../../gfx/pipeline-state'; + GFXInputState, GFXPipelineState, GFXRasterizerState, IGFXPipelineStateInfo } from '../../gfx/pipeline-state'; import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; @@ -24,6 +24,13 @@ export interface IPassInfoFull extends IPassInfo { globals: GFXBuffer; } +export interface IPassOverrides { + bs: GFXBlendState; + dss: GFXDepthStencilState; + rs: GFXRasterizerState; + primitive: GFXPrimitiveMode; +} + const _type2fn = { [GFXType.INT]: (a: Float32Array, v: any) => a[0] = v, [GFXType.INT2]: (a: Float32Array, v: any) => vec2.array(a, v), @@ -114,7 +121,7 @@ export class Pass { if (!this._pipelineLayout) { console.error('create pipeline layout failed'); return; } this._shader = info.shader; this._renderPass = info.renderPass; - this.createPipelineState(info); + this._createPipelineState(info); for (const u of info.blocks) { if (builtinRE.test(u.name)) { @@ -199,9 +206,18 @@ export class Pass { (this._bindingLayout as GFXBindingLayout).bindSampler(binding, value); } - public setStates (info: IPassInfo) { + public rebuildWithOverrides (info: Partial, overrides: IPassOverrides) { if (this._pipelineState) { this._pipelineState.destroy(); } - this.createPipelineState(info); + const ors = Object.assign({}, overrides); + this._createPipelineState(info, (states) => { + Object.assign(states.rs, ors.rs); + Object.assign(states.dss, ors.dss); + 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 () { @@ -224,7 +240,7 @@ export class Pass { (this._bindingLayout as GFXBindingLayout).update(); } - protected createPipelineState (info: IPassInfo) { + protected _createPipelineState (info: Partial, override?: (states: IGFXPipelineStateInfo) => any) { if (info.primitive) { this._primitive = info.primitive; } if (info.stage) { this._stage = info.stage; } @@ -252,6 +268,7 @@ export class Pass { rs: Object.assign(new GFXRasterizerState(), info.rasterizerState), shader: this._shader, }; + if (override) { override(stateInfo); } if (this._pipelineState) { this._pipelineState.initialize(stateInfo); } else { diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index ab3f5aa439..3138f8323a 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -2,11 +2,11 @@ import { intersect, ray, triangle } from '../../3d/geom-utils'; import { RecyclePool } from '../../3d/memop'; import { _createSceneFun, Root } from '../../core/root'; import { mat4, vec3 } from '../../core/vmath'; +import { GFXPrimitiveMode } from '../../gfx/define'; import { Layers } from '../../scene-graph/layers'; import { Camera, ICameraInfo } from './camera'; import { Light } from './light'; import { Model } from './model'; -import { GFXPrimitiveMode } from '../../gfx/define'; export interface IRenderSceneInfo { name: string; diff --git a/cocos/renderer/utils.js b/cocos/renderer/utils.js index e437a9c6d4..dc5bc986bc 100644 --- a/cocos/renderer/utils.js +++ b/cocos/renderer/utils.js @@ -37,7 +37,7 @@ export function createIA(device, data) { vfmt.push({ name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGB32F }); } - let vb = cc.director.root.device.createBuffer({ + let vb = device.createBuffer({ usage: GFXBufferUsageBit.VERTEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: verts.length * 4, @@ -46,7 +46,7 @@ export function createIA(device, data) { vb.update(new Float32Array(verts)); - let ib = cc.director.root.device.createBuffer({ + let ib = device.createBuffer({ usage: GFXBufferUsageBit.INDEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, size: data.indices.length * 2, @@ -55,7 +55,7 @@ export function createIA(device, data) { ib.update(new Uint16Array(data.indices)); - return cc.director.root.device.createInputAssembler({ + return device.createInputAssembler({ attributes: vfmt, vertexBuffers: [vb], indexBuffer: ib, diff --git a/playground/simple.html b/playground/simple.html index b2e57b0d8f..a59f36f59d 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -63,7 +63,7 @@ modelNode.parent = scene; const modelCom = modelNode.addComponent('cc.ModelComponent'); modelCom.material = material; - modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + modelCom.mesh = cc.utils.createMesh(cc.game._gfxDevice, cc.primitives.box()); modelNode.setRotationFromEuler(45, 45, 45); cc.director.runSceneImmediate(scene); From d24aeb1550eb8c839f1cec94739d79a89f9cea7f Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 17:21:07 +0800 Subject: [PATCH 121/267] add @property --- cocos/3d/assets/mesh.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 983230fa12..1091f0f01a 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -376,6 +376,7 @@ export class Mesh extends Asset { return this._data; } + @property private _struct: IMeshStruct; private _data: Uint8Array | null = null; From a4bed0cdee782cb02d4e5bb255d2b4b4ef3642b6 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 17:33:46 +0800 Subject: [PATCH 122/267] delete Topology enum --- cocos/3d/assets/mesh.ts | 27 ++------------------------- cocos/3d/misc/utils.ts | 16 ++-------------- 2 files changed, 4 insertions(+), 39 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 1091f0f01a..943dbd1b2e 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -98,29 +98,6 @@ export enum AttributeType { ccenum(AttributeType); -export enum Topology { - /** - * Point list. - */ - POINT_LIST = GFXPrimitiveMode.POINT_LIST, - - /** - * Line list. - */ - LINE_LIST = GFXPrimitiveMode.LINE_LIST, - - /** - * Triangle list. - */ - TRIANGLE_LIST = GFXPrimitiveMode.TRIANGLE_LIST, -} - -ccenum(Topology); - -function toGFXTopology (topology: Topology) { - return topology as unknown as GFXPrimitiveMode; -} - export enum IndexUnit { /** * 8 bits unsigned integer. @@ -262,7 +239,7 @@ export interface IPrimitive { /** * This primitive's topology. */ - topology: Topology; + primitiveMode: GFXPrimitiveMode; } /** @@ -501,7 +478,7 @@ export class Mesh extends Asset { } return { - primitiveMode: toGFXTopology(primitive.topology), + primitiveMode: primitive.primitiveMode, inputAssembler: gfxDevice.createInputAssembler(inputAssemblerInfo), } as IRenderingSubmesh ; }); diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 09db9ade47..4070547774 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -4,7 +4,7 @@ import Texture2D from '../../assets/texture-2d'; import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; import { Vec3 } from '../../core/value-types'; import { AttributeBaseType, AttributeType, - IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh, Topology } from '../assets/mesh'; + IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh } from '../assets/mesh'; import { IGeometry } from '../primitive/defines'; /** @@ -101,7 +101,7 @@ export function createMesh (geometry: IGeometry) { // Create primitive. const primitive: IPrimitive = { - topology: _getTopology(geometry.primitiveMode), + primitiveMode: geometry.primitiveMode, vertexBundelIndices: [0], }; if (indexBuffer) { @@ -192,18 +192,6 @@ class BufferBlob { } } -function _getTopology (primitiveMode: GFXPrimitiveMode) { - switch (primitiveMode) { - case GFXPrimitiveMode.POINT_LIST: - return Topology.POINT_LIST; - case GFXPrimitiveMode.LINE_LIST: - return Topology.LINE_LIST; - case GFXPrimitiveMode.TRIANGLE_LIST: - return Topology.TRIANGLE_LIST; - } - return Topology.POINT_LIST; -} - function _writeVertices ( target: DataView, offset: number, stride: number, attribute: IVertexAttribute, data: number[]) { const writer = _getVerticesWriter(target, attribute.baseType); From fc05fdcf4742732757b23371b7ec1daae98db681 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 14 Jan 2019 17:46:10 +0800 Subject: [PATCH 123/267] minor --- cocos/3d/assets/material.ts | 4 +- cocos/3d/assets/mesh.ts | 4 +- cocos/3d/framework/model-component.js | 4 +- cocos/3d/misc/utils.js | 69 --------------------------- cocos/renderer/scene/model.ts | 1 - 5 files changed, 6 insertions(+), 76 deletions(-) delete mode 100644 cocos/3d/misc/utils.js diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index cfc9f86801..dd82a19612 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -26,8 +26,8 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { GFXBindingType } from '../../gfx/define'; import { Effect } from '../../renderer/core/effect'; -import { Pass, IPassOverrides } from '../../renderer/core/pass'; -import { EffectAsset, IPassInfo, ITechniqueInfo } from './effect-asset'; +import { IPassOverrides, Pass } from '../../renderer/core/pass'; +import { EffectAsset } from './effect-asset'; @ccclass('cc.Material') export class Material extends Asset { diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 943dbd1b2e..9bbdf5aff5 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -396,7 +396,7 @@ export class Mesh extends Asset { * Gets the rendering mesh. */ public get renderingMesh () { - this._lazyInitRenderResources(); + this._deferredInit(); return this._renderingMesh; } @@ -411,7 +411,7 @@ export class Mesh extends Asset { return renderingSubmesh ? renderingSubmesh.inputAssembler : null; } - private _lazyInitRenderResources () { + private _deferredInit () { if (this._initialized) { return; } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 66dc454c29..d5197a0a7e 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -259,8 +259,8 @@ export default class ModelComponent extends RenderableComponent { return; for (let i = 0; i < this._models.length; ++i) { let model = this._models[i]; - if (model._defines['_USE_SHADOW_MAP'] != undefined) { - this.getMaterial(i).define('_USE_SHADOW_MAP', this._receiveShadows); + if (model._defines['CC_USE_SHADOW_MAP'] != undefined) { + this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); } } } diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js deleted file mode 100644 index a6256437a4..0000000000 --- a/cocos/3d/misc/utils.js +++ /dev/null @@ -1,69 +0,0 @@ -import { renderer } from '../../renderer'; -import find from '../../scene-graph/find'; -import { Mesh, RenderingMesh } from '../assets/mesh'; -import gfx from '../../renderer/gfx/index'; -import { GFXPrimitiveMode } from '../../gfx/define'; - -/** - * - * @param {import("../assets/skeleton").default} skinning - */ -function createJointsTexture(skinning) { - const jointCount = skinning.joints.length; - - // Set jointsTexture. - // A squared texture with side length N(N > 1) multiples of 2 can store - // 2 ^ (2 * N - 2) matrices. - // We support most 1024 joints. - let size; - if (jointCount > 1024) { - throw "To many joints(more than 1024)."; - } else if (jointCount > 256) { - size = 64; - } else if (jointCount > 64) { - size = 32; - } else if (jointCount > 16) { - size = 16; - } else if (jointCount > 4) { - size = 8; - } else { - size = 4; - } - - return new gfx.Texture2D(cc.game._gfxDevice, { - width: size, - height: size, - format: gfx.TEXTURE_FMT_RGBA32F, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - mipmap: false - }); -} - -function createMesh(context, data) { - let ia = renderer.createIA(context, data); - let meshAsset = new Mesh(); - const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; - meshAsset._renderingMesh = new RenderingMesh([{inputAssembler: ia, primitiveMode}], [], []); - meshAsset._minPosition = data.minPos; - meshAsset._maxPosition = data.maxPos; - - return meshAsset; -} - -/** - * @param {Uint8Array} buffer - */ -function toPPM(buffer, w, h) { - return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; -} - -export default { - createJointsTexture, - createMesh, - - find, - toPPM -}; diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index daf815ad94..d0c23c6246 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -220,7 +220,6 @@ export class Model { const subMesh = this._subMeshObject as IRenderingSubmesh; pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, localUBO); - pass.update(); const cmdBuff = this._cmdBuffers[index]; cmdBuff.begin(); From 956ea89164d3f4d3cdb93e336968d631096e006c Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 14 Jan 2019 20:42:16 +0800 Subject: [PATCH 124/267] add cached array, and optimize render queue with it --- cocos/3d/misc/utils.js | 69 ------------------------- cocos/core/memop/cached-array.ts | 47 +++++++++++++++++ cocos/gfx/command-buffer.ts | 2 +- cocos/gfx/webgl/webgl-command-buffer.ts | 15 +++--- cocos/pipeline/forward/forward-stage.ts | 8 +-- cocos/pipeline/render-queue.ts | 63 +++++++++++----------- 6 files changed, 88 insertions(+), 116 deletions(-) delete mode 100644 cocos/3d/misc/utils.js create mode 100644 cocos/core/memop/cached-array.ts diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js deleted file mode 100644 index a6256437a4..0000000000 --- a/cocos/3d/misc/utils.js +++ /dev/null @@ -1,69 +0,0 @@ -import { renderer } from '../../renderer'; -import find from '../../scene-graph/find'; -import { Mesh, RenderingMesh } from '../assets/mesh'; -import gfx from '../../renderer/gfx/index'; -import { GFXPrimitiveMode } from '../../gfx/define'; - -/** - * - * @param {import("../assets/skeleton").default} skinning - */ -function createJointsTexture(skinning) { - const jointCount = skinning.joints.length; - - // Set jointsTexture. - // A squared texture with side length N(N > 1) multiples of 2 can store - // 2 ^ (2 * N - 2) matrices. - // We support most 1024 joints. - let size; - if (jointCount > 1024) { - throw "To many joints(more than 1024)."; - } else if (jointCount > 256) { - size = 64; - } else if (jointCount > 64) { - size = 32; - } else if (jointCount > 16) { - size = 16; - } else if (jointCount > 4) { - size = 8; - } else { - size = 4; - } - - return new gfx.Texture2D(cc.game._gfxDevice, { - width: size, - height: size, - format: gfx.TEXTURE_FMT_RGBA32F, - minFilter: gfx.FILTER_NEAREST, - magFilter: gfx.FILTER_NEAREST, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - mipmap: false - }); -} - -function createMesh(context, data) { - let ia = renderer.createIA(context, data); - let meshAsset = new Mesh(); - const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; - meshAsset._renderingMesh = new RenderingMesh([{inputAssembler: ia, primitiveMode}], [], []); - meshAsset._minPosition = data.minPos; - meshAsset._maxPosition = data.maxPos; - - return meshAsset; -} - -/** - * @param {Uint8Array} buffer - */ -function toPPM(buffer, w, h) { - return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; -} - -export default { - createJointsTexture, - createMesh, - - find, - toPPM -}; diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts new file mode 100644 index 0000000000..f63b7e3db5 --- /dev/null +++ b/cocos/core/memop/cached-array.ts @@ -0,0 +1,47 @@ +export class CachedArray { + + public data: Array; + public length: number = 0; + private _compareFn; + + constructor (count: number, compareFn?: (a: T, b: T) => number) { + this.data = new Array(count); + this.length = 0; + + if (compareFn !== undefined) { + this._compareFn = compareFn; + } else { + this._compareFn = (a: number, b: number) => a - b; + } + } + + public push (item: T) { + if (this.length >= this.data.length) { + const size = this.length * 2; + const temp = this.data; + this.data = new Array(size); + for (let i = 0; i < temp.length; ++i) { + this.data[i] = temp[i]; + } + } + + this.data[this.length++] = item; + } + + public pop (): T | undefined { + return this.data[this.length--]; + } + + public get (idx: number): T | undefined { + return this.data[idx]; + } + + public clear () { + this.length = 0; + } + + public sort () { + this.data.fill(undefined, this.length, this.data.length); + this.data.sort(this._compareFn); + } +} diff --git a/cocos/gfx/command-buffer.ts b/cocos/gfx/command-buffer.ts index 28388d51fe..fd14d277d9 100644 --- a/cocos/gfx/command-buffer.ts +++ b/cocos/gfx/command-buffer.ts @@ -50,5 +50,5 @@ export abstract class GFXCommandBuffer extends GFXObject { 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[]); - public abstract execute (cmdBuffs: GFXCommandBuffer[]); + public abstract execute (cmdBuffs: GFXCommandBuffer[], count: number); } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 1f64f68349..f15abbb38d 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -124,7 +124,6 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public draw (inputAssembler: GFXInputAssembler) { - if (this._type === GFXCommandBufferType.PRIMARY && this._isInRenderPass || this._type === GFXCommandBufferType.SECONDARY) { if (this._isStateInvalied) { @@ -145,7 +144,8 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public updateBuffer (buffer: GFXBuffer, data: GFXBufferSource, offset?: number, size?: number) { - if (!this._isInRenderPass) { + if (this._type === GFXCommandBufferType.PRIMARY && !this._isInRenderPass || + this._type === GFXCommandBufferType.SECONDARY) { const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; if (gpuBuffer) { const cmd = (this._allocator as WebGLGFXCommandAllocator). @@ -183,7 +183,8 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { dstLayout: GFXTextureLayout, regions: GFXBufferTextureCopy[]) { - if (!this._isInRenderPass) { + if (this._type === GFXCommandBufferType.PRIMARY && !this._isInRenderPass || + this._type === GFXCommandBufferType.SECONDARY) { const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; if (gpuBuffer && gpuTexture) { @@ -205,10 +206,10 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } // tslint:disable: max-line-length - public execute (cmdBuffs: GFXCommandBuffer[]) { + public execute (cmdBuffs: GFXCommandBuffer[], count: number) { - for (const cmdBuff of cmdBuffs) { - const webGLCmdBuff = cmdBuff as WebGLGFXCommandBuffer; + for (let i = 0; i < count; ++i) { + const webGLCmdBuff = cmdBuffs[i] as WebGLGFXCommandBuffer; this.cmdPackage.beginRenderPassCmds = this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); this.cmdPackage.bindStatesCmds = this.cmdPackage.bindStatesCmds.concat(webGLCmdBuff.cmdPackage.bindStatesCmds); @@ -220,7 +221,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public get webGLDevice (): WebGLGFXDevice { - return this._device as WebGLGFXDevice; + return this._device as WebGLGFXDevice; } private bindStates () { diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index c0589212cd..f7b3644166 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -51,13 +51,7 @@ export class ForwardStage extends RenderStage { cmdBuff.beginRenderPass(this._framebuffer as GFXFramebuffer, this._renderArea, [camera.clearColor], camera.clearDepth, camera.clearStencil); - for (const item of queue.opaques) { - cmdBuff.execute([item.cmdBuff]); - } - - for (const item of queue.transparents) { - cmdBuff.execute([item.cmdBuff]); - } + cmdBuff.execute(queue.cmdBuffs, queue.cmdBuffCount); cmdBuff.endRenderPass(); cmdBuff.end(); diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index 458f3b5ba8..a194e70cb1 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -1,12 +1,10 @@ +import { CachedArray } from '../core/memop/cached-array'; import { vec3 } from '../core/vmath'; import { GFXCommandBuffer } from '../gfx/command-buffer'; import { Pass } from '../renderer/core/pass'; import { Camera } from '../renderer/scene/camera'; import { Model } from '../renderer/scene/model'; -const _pos: vec3 = vec3.create(); -const _cameraPos: vec3 = vec3.create(); - export class RenderItem { public hash: number; public model: Model; @@ -22,35 +20,40 @@ export class RenderItem { } export class RenderQueue { - - public opaques: RenderItem[] = []; - // public opaqueCmdBuffs: GFXCommandBuffer[] = []; - public transparents: RenderItem[] = []; - // public transparentCmdBuffs: GFXCommandBuffer[] = []; + public opaques: CachedArray; + public transparents: CachedArray; + public cmdBuffs: GFXCommandBuffer[] = []; + public cmdBuffCount: number = 0; private _buffer: ArrayBuffer; private _f32View: Float32Array; private _ui32View: Uint32Array; constructor () { + const compareFn = (a: RenderItem, b: RenderItem) => { + return a.hash - b.hash; + }; + + this.opaques = new CachedArray(64, compareFn); + this.transparents = new CachedArray(64, compareFn); + this._buffer = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT); this._f32View = new Float32Array(this._buffer); this._ui32View = new Uint32Array(this._buffer); } public clear () { - this.opaques = []; - this.transparents = []; + this.opaques.clear(); + this.transparents.clear(); + this.cmdBuffCount = 0; } public add (model: Model, camera: Camera) { - model.node.getPosition(_pos); - camera.node.getPosition(_cameraPos); - this._f32View[0] = vec3.distance(_cameraPos, _pos); + this._f32View[0] = vec3.distance(camera.node.getPosition(), model.node.getPosition()); let ui32Depth: number = this._ui32View[0]; const mask = -(ui32Depth >> 31) | 0x8000000000000000; ui32Depth = (ui32Depth ^ mask); - const ui32DepthInv = (ui32Depth ^ 0xffffffffffffffff); + const ui32DepthInv = (ui32Depth ^ 0x00000000ffffffff); for (let i = 0; i < model.passes.length; ++i) { const pass = model.passes[i]; @@ -58,10 +61,6 @@ export class RenderQueue { // update pass pass.update(); - const cmdBuff = model.commandBuffers[i]; - - model.node.getWorldPosition(); - const pso = pass.pipelineState; const isTransparent = pso.blendState.targets[0].blend; @@ -72,36 +71,36 @@ export class RenderQueue { // Opaque objects are sorted by depth front to back -> pass priority -> shader id. const hash = (0 << 61) | (i << 45) | (ui32Depth << 13) | pso.shader.id; - this.opaques.push({hash, model, pass, cmdBuff}); + this.opaques.push({hash, model, pass, cmdBuff: model.commandBuffers[i]}); } else { // Transparent objects are sorted by depth back to front -> pass priority -> shader id. const hash = (1 << 61) | (i << 45) | (ui32DepthInv << 13) | pso.shader.id; - this.transparents.push({hash, model, pass, cmdBuff}); + this.transparents.push({hash, model, pass, cmdBuff: model.commandBuffers[i]}); } } } public sort () { - this.opaques.sort((a: RenderItem, b: RenderItem) => { - return a.hash - b.hash; - }); + this.opaques.sort(); + this.transparents.sort(); - this.transparents.sort((a: RenderItem, b: RenderItem) => { - return a.hash - b.hash; - }); + const opaqueCount = this.opaques.length; + const cmdBuffCount = opaqueCount + this.transparents.length; + + if (cmdBuffCount > this.cmdBuffs.length) { + this.cmdBuffs = new Array(cmdBuffCount); + } + + this.cmdBuffCount = cmdBuffCount; - /* - this.opaqueCmdBuffs = new Array(this.opaques.length); for (let i = 0; i < this.opaques.length; ++i) { - this.opaqueCmdBuffs[i] = this.opaques[i].cmdBuff; + this.cmdBuffs[i] = (this.opaques.data[i] as RenderItem).cmdBuff; } - this.transparentCmdBuffs = new Array(this.transparents.length); for (let i = 0; i < this.transparents.length; ++i) { - this.transparentCmdBuffs[i] = this.transparents[i].cmdBuff; + this.cmdBuffs[opaqueCount + i] = (this.transparents.data[i] as RenderItem).cmdBuff; } - */ } } From 803720b159e91ddec3bbca4848499b492cec8ec1 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 15 Jan 2019 00:17:32 +0800 Subject: [PATCH 125/267] optimize command buffer with cached array --- cocos/core/memop/cached-array.ts | 71 +++++++++++++++++++------ cocos/gfx/webgl/webgl-command-buffer.ts | 22 +++++--- cocos/gfx/webgl/webgl-commands.ts | 58 ++++++++++---------- cocos/pipeline/forward/forward-stage.ts | 2 +- cocos/pipeline/render-queue.ts | 11 ++-- 5 files changed, 106 insertions(+), 58 deletions(-) diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index f63b7e3db5..c11ff7636b 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -1,11 +1,13 @@ export class CachedArray { - public data: Array; + public array: T[]; public length: number = 0; private _compareFn; + private _cache: Array; - constructor (count: number, compareFn?: (a: T, b: T) => number) { - this.data = new Array(count); + constructor (length: number, compareFn?: (a: T, b: T) => number) { + this.array = new Array(length); + this._cache = this.array; this.length = 0; if (compareFn !== undefined) { @@ -15,25 +17,34 @@ export class CachedArray { } } - public push (item: T) { - if (this.length >= this.data.length) { - const size = this.length * 2; - const temp = this.data; - this.data = new Array(size); - for (let i = 0; i < temp.length; ++i) { - this.data[i] = temp[i]; + public reserve (length: number) { + if (length > this.array.length) { + this.array = new Array(length); + for (let i = 0; i < this._cache.length; ++i) { + this.array[i] = this._cache[i] as T; } + this._cache = this.array; + } + } + + public push (item: T) { + if (this.length > this.array.length) { + this.array = new Array(length); + for (let i = 0; i < this._cache.length; ++i) { + this.array[i] = this._cache[i] as T; + } + this._cache = this.array; } - this.data[this.length++] = item; + this.array[this.length++] = item; } public pop (): T | undefined { - return this.data[this.length--]; + return this.array[this.length--]; } - public get (idx: number): T | undefined { - return this.data[idx]; + public get (idx: number): T { + return this.array[idx]; } public clear () { @@ -41,7 +52,35 @@ export class CachedArray { } public sort () { - this.data.fill(undefined, this.length, this.data.length); - this.data.sort(this._compareFn); + this._cache.fill(undefined, this.length, this.array.length); + this._cache.sort(this._compareFn); + } + + public concat (array: CachedArray) { + if (array.length + this.length > this._cache.length) { + this.array = new Array(length); + for (let i = 0; i < this._cache.length; ++i) { + this.array[i] = this._cache[i] as T; + } + this._cache = this.array; + } + + for (let i = 0; i < array.length; ++i) { + this._cache[this.length++] = array.array[i]; + } + } + + public append (array: T[]) { + if (array.length + this.length > this._cache.length) { + this.array = new Array(length); + for (let i = 0; i < this._cache.length; ++i) { + this.array[i] = this._cache[i] as T; + } + this._cache = this.array; + } + + for (const item of array) { + this._cache[this.length++] = item; + } } } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index f15abbb38d..4ddb37644b 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -1,7 +1,15 @@ import { GFXBindingLayout } from '../binding-layout'; import { GFXBuffer, GFXBufferSource } from '../buffer'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; -import { GFXBufferTextureCopy, GFXBufferUsageBit, GFXStatus, GFXTextureLayout, IGFXColor, IGFXRect, GFXCommandBufferType } from '../define'; +import { + GFXBufferTextureCopy, + GFXBufferUsageBit, + GFXCommandBufferType, + GFXStatus, + GFXTextureLayout, + IGFXColor, + IGFXRect, +} from '../define'; import { GFXDevice } from '../device'; import { GFXFramebuffer } from '../framebuffer'; import { GFXInputAssembler } from '../input-assembler'; @@ -211,12 +219,12 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { for (let i = 0; i < count; ++i) { const webGLCmdBuff = cmdBuffs[i] as WebGLGFXCommandBuffer; - this.cmdPackage.beginRenderPassCmds = this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); - this.cmdPackage.bindStatesCmds = this.cmdPackage.bindStatesCmds.concat(webGLCmdBuff.cmdPackage.bindStatesCmds); - this.cmdPackage.drawCmds = this.cmdPackage.drawCmds.concat(webGLCmdBuff.cmdPackage.drawCmds); - this.cmdPackage.updateBufferCmds = this.cmdPackage.updateBufferCmds.concat(webGLCmdBuff.cmdPackage.updateBufferCmds); - this.cmdPackage.copyBufferToTextureCmds = this.cmdPackage.copyBufferToTextureCmds.concat(webGLCmdBuff.cmdPackage.copyBufferToTextureCmds); - this.cmdPackage.cmds = this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); + this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); + this.cmdPackage.bindStatesCmds.concat(webGLCmdBuff.cmdPackage.bindStatesCmds); + this.cmdPackage.drawCmds.concat(webGLCmdBuff.cmdPackage.drawCmds); + this.cmdPackage.updateBufferCmds.concat(webGLCmdBuff.cmdPackage.updateBufferCmds); + this.cmdPackage.copyBufferToTextureCmds.concat(webGLCmdBuff.cmdPackage.copyBufferToTextureCmds); + this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); } } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 9310c3b284..405a4d97fb 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -9,6 +9,7 @@ import { WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer WebGLGPUInput, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniform, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; import { IWebGLTexUnit } from './webgl-state-cache'; +import { CachedArray } from '../../core/memop/cached-array'; // tslint:disable: max-line-length @@ -442,51 +443,51 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { } export class WebGLCmdPackage { - public cmds: WebGLCmd[] = []; - public beginRenderPassCmds: WebGLCmdBeginRenderPass[] = []; - public bindStatesCmds: WebGLCmdBindStates[] = []; - public drawCmds: WebGLCmdDraw[] = []; - public updateBufferCmds: WebGLCmdUpdateBuffer[] = []; - public copyBufferToTextureCmds: WebGLCmdCopyBufferToTexture[] = []; + public cmds: CachedArray = new CachedArray(1); + public beginRenderPassCmds: CachedArray = new CachedArray(1); + public bindStatesCmds: CachedArray = new CachedArray(1); + public drawCmds: CachedArray = new CachedArray(1); + public updateBufferCmds: CachedArray = new CachedArray(1); + public copyBufferToTextureCmds: CachedArray = new CachedArray(1); public clearCmds (allocator: WebGLGFXCommandAllocator) { if (this.beginRenderPassCmds.length) { - for (const beginRenderPassCmd of this.beginRenderPassCmds) { - allocator.beginRenderPassCmdPool.free(beginRenderPassCmd); + for (let i = 0; i < this.beginRenderPassCmds.length; ++i) { + allocator.beginRenderPassCmdPool.free(this.beginRenderPassCmds.array[i]); } - this.beginRenderPassCmds = []; + this.beginRenderPassCmds.clear(); } if (this.bindStatesCmds.length) { - for (const bindStatesCmd of this.bindStatesCmds) { - allocator.bindStatesCmdPool.free(bindStatesCmd); + for (let i = 0; i < this.bindStatesCmds.length; ++i) { + allocator.bindStatesCmdPool.free(this.bindStatesCmds.array[i]); } - this.bindStatesCmds = []; + this.bindStatesCmds.clear(); } if (this.drawCmds.length) { - for (const drawCmd of this.drawCmds) { - allocator.drawCmdPool.free(drawCmd); + for (let i = 0; i < this.drawCmds.length; ++i) { + allocator.drawCmdPool.free(this.drawCmds.array[i]); } - this.drawCmds = []; + this.drawCmds.clear(); } if (this.updateBufferCmds.length) { - for (const updateBufferCmd of this.updateBufferCmds) { - allocator.updateBufferCmdPool.free(updateBufferCmd); + for (let i = 0; i < this.updateBufferCmds.length; ++i) { + allocator.updateBufferCmdPool.free(this.updateBufferCmds.array[i]); } - this.updateBufferCmds = []; + this.updateBufferCmds.clear(); } if (this.copyBufferToTextureCmds.length) { - for (const copyBufferToTextureCmd of this.copyBufferToTextureCmds) { - allocator.copyBufferToTextureCmdPool.free(copyBufferToTextureCmd); + for (let i = 0; i < this.copyBufferToTextureCmds.length; ++i) { + allocator.copyBufferToTextureCmdPool.free(this.copyBufferToTextureCmds.array[i]); } - this.copyBufferToTextureCmds = []; + this.copyBufferToTextureCmds.clear(); } - this.cmds = []; + this.cmds.clear(); } } @@ -1086,12 +1087,13 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web let gpuInputAssembler: WebGLGPUInputAssembler | null = null; let glPrimitive = WebGLRenderingContext.TRIANGLES; - for (const cmd of cmdPackage.cmds) { + for (let i = 0; i < cmdPackage.cmds.length; ++i) { + const cmd = cmdPackage.cmds.array[i]; const cmdId = cmdIds[cmd]++; switch (cmd) { case WebGLCmd.BEGIN_RENDER_PASS: { - const cmd0 = cmdPackage.beginRenderPassCmds[cmdId]; + const cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId]; let clears: GLbitfield = 0; @@ -1263,7 +1265,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLCmd.BIND_STATES: { - const cmd2 = cmdPackage.bindStatesCmds[cmdId]; + const cmd2 = cmdPackage.bindStatesCmds.array[cmdId]; if (cmd2.gpuPipelineState) { glPrimitive = cmd2.gpuPipelineState.glPrimitive; @@ -1883,7 +1885,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web break; } case WebGLCmd.DRAW: { - const cmd3: WebGLCmdDraw = cmdPackage.drawCmds[cmdId]; + const cmd3: WebGLCmdDraw = cmdPackage.drawCmds.array[cmdId]; if (gpuInputAssembler && gpuShader) { if (!cmd3.isIndirect) { const drawInfo = cmd3.drawInfo as IGFXDrawInfo; @@ -1913,7 +1915,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web break; } case WebGLCmd.UPDATE_BUFFER: { - const cmd4 = cmdPackage.updateBufferCmds[cmdId]; + const cmd4 = cmdPackage.updateBufferCmds.array[cmdId]; WebGLCmdFuncUpdateBuffer( device, cmd4.gpuBuffer as WebGLGPUBuffer, @@ -1924,7 +1926,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web break; } case WebGLCmd.COPY_BUFFER_TO_TEXTURE: { - const cmd5 = cmdPackage.copyBufferToTextureCmds[cmdId]; + const cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId]; WebGLCmdFuncCopyBufferToTexture( device, (cmd5.gpuBuffer as WebGLGPUBuffer).buffer as GFXBufferSource, diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index f7b3644166..f0b780c527 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -51,7 +51,7 @@ export class ForwardStage extends RenderStage { cmdBuff.beginRenderPass(this._framebuffer as GFXFramebuffer, this._renderArea, [camera.clearColor], camera.clearDepth, camera.clearStencil); - cmdBuff.execute(queue.cmdBuffs, queue.cmdBuffCount); + cmdBuff.execute(queue.cmdBuffs.array, queue.cmdBuffCount); cmdBuff.endRenderPass(); cmdBuff.end(); diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index a194e70cb1..e2f87ad394 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -22,7 +22,7 @@ export class RenderItem { export class RenderQueue { public opaques: CachedArray; public transparents: CachedArray; - public cmdBuffs: GFXCommandBuffer[] = []; + public cmdBuffs: CachedArray; public cmdBuffCount: number = 0; private _buffer: ArrayBuffer; private _f32View: Float32Array; @@ -35,6 +35,7 @@ export class RenderQueue { this.opaques = new CachedArray(64, compareFn); this.transparents = new CachedArray(64, compareFn); + this.cmdBuffs = new CachedArray(64); this._buffer = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT); this._f32View = new Float32Array(this._buffer); @@ -89,18 +90,16 @@ export class RenderQueue { const opaqueCount = this.opaques.length; const cmdBuffCount = opaqueCount + this.transparents.length; - if (cmdBuffCount > this.cmdBuffs.length) { - this.cmdBuffs = new Array(cmdBuffCount); - } + this.cmdBuffs.reserve(cmdBuffCount); this.cmdBuffCount = cmdBuffCount; for (let i = 0; i < this.opaques.length; ++i) { - this.cmdBuffs[i] = (this.opaques.data[i] as RenderItem).cmdBuff; + this.cmdBuffs.array[i] = this.opaques.array[i].cmdBuff; } for (let i = 0; i < this.transparents.length; ++i) { - this.cmdBuffs[opaqueCount + i] = (this.transparents.data[i] as RenderItem).cmdBuff; + this.cmdBuffs.array[opaqueCount + i] = this.transparents.array[i].cmdBuff; } } } From 455409784bbab3477454a5e3e9c4d82c4daeadf1 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 15 Jan 2019 10:27:53 +0800 Subject: [PATCH 126/267] fix pass overrides --- cocos/renderer/core/pass.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index c89a96c36e..714b405836 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -210,13 +210,18 @@ export class Pass { if (this._pipelineState) { this._pipelineState.destroy(); } const ors = Object.assign({}, overrides); this._createPipelineState(info, (states) => { + if (overrides.primitive !== undefined) { states.primitive = overrides.primitive; } Object.assign(states.rs, ors.rs); Object.assign(states.dss, ors.dss); - for (let i = 0; i < ors.bs.targets.length; i++) { - Object.assign(states.bs.targets[i], ors.bs.targets[i]); + 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); } - delete ors.bs.targets; - Object.assign(states.bs, ors.bs); }); } From a49e6e5f594fc1c1825ad4117579a7c820ba5dd5 Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 15 Jan 2019 10:32:26 +0800 Subject: [PATCH 127/267] fix node api --- cocos/scene-graph/node.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 454cf8e880..b9125e0327 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -288,7 +288,7 @@ class Node extends BaseNode { * @param z - The z component of the new local position. * @param w - The w component of the new local position. */ - public setPosition (x: number, y?: number, z?: number, w?: number): void; + public setPosition (x: number, y: number, z: number): void; /** * set local position @@ -334,7 +334,7 @@ class Node extends BaseNode { * @param z - The z component of the new local rotation. * @param w - The w component of the new local rotation. */ - public setRotation (x: number, y?: number, z?: number, w?: number): void; + public setRotation (x: number, y: number, z: number, w: number): void; public setRotation (val: Quat | number, y?: number, z?: number, w?: number) { if (y === undefined || z === undefined || w === undefined) { @@ -389,9 +389,8 @@ class Node extends BaseNode { * @param x - The x component of the new local scale. * @param y - The y component of the new local scale. * @param z - The z component of the new local scale. - * @param w - The w component of the new local scale. */ - public setScale (x: number, y?: number, z?: number, w?: number): void; + public setScale (x: number, y: number, z: number): void; /** * set local scale @@ -435,9 +434,8 @@ class Node extends BaseNode { * @param x - The x component of the new world position. * @param y - The y component of the new world position. * @param z - The z component of the new world position. - * @param w - The w component of the new world position. */ - public setWorldPosition (x: number, y?: number, z?: number, w?: number): void; + public setWorldPosition (x: number, y: number, z: number): void; /** * set world position @@ -493,7 +491,7 @@ class Node extends BaseNode { * @param z - The z component of the new world rotation. * @param w - The w component of the new world rotation. */ - public setWorldRotation (x: number, y?: number, z?: number, w?: number): void; + public setWorldRotation (x: number, y: number, z: number, w: number): void; /** * set world rotation @@ -566,9 +564,8 @@ class Node extends BaseNode { * @param x - The x component of the new world scale. * @param y - The y component of the new world scale. * @param z - The z component of the new world scale. - * @param w - The w component of the new world scale. */ - public setWorldScale (x: number, y?: number, z?: number, w?: number): void; + public setWorldScale (x: number, y: number, z: number): void; /** * set world scale From 0cc79efed97a1f3f07ddecfc44c37aa8cef165a6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 15 Jan 2019 10:39:10 +0800 Subject: [PATCH 128/267] modify indirect interface --- cocos/gfx/input-assembler.ts | 21 +++++++++++---------- cocos/gfx/webgl/webgl-command-buffer.ts | 2 +- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 9061730b13..3e58ed3dfd 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,4 +1,4 @@ -import { GFXBuffer, IGFXDrawInfo } from './buffer'; +import { GFXBuffer, IGFXDrawInfo, IGFXIndirectBuffer } from './buffer'; import { GFXFormat, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; @@ -93,14 +93,6 @@ export abstract class GFXInputAssembler extends GFXObject { return this._isIndirect; } - public set indirects (drawInfos: IGFXDrawInfo[]) { - this.indirects = drawInfos; - } - - public get indirects (): IGFXDrawInfo[] { - return this._indirects; - } - public get indirectBuffer (): GFXBuffer | null { return this._indirectBuffer; } @@ -117,7 +109,6 @@ export abstract class GFXInputAssembler extends GFXObject { protected _instanceCount: number = 0; protected _firstInstance: number = 0; protected _isIndirect: boolean = false; - protected _indirects: IGFXDrawInfo[] = []; protected _indirectBuffer: GFXBuffer | null = null; constructor (device: GFXDevice) { @@ -135,4 +126,14 @@ export abstract class GFXInputAssembler extends GFXObject { return null; } } + + public extractDrawInfo (drawInfo: IGFXDrawInfo) { + drawInfo.vertexCount = this._vertexCount; + drawInfo.firstVertex = this._firstVertex; + drawInfo.indexCount = this._indexCount; + drawInfo.firstIndex = this._firstIndex; + drawInfo.vertexOffset = this._vertexOffset; + drawInfo.instanceCount = this._instanceCount; + drawInfo.firstInstance = this._firstInstance; + } } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 4ddb37644b..8806d9c3f4 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -172,7 +172,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { const buff = data as ArrayBuffer; cmd.gpuBuffer = gpuBuffer; - cmd.buffer = buff.slice(0); + cmd.buffer = buff; cmd.offset = (offset !== undefined ? offset : 0); cmd.size = buffSize; this.cmdPackage.updateBufferCmds.push(cmd); From 06d8ab9772a1580d3bb86aa058a116aed3c58a06 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 15 Jan 2019 10:54:28 +0800 Subject: [PATCH 129/267] remove GFXInputAssemblerInfo.isIndirect --- cocos/gfx/input-assembler.ts | 3 +-- cocos/gfx/pipeline-state.ts | 14 +++++++++++++- cocos/gfx/webgl/webgl-commands.ts | 5 ++--- cocos/gfx/webgl/webgl-input-assembler.ts | 9 ++------- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/cocos/gfx/input-assembler.ts b/cocos/gfx/input-assembler.ts index 3e58ed3dfd..5a5856164e 100644 --- a/cocos/gfx/input-assembler.ts +++ b/cocos/gfx/input-assembler.ts @@ -1,4 +1,4 @@ -import { GFXBuffer, IGFXDrawInfo, IGFXIndirectBuffer } from './buffer'; +import { GFXBuffer, IGFXDrawInfo } from './buffer'; import { GFXFormat, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; @@ -15,7 +15,6 @@ export interface IGFXInputAssemblerInfo { attributes: IGFXInputAttribute[]; vertexBuffers: GFXBuffer[]; indexBuffer?: GFXBuffer; - isIndirect?: boolean; indirectBuffer?: GFXBuffer; } diff --git a/cocos/gfx/pipeline-state.ts b/cocos/gfx/pipeline-state.ts index b854d4b7e7..524524cbbe 100644 --- a/cocos/gfx/pipeline-state.ts +++ b/cocos/gfx/pipeline-state.ts @@ -1,4 +1,16 @@ -import { GFXBlendFactor, GFXBlendOp, GFXColorMask, GFXComparisonFunc, GFXCullMode, GFXObject, GFXObjectType, GFXPolygonMode, GFXPrimitiveMode, GFXShadeModel, GFXStencilOp } from './define'; +import { + GFXBlendFactor, + GFXBlendOp, + GFXColorMask, + GFXComparisonFunc, + GFXCullMode, + GFXObject, + GFXObjectType, + GFXPolygonMode, + GFXPrimitiveMode, + GFXShadeModel, + GFXStencilOp, +} from './define'; import { GFXDevice } from './device'; import { IGFXInputAttribute } from './input-assembler'; import { GFXPipelineLayout } from './pipeline-layout'; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 405a4d97fb..a989e288a0 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,3 +1,4 @@ +import { CachedArray } from '../../core/memop/cached-array'; import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, GFXCullMode, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, GFXMemoryUsageBit, @@ -9,7 +10,6 @@ import { WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer WebGLGPUInput, WebGLGPUInputAssembler, WebGLGPUPipelineState, WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniform, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; import { IWebGLTexUnit } from './webgl-state-cache'; -import { CachedArray } from '../../core/memop/cached-array'; // tslint:disable: max-line-length @@ -394,7 +394,6 @@ export class WebGLCmdDraw extends WebGLCmdObject { firstInstance: 0, }; - public isIndirect: boolean = false; public gpuIndirectBuffer: WebGLGPUBuffer | null = null; constructor () { @@ -1887,7 +1886,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web case WebGLCmd.DRAW: { const cmd3: WebGLCmdDraw = cmdPackage.drawCmds.array[cmdId]; if (gpuInputAssembler && gpuShader) { - if (!cmd3.isIndirect) { + if (!cmd3.gpuIndirectBuffer) { const drawInfo = cmd3.drawInfo as IGFXDrawInfo; const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; diff --git a/cocos/gfx/webgl/webgl-input-assembler.ts b/cocos/gfx/webgl/webgl-input-assembler.ts index 4551e19ce2..54f1d9facc 100644 --- a/cocos/gfx/webgl/webgl-input-assembler.ts +++ b/cocos/gfx/webgl/webgl-input-assembler.ts @@ -40,10 +40,6 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { this._vertexCount = vertBuff.size / vertBuff.stride; } - if (info.isIndirect !== undefined) { - this._isIndirect = info.isIndirect; - } - this._gpuInputAssembler = this.webGLDevice.emitCmdCreateGPUInputAssembler(info); this._status = GFXStatus.SUCCESS; @@ -59,8 +55,7 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { } public extractCmdDraw (cmd: WebGLCmdDraw) { - cmd.isIndirect = this._isIndirect; - if (!this._isIndirect) { + if (!this._indirectBuffer) { cmd.drawInfo.vertexCount = this._vertexCount; cmd.drawInfo.firstVertex = this._firstVertex; cmd.drawInfo.indexCount = this._indexCount; @@ -68,7 +63,7 @@ export class WebGLGFXInputAssembler extends GFXInputAssembler { cmd.drawInfo.vertexOffset = this._vertexOffset; cmd.drawInfo.instanceCount = this._instanceCount; cmd.drawInfo.firstInstance = this._firstInstance; - cmd.isIndirect = this._isIndirect; + cmd.gpuIndirectBuffer = null; } else { cmd.gpuIndirectBuffer = (this._indirectBuffer as WebGLGFXBuffer).gpuBuffer; } From 0ac050b843273810a8739800a66a6a28bee1a9d3 Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 15 Jan 2019 11:11:52 +0800 Subject: [PATCH 130/267] renderable-component.js: rename to ts, tslint autofix --- ...e-component.js => renderable-component.ts} | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) rename cocos/3d/framework/{renderable-component.js => renderable-component.ts} (78%) diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.ts similarity index 78% rename from cocos/3d/framework/renderable-component.js rename to cocos/3d/framework/renderable-component.ts index 533c00e606..24131cf972 100644 --- a/cocos/3d/framework/renderable-component.js +++ b/cocos/3d/framework/renderable-component.ts @@ -1,7 +1,7 @@ -//@ts-check +// @ts-check +import { Component } from '../../components/component'; import { _decorator } from '../../core/data/index'; -import { Material } from "../assets/material"; -import { Component } from "../../components/component"; +import { Material } from '../assets/material'; const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') @@ -10,21 +10,21 @@ export default class RenderableComponent extends Component { * @type {Material[]} */ @property([Material]) - _materials = []; + public _materials = []; - constructor() { + constructor () { super(); } @property({ type: [Material], - displayName: 'Materials' + displayName: 'Materials', }) - get sharedMaterials() { + get sharedMaterials () { return this._materials; } - set sharedMaterials(val) { + set sharedMaterials (val) { // 因为现在编辑器的做法是,当这个val传进来时,内部的materials已经被修改了。 // 我们没办法做到上面的最优化,只能先清理ModelComponent里所有Submodel的材质,再重新关联。 this._clearMaterials(); @@ -37,14 +37,14 @@ export default class RenderableComponent extends Component { * !#ch 模型材质 * @type {Material[]} */ - get materials() { + get materials () { for (let i = 0; i < this._materials.length; i++) { this._materials[i] = this.getMaterial(i); } return this._materials; } - set materials(val) { + set materials (val) { const dLen = val.length - this._materials.length; if (dLen > 0) { this._materials = this._materials.concat(new Array(dLen).fill(null)); @@ -62,12 +62,12 @@ export default class RenderableComponent extends Component { * !#ch 返回相对应序号的材质 * @param {Number} idx - Look for the material list number */ - getMaterial(idx) { + public getMaterial (idx) { if (idx < 0 || idx >= this._materials.length || this._materials[idx] == null) { return null; } - let instantiated = Material.getInstantiatedMaterial(this._materials[idx], this); + const instantiated = Material.getInstantiatedMaterial(this._materials[idx], this); if (instantiated !== this._materials[idx]) { this.setMaterial(instantiated, idx); } @@ -75,38 +75,38 @@ export default class RenderableComponent extends Component { return this._materials[idx]; } - getSharedMaterial(idx) { + public getSharedMaterial (idx) { if (idx < 0 || idx >= this._materials.length) { return null; } return this._materials[idx]; } - get material() { + get material () { return this.getMaterial(0); } - get sharedMaterial() { + get sharedMaterial () { return this.getSharedMaterial(0); } - set material(val) { + set material (val) { if (this._materials.length === 1 && this._materials[0] === val) { return; } this.setMaterial(val, 0); } - setMaterial(material, index) { + public setMaterial (material, index) { this._materials[index] = material; this._onMaterialModified(index, material); } - _onMaterialModified(index, material) { + public _onMaterialModified (index, material) { } - _clearMaterials() { + public _clearMaterials () { } } From 437755c5a2017e2e06cb0e06c5242d8da5bd8edd Mon Sep 17 00:00:00 2001 From: Leslie Date: Tue, 15 Jan 2019 11:13:24 +0800 Subject: [PATCH 131/267] fix ts errors --- cocos/3d/framework/renderable-component.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 24131cf972..4d0055ed0e 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -6,11 +6,8 @@ const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') export default class RenderableComponent extends Component { - /** - * @type {Material[]} - */ @property([Material]) - public _materials = []; + private _materials: Material[] = []; constructor () { super(); @@ -39,7 +36,7 @@ export default class RenderableComponent extends Component { */ get materials () { for (let i = 0; i < this._materials.length; i++) { - this._materials[i] = this.getMaterial(i); + this._materials[i] = this.getMaterial(i)!; } return this._materials; } @@ -86,10 +83,6 @@ export default class RenderableComponent extends Component { return this.getMaterial(0); } - get sharedMaterial () { - return this.getSharedMaterial(0); - } - set material (val) { if (this._materials.length === 1 && this._materials[0] === val) { return; @@ -97,6 +90,10 @@ export default class RenderableComponent extends Component { this.setMaterial(val, 0); } + get sharedMaterial () { + return this.getSharedMaterial(0); + } + public setMaterial (material, index) { this._materials[index] = material; this._onMaterialModified(index, material); From a1cca05b2020dfc8d575bdf340ddaa638465d066 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 15 Jan 2019 11:21:45 +0800 Subject: [PATCH 132/267] pipeline defines --- cocos/3d/assets/mesh.ts | 2 +- cocos/3d/misc/utils.ts | 2 +- cocos/pipeline/define.ts | 4 ++++ cocos/pipeline/index.ts | 3 ++- cocos/pipeline/render-pipeline.ts | 7 +------ index.js | 1 + 6 files changed, 10 insertions(+), 9 deletions(-) create mode 100644 cocos/pipeline/define.ts diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 9bbdf5aff5..c2ad0ce406 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -404,7 +404,7 @@ export class Mesh extends Asset { * !#en * Gets the specified submesh. * @param index Index of the specified submesh. - * @deprecated Using this.renderingMesh.getSubmesh(index)inputAssembler instead. + * @deprecated Use this.renderingMesh.getSubmesh(index).inputAssembler instead. */ public getSubMesh (index: number) { const renderingSubmesh = this.renderingMesh ? this.renderingMesh.getSubmesh(index) : null; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 4070547774..8279f7c0d8 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -39,13 +39,13 @@ export function createJointsTexture (skinning: { joints: any[]; }) { return texture; } +const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); export function createMesh (geometry: IGeometry) { // Collect attributes and calculate length of result vertex buffer. const attributes: IVertexAttribute[] = []; let stride = 0; const channels: Array<{ offset: number; data: number[]; attribute: IVertexAttribute; }> = []; let verticesCount = 0; - const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); const addAttribute = (attribute: IVertexAttribute, data: number[]) => { const componentCount = _getComponentCount(attribute); const componentBytesLength = _getComponentByteLength(attribute); diff --git a/cocos/pipeline/define.ts b/cocos/pipeline/define.ts new file mode 100644 index 0000000000..bd8119ba8b --- /dev/null +++ b/cocos/pipeline/define.ts @@ -0,0 +1,4 @@ + +export enum RenderPassStage { + DEFAULT = 100, +} diff --git a/cocos/pipeline/index.ts b/cocos/pipeline/index.ts index 3bdeba37ab..7c6da1eb92 100644 --- a/cocos/pipeline/index.ts +++ b/cocos/pipeline/index.ts @@ -1 +1,2 @@ -import "./render-view"; +import './define'; +import './render-view'; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 94712630ce..cddb7ab4cf 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,7 +1,6 @@ import { intersect } from '../3d/geom-utils'; import { Root } from '../core/root'; -import { vec3 } from '../core/vmath'; -import mat4 from '../core/vmath/mat4'; +import { mat4, vec3 } from '../core/vmath'; import { GFXBuffer } from '../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXType } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; @@ -15,10 +14,6 @@ import { IRenderFlowInfo, RenderFlow } from './render-flow'; import { RenderQueue } from './render-queue'; import { RenderView } from './render-view'; -export enum RenderPassStage { - DEFAULT = 100, -} - export class UBOGlobal { public static TIME_OFFSET: number = 0; public static SCREEN_SIZE_OFFSET: number = UBOGlobal.TIME_OFFSET + 4; diff --git a/index.js b/index.js index 31c44b1770..f301a466cc 100644 --- a/index.js +++ b/index.js @@ -41,5 +41,6 @@ export * from './cocos/components'; export * from './cocos/animation'; export * from './cocos/3d'; export * from './cocos/gfx'; +export * from './cocos/pipeline'; // export default cc; From 4d30e1b0731b28cbda629e871a41e21180ba7919 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 15 Jan 2019 11:31:00 +0800 Subject: [PATCH 133/267] fix build --- cocos/assets/render-texture.ts | 2 +- cocos/pipeline/forward/forward-pipeline.ts | 3 ++- cocos/renderer/core/effect.ts | 2 +- cocos/renderer/core/pass.ts | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts index 30e1ba5699..a2e032753a 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/assets/render-texture.ts @@ -4,7 +4,7 @@ import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } fro import { GFXFramebuffer } from '../gfx/framebuffer'; import { GFXTexture } from '../gfx/texture'; import { GFXTextureView } from '../gfx/texture-view'; -import { RenderPassStage } from '../pipeline/render-pipeline'; +import { RenderPassStage } from '../pipeline/define'; import ImageAsset from './image-asset'; import Texture2D from './texture-2d'; diff --git a/cocos/pipeline/forward/forward-pipeline.ts b/cocos/pipeline/forward/forward-pipeline.ts index 02a90df558..af8351d9a4 100644 --- a/cocos/pipeline/forward/forward-pipeline.ts +++ b/cocos/pipeline/forward/forward-pipeline.ts @@ -1,7 +1,8 @@ import { Root } from '../../core/root'; import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; import { GFXRenderPass } from '../../gfx/render-pass'; -import { RenderPassStage, RenderPipeline, UBOGlobal } from '../render-pipeline'; +import { RenderPassStage } from '../define'; +import { RenderPipeline, UBOGlobal } from '../render-pipeline'; import { ForwardFlow } from './forward-flow'; export enum ForwardFlowPriority { diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 00e88c5f9c..635142d11c 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -4,7 +4,7 @@ import { EffectAsset, IShaderInfo } from '../../3d/assets/effect-asset'; import { CCObject } from '../../core/data'; import { Color, Mat4, Vec2, Vec3, Vec4 } from '../../core/value-types'; import { GFXType } from '../../gfx/define'; -import { RenderPassStage } from '../../pipeline/render-pipeline'; +import { RenderPassStage } from '../../pipeline/define'; import Texture2D from '../gfx/texture-2d'; import TextureCube from '../gfx/texture-cube'; import { IPassInfoFull, Pass } from './pass'; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 714b405836..50ba99dc85 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -13,7 +13,8 @@ import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; -import { RenderPassStage, UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; +import { RenderPassStage } from '../../pipeline/define'; +import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; export interface IPassInfoFull extends IPassInfo { // generated part From 17610f3e130380ff6011d6574b140d99240362fb Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 15 Jan 2019 11:49:36 +0800 Subject: [PATCH 134/267] add GUI module --- cocos/core/root.ts | 12 ++++++++++-- cocos/renderer/gui/gui.ts | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 cocos/renderer/gui/gui.ts diff --git a/cocos/core/root.ts b/cocos/core/root.ts index f5170420a8..12d17b31b0 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -4,6 +4,7 @@ import { ForwardPipeline } from '../pipeline/forward/forward-pipeline'; import { RenderPipeline } from '../pipeline/render-pipeline'; import { IRenderViewInfo, RenderView } from '../pipeline/render-view'; import { IRenderSceneInfo, RenderScene } from '../renderer/scene/render-scene'; +import { GUI } from '../renderer/gui/gui'; export let _createSceneFun; export let _createViewFun; @@ -29,8 +30,12 @@ export class Root { return this._windows; } - public get pipeline (): RenderPipeline | null { - return this._pipeline; + public get pipeline (): RenderPipeline { + return this._pipeline as RenderPipeline; + } + + public get gui (): GUI { + return this._gui as GUI; } public get scenes (): RenderScene[] { @@ -52,6 +57,7 @@ export class Root { private _windows: GFXWindow[] = []; private _mainWindow: GFXWindow | null = null; private _pipeline: RenderPipeline | null = null; + private _gui: GUI | null = null; private _scenes: RenderScene[] = []; private _views: RenderView[] = []; private _frameTime: number = 0; @@ -78,6 +84,8 @@ export class Root { this._pipeline = pipeline; + this._gui = new GUI(this); + return true; } diff --git a/cocos/renderer/gui/gui.ts b/cocos/renderer/gui/gui.ts new file mode 100644 index 0000000000..0a1c6843f6 --- /dev/null +++ b/cocos/renderer/gui/gui.ts @@ -0,0 +1,17 @@ +import { Root } from '../../core/root'; + +export class GUI { + + public get root (): Root { + return this._root; + } + + private _root: Root; + + constructor (root: Root) { + this._root = root; + } + + public frameMove (deltaTime: number) { + } +} From 12918875be0f5358f78b4e0f5355e5666e131a44 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 15 Jan 2019 14:38:10 +0800 Subject: [PATCH 135/267] update builtin effects --- cocos/3d/assets/mesh.ts | 6 ++-- cocos/3d/builtin/effects.js | 69 +++---------------------------------- cocos/3d/misc/utils.ts | 2 +- playground/simple.html | 33 ++++++++++-------- 4 files changed, 25 insertions(+), 85 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index c2ad0ce406..83725feeff 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -23,12 +23,10 @@ THE SOFTWARE. ****************************************************************************/ -// @ts-check -import { _decorator } from '../../core/data'; -import { ccenum } from '../../core/value-types/enum'; -const { ccclass, property } = _decorator; import { Asset } from '../../assets/asset'; +import { ccclass, property } from '../../core/data/class-decorator'; import { Vec3 } from '../../core/value-types'; +import { ccenum } from '../../core/value-types/enum'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 3329793c89..79e129833b 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,51 +1,11 @@ export default [ - { - "name": "test", - "techniques": [{"queue": 0, "lod": 500, "passes": [{"stage": 100, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}], "priority": 0}], - "properties": {"u_color": {"type": 16, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": null}}, - "shaders": [ - { - "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", - "vert": ` - attribute vec3 a_position; - attribute vec2 a_texCoord; - uniform mat4 cc_matWorld; - varying vec2 v_texCoord; - void main() { - gl_Position = cc_matWorld*vec4(a_position, 1.0); - v_texCoord = a_texCoord; - } -`, - "frag": ` - varying vec2 v_texCoord; - uniform vec4 u_color; - uniform sampler2D u_sampler; - void main() { - - gl_FragColor = texture2D(u_sampler, v_texCoord); - gl_FragColor.r = u_color.r; - } -`, - "defines": [], - "blocks": [ - {"name": "Constants", "size": 16, "defines": [], "binding": 0, "members": [ - {"name": "u_color", "type": 16, "count": 1, "size": 16} - ]} - ], - "samplers": [ - {"name": "u_sampler", "type": 29, "count": 1, "defines": [], "binding": 1} - ], - "dependencies": {} - } - ] - }, { "name": "builtin-effect-unlit", - "techniques": [{"queue": "opaque", "lod": 100, "passes": [{"properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": "grey"}}, "program": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c"}]}], + "techniques": [{"queue": "opaque", "lod": 100, "passes": [{"properties": {"color": {"type": 17, "value": [1, 1, 1, 1]}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "mainTexture": {"type": 29, "value": "grey"}}, "program": "185ba10e9dc3fd42752e6035d32ff7842c9e0e3cda549999b7ef5f68"}]}], "shaders": [ { - "name": "e238b675dacba30ad29961fac06cb18d8c771e16d4fb0f9662acbe3c", - "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_texCoord1;\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;\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_texCoord1 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "name": "185ba10e9dc3fd42752e6035d32ff7842c9e0e3cda549999b7ef5f68", + "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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;\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": []}, @@ -69,27 +29,6 @@ export default [ } ] }, - { - "name": "test", - "techniques": [{"queue": "opaque", "lod": 500, "passes": [{"stage": 100, "properties": {"u_color": {"type": 17, "value": [1, 1, 1, 1]}, "u_sampler": {"type": 29, "value": "grey"}}, "program": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574"}]}], - "shaders": [ - { - "name": "f4c45e6cc7794309d86202e6ec9036a3871fd1ec167a9e02eb1e1574", - "vert": "\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n varying vec2 v_texCoord;\n void main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_texCoord;\n }\n", - "frag": "\n varying vec2 v_texCoord;\n uniform vec4 u_color;\n uniform sampler2D u_sampler;\n void main() {\n \n gl_FragColor = texture2D(u_sampler, v_texCoord);\n gl_FragColor.r = u_color.r;\n }\n", - "defines": [], - "blocks": [ - {"name": "Constants", "size": 16, "defines": [], "binding": 0, "members": [ - {"name": "u_color", "type": 16, "count": 1, "size": 16} - ]} - ], - "samplers": [ - {"name": "u_sampler", "type": 29, "count": 1, "defines": [], "binding": 1} - ], - "dependencies": {} - } - ] - }, { "name": "builtin-effect-skybox", "techniques": [{"queue": "opaque-1000", "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": false, "depthWrite": false}, "properties": {"cubeMap": {"type": 32, "value": "greyCube"}}, "program": "d9cd35729516d899db5cd6b6ecf025e61a484094405a391a3056591d"}]}], @@ -125,5 +64,5 @@ export default [ "dependencies": {} } ] - }, + } ]; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 8279f7c0d8..582c39b5e1 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -1,4 +1,4 @@ -import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define'; +import { GFXAttributeName } from '../../gfx/define'; export { default as find } from '../../scene-graph/find'; import Texture2D from '../../assets/texture-2d'; import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; diff --git a/playground/simple.html b/playground/simple.html index 62dd098689..b85312a16e 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -23,40 +23,44 @@ - + + + + + + + From 3568f1c4e0cba15b5b9a930955cfb3e8991e71a6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 10:06:32 +0800 Subject: [PATCH 184/267] optimize uniform buffer update --- cocos/core/memop/cached-array.ts | 48 ++-- cocos/gfx/buffer.ts | 8 + cocos/gfx/webgl/webgl-buffer.ts | 11 +- cocos/gfx/webgl/webgl-commands.ts | 332 ++++++++++++++------------- cocos/gfx/webgl/webgl-device.ts | 12 +- cocos/gfx/webgl/webgl-gpu-objects.ts | 47 ++-- 6 files changed, 254 insertions(+), 204 deletions(-) diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index f893605999..de18948305 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -3,11 +3,11 @@ export class CachedArray { public array: T[]; public length: number = 0; private _compareFn; - private _cache: Array; + private _capacity: number = 0; constructor (length: number, compareFn?: (a: T, b: T) => number) { this.array = new Array(length); - this._cache = this.array; + this._capacity = length; this.length = 0; if (compareFn !== undefined) { @@ -18,22 +18,24 @@ export class CachedArray { } public reserve (length: number) { - if (length > this.array.length) { + if (length > this._capacity) { + const temp = this.array; this.array = new Array(length); - for (let i = 0; i < this._cache.length; ++i) { - this.array[i] = this._cache[i] as T; + for (let i = 0; i < this._capacity; ++i) { + this.array[i] = temp[i]; } - this._cache = this.array; + this._capacity = length; } } public push (item: T) { - if (this.length > this.array.length) { + if (this.length > this._capacity) { + const temp = this.array; this.array = new Array(this.length); - for (let i = 0; i < this._cache.length; ++i) { - this.array[i] = this._cache[i] as T; + for (let i = 0; i < this._capacity; ++i) { + this.array[i] = temp[i]; } - this._cache = this.array; + this._capacity = length; } this.array[this.length++] = item; @@ -52,35 +54,37 @@ export class CachedArray { } public sort () { - this._cache.fill(undefined, this.length, this.array.length); - this._cache.sort(this._compareFn); + this.array.length = this.length; + this.array.sort(this._compareFn); } public concat (array: CachedArray) { - if (array.length + this.length > this._cache.length) { + if (array.length + this.length > this._capacity) { + const temp = this.array; this.array = new Array(array.length + this.length); - for (let i = 0; i < this._cache.length; ++i) { - this.array[i] = this._cache[i] as T; + for (let i = 0; i < this._capacity; ++i) { + this.array[i] = temp[i]; } - this._cache = this.array; + this._capacity = this.array.length; } for (let i = 0; i < array.length; ++i) { - this._cache[this.length++] = array.array[i]; + this.array[this.length++] = array.array[i]; } } public append (array: T[]) { - if (array.length + this.length > this._cache.length) { + if (array.length + this.length > this._capacity) { + const temp = this.array; this.array = new Array(array.length + this.length); - for (let i = 0; i < this._cache.length; ++i) { - this.array[i] = this._cache[i] as T; + for (let i = 0; i < this._capacity; ++i) { + this.array[i] = temp[i]; } - this._cache = this.array; + this._capacity = this.array.length; } for (const item of array) { - this._cache[this.length++] = item; + this.array[this.length++] = item; } } } diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 75b2671876..2315a74ef5 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -5,9 +5,16 @@ import { GFXMemoryUsageBit, GFXObject, GFXObjectType, + GFXType, } from './define'; import { GFXDevice } from './device'; +export interface IGFXUniformInfo { + name: string; + type: GFXType; + count: number; +} + export interface IGFXDrawInfo { vertexCount: number; firstVertex: number; @@ -61,6 +68,7 @@ export abstract class GFXBuffer extends GFXObject { protected _size: number = 0; protected _stride: number = 1; protected _buffer: GFXBufferSource | null = null; + protected _uniforms: GFXBufferSource | null = null; constructor (device: GFXDevice) { super(GFXObjectType.BUFFER); diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index 8b089963c8..f7cb4595b3 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -1,5 +1,5 @@ import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer'; -import { GFXBufferUsageBit, GFXMemoryUsageBit, GFXStatus } from '../define'; +import { GFXBufferUsageBit, GFXGetTypeSize, GFXMemoryUsageBit, GFXStatus } from '../define'; import { GFXDevice } from '../device'; import { WebGLGFXDevice } from './webgl-device'; import { WebGLGPUBuffer } from './webgl-gpu-objects'; @@ -11,7 +11,7 @@ export class WebGLGFXBuffer extends GFXBuffer { } public get gpuBuffer (): WebGLGPUBuffer { - return this._gpuBuffer as WebGLGPUBuffer; + return this._gpuBuffer!; } private _gpuBuffer: WebGLGPUBuffer | null = null; @@ -32,11 +32,10 @@ export class WebGLGFXBuffer extends GFXBuffer { this._stride = Math.max(this._stride, 1); if (this._memUsage & GFXMemoryUsageBit.HOST) { - - if (!(this._usage & GFXBufferUsageBit.INDIRECT)) { - this._buffer = new ArrayBuffer(this._size); - } else { + if (this._usage & GFXBufferUsageBit.INDIRECT) { this._buffer = { drawInfos: [] }; + } else { + this._buffer = new ArrayBuffer(this._size); } } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 75223bab2c..4acf9b9cf2 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -7,11 +7,13 @@ import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, 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, - WebGLGPUTexture, WebGLGPUUniform, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; +import { IWebGLGPUUniform, WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, + WebGLGPUFramebuffer, WebGLGPUInput, WebGLGPUInputAssembler, WebGLGPUPipelineState, + WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; import { IWebGLTexUnit } from './webgl-state-cache'; +const _uniformValues = new Array(1024 * 4); + // tslint:disable: max-line-length function CmpF32NotEuqal (a: number, b: number): boolean { @@ -541,7 +543,7 @@ export function WebGLCmdFuncCreateBuffer (device: WebGLGFXDevice, gpuBuffer: Web gpuBuffer.glTarget = WebGLRenderingContext.NONE; if (gpuBuffer.buffer) { - gpuBuffer.viewF32 = new Float32Array(gpuBuffer.buffer as ArrayBuffer); + gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer as ArrayBuffer); } } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { gpuBuffer.glTarget = WebGLRenderingContext.NONE; @@ -565,11 +567,10 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: We export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { - if (gpuBuffer.viewF32 && buffer) { - gpuBuffer.viewF32.set(new Float32Array(buffer as ArrayBuffer, 0, size / 4), offset); - } + const buff = buffer as ArrayBuffer; + gpuBuffer.vf32!.set(new Float32Array(buff.slice(0, size)), offset); } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { - gpuBuffer.buffer = buffer; + gpuBuffer.indirects = (buffer as IGFXIndirectBuffer).drawInfos; } else { const buff = buffer as ArrayBuffer; const gl = device.gl; @@ -584,7 +585,7 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: Web if (size === buff.byteLength) { gl.bufferSubData(gpuBuffer.glTarget, offset, buff); } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buff, 0, size)); + gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); } break; @@ -598,7 +599,7 @@ export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: Web if (size === buff.byteLength) { gl.bufferSubData(gpuBuffer.glTarget, offset, buff); } else { - gl.bufferSubData(gpuBuffer.glTarget, offset, new Uint8Array(buff, 0, size)); + gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size)); } break; @@ -896,7 +897,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web binding: block.binding, name: block.name, size: 0, - glUniforms: new Array(block.members.length), + glUniforms: new Array(block.members.length), glActiveUniforms: [], isUniformPackage: true, buffer: null, @@ -909,6 +910,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web const glType = GFXTypeToWebGLType(uniform.type); const stride = WebGLGetTypeSize(glType); const size = stride * uniform.count; + const begin = glBlock.size / 4; + // const count = size / 4; glBlock.glUniforms[u] = { binding: -1, @@ -921,13 +924,36 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web glType, glLoc: -1, - view: null, + vi32: null, + vf32: null, + begin, }; glBlock.size += size; } glBlock.buffer = new ArrayBuffer(glBlock.size); + + for (const glUniform of glBlock.glUniforms) { + switch (glUniform.glType) { + case gl.BOOL: + case gl.BOOL_VEC2: + case gl.BOOL_VEC3: + case gl.BOOL_VEC4: + case gl.INT: + case gl.INT_VEC2: + case gl.INT_VEC3: + case gl.INT_VEC4: + case gl.SAMPLER_2D: + case gl.SAMPLER_CUBE: { + glUniform.vi32 = new Int32Array(glBlock.buffer); + break; + } + default: { + glUniform.vf32 = new Float32Array(glBlock.buffer); + } + } + } } } @@ -979,29 +1005,6 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web // let varSize = stride * info.size; glUniform.glLoc = glLoc; - - // let count = glUniform.size / 4; - // glUniform.view = new Float32Array(glBlock.buffer, glUniform.offset, count); - - switch (glUniform.glType) { - case WebGLRenderingContext.BOOL: - case WebGLRenderingContext.BOOL_VEC2: - case WebGLRenderingContext.BOOL_VEC3: - case WebGLRenderingContext.BOOL_VEC4: - case WebGLRenderingContext.INT: - case WebGLRenderingContext.INT_VEC3: - case WebGLRenderingContext.INT_VEC2: - case WebGLRenderingContext.INT_VEC4: { - const count = glUniform.size / 4; - glUniform.view = new Int32Array(glBlock.buffer as ArrayBuffer, glUniform.offset, count); - break; - } - default: { - const count = glUniform.size / 4; - glUniform.view = new Float32Array(glBlock.buffer as ArrayBuffer, glUniform.offset, count); - } - } - glBlock.glActiveUniforms.push(glUniform); break; @@ -1533,21 +1536,21 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } - if (glBlock && gpuBinding.gpuBuffer.viewF32) { - const vf32 = gpuBinding.gpuBuffer.viewF32; - + if (glBlock && gpuBinding.gpuBuffer.vf32) { for (const glUniform of glBlock.glActiveUniforms) { - let offset = glUniform.offset / 4; - switch (glUniform.glType) { case WebGLRenderingContext.BOOL: case WebGLRenderingContext.INT: { - const view = glUniform.view as Int32Array; - for (let m = 0; m < glUniform.count; ++m, ++offset) { - if (vf32[offset] !== view[m]) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + glUniform.count)); - gl.uniform1iv(glUniform.glLoc, view); + for (let u = 0; u < glUniform.count; ++u) { + if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u] !== glUniform.vi32![u]) { + + _uniformValues.length = glUniform.count; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vi32!.set(_uniformValues); + gl.uniform1iv(glUniform.glLoc, _uniformValues); break; } } @@ -1555,15 +1558,17 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { - const view = glUniform.view as Int32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 2) { - const idx = 2 * m; - if (vf32[offset] !== view[idx] || - vf32[offset + 1] !== view[idx + 1]) { + for (let u = 0; u < glUniform.count; ++u) { + if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2] !== glUniform.vi32![u * 2] || + gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2 + 1] !== glUniform.vi32![u * 2 + 1]) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); - gl.uniform2iv(glUniform.glLoc, view); + _uniformValues.length = glUniform.count * 2; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vi32!.set(_uniformValues); + gl.uniform2iv(glUniform.glLoc, _uniformValues); break; } } @@ -1571,16 +1576,18 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { - const view = glUniform.view as Int32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 3) { - const idx = 3 * m; - if (vf32[offset] !== view[idx] || - vf32[offset + 1] !== view[idx + 1] || - vf32[offset + 2] !== view[idx + 2]) { + for (let u = 0; u < glUniform.count; ++u) { + if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3] !== glUniform.vi32![u * 3] || + gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 1] !== glUniform.vi32![u * 3 + 1] || + gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 2] !== glUniform.vi32![u * 3 + 2]) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); - gl.uniform3iv(glUniform.glLoc, view); + _uniformValues.length = glUniform.count * 3; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vi32!.set(_uniformValues); + gl.uniform3iv(glUniform.glLoc, _uniformValues); break; } } @@ -1588,149 +1595,163 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.BOOL_VEC4: case WebGLRenderingContext.INT_VEC4: { - const view = glUniform.view as Int32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 4) { - const idx = 4 * m; - if (vf32[offset] !== view[idx] || - vf32[offset + 1] !== view[idx + 1] || - vf32[offset + 2] !== view[idx + 2] || - vf32[offset + 3] !== view[idx + 3]) { + for (let u = 0; u < glUniform.count; ++u) { + if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4] !== glUniform.vi32![u * 4] || + gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 1] !== glUniform.vi32![u * 4 + 1] || + gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 2] !== glUniform.vi32![u * 4 + 2] || + gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 3] !== glUniform.vi32![u * 4 + 3]) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniform4iv(glUniform.glLoc, view); + _uniformValues.length = glUniform.count * 4; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vi32!.set(_uniformValues); + gl.uniform4iv(glUniform.glLoc, _uniformValues); break; } } break; } case WebGLRenderingContext.FLOAT: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, ++offset) { + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u], glUniform.vf32![u])) { - if (CmpF32NotEuqal(vf32[offset], view[m])) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + glUniform.count)); - gl.uniform1fv(glUniform.glLoc, view); + _uniformValues.length = glUniform.count; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vf32!.set(_uniformValues); + gl.uniform1fv(glUniform.glLoc, glUniform.vf32!); break; } } break; } case WebGLRenderingContext.FLOAT_VEC2: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 2) { - const idx = 2 * m; - if (CmpF32NotEuqal(vf32[offset], view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], view[idx + 1])) { + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2], glUniform.vf32![u * 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2 + 1], glUniform.vf32![u * 2 + 1])) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 2 * glUniform.count)); - gl.uniform2fv(glUniform.glLoc, view); + _uniformValues.length = glUniform.count * 2; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vf32!.set(_uniformValues); + gl.uniform2fv(glUniform.glLoc, _uniformValues); break; } } break; } case WebGLRenderingContext.FLOAT_VEC3: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 3) { - const idx = 3 * m; - if (CmpF32NotEuqal(vf32[offset], view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], view[idx + 2])) { + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3], glUniform.vf32![u * 3]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 1], glUniform.vf32![u * 3 + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 2], glUniform.vf32![u * 3 + 2])) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 3 * glUniform.count)); - gl.uniform3fv(glUniform.glLoc, view); + _uniformValues.length = glUniform.count * 3; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vf32!.set(_uniformValues); + gl.uniform3fv(glUniform.glLoc, _uniformValues); break; } - } break; } case WebGLRenderingContext.FLOAT_VEC4: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 4) { - const idx = 4 * m; + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4], glUniform.vf32![u * 4]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 1], glUniform.vf32![u * 4 + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 2], glUniform.vf32![u * 4 + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 3], glUniform.vf32![u * 4 + 3])) { - if (CmpF32NotEuqal(vf32[offset], view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], view[idx + 3])) { + _uniformValues.length = glUniform.count * 4; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniform4fv(glUniform.glLoc, view); + glUniform.vf32!.set(_uniformValues); + gl.uniform4fv(glUniform.glLoc, _uniformValues); break; } } break; } case WebGLRenderingContext.FLOAT_MAT2: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 4) { - const idx = 4 * m; - if (CmpF32NotEuqal(vf32[offset], view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], view[idx + 3])) { + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4], glUniform.vf32![u * 4]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 1], glUniform.vf32![u * 4 + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 2], glUniform.vf32![u * 4 + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 3], glUniform.vf32![u * 4 + 3])) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 4 * glUniform.count)); - gl.uniformMatrix2fv(glUniform.glLoc, false, view); + _uniformValues.length = glUniform.count * 4; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vf32!.set(_uniformValues); + gl.uniformMatrix2fv(glUniform.glLoc, false, _uniformValues); break; } } break; } case WebGLRenderingContext.FLOAT_MAT3: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 9) { - const idx = 9 * m; - if (CmpF32NotEuqal(vf32[offset], view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], view[idx + 3]) || - CmpF32NotEuqal(vf32[offset + 4], view[idx + 4]) || - CmpF32NotEuqal(vf32[offset + 5], view[idx + 5]) || - CmpF32NotEuqal(vf32[offset + 6], view[idx + 6]) || - CmpF32NotEuqal(vf32[offset + 7], view[idx + 7]) || - CmpF32NotEuqal(vf32[offset + 8], view[idx + 8])) { + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9], glUniform.vf32![u * 9]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 1], glUniform.vf32![u * 9 + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 2], glUniform.vf32![u * 9 + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 3], glUniform.vf32![u * 9 + 3]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 4], glUniform.vf32![u * 9 + 4]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 5], glUniform.vf32![u * 9 + 5]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 6], glUniform.vf32![u * 9 + 6]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 7], glUniform.vf32![u * 9 + 7]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 8], glUniform.vf32![u * 9 + 8])) { - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 9 * glUniform.count)); - gl.uniformMatrix3fv(glUniform.glLoc, false, view); + _uniformValues.length = glUniform.count * 9; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } + + glUniform.vf32!.set(_uniformValues); + gl.uniformMatrix3fv(glUniform.glLoc, false, _uniformValues); break; } } break; } case WebGLRenderingContext.FLOAT_MAT4: { - const view = glUniform.view as Float32Array; - for (let m = 0; m < glUniform.count; ++m, offset += 16) { - const idx = 16 * m; + for (let u = 0; u < glUniform.count; ++u) { + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16], glUniform.vf32![u * 16]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 1], glUniform.vf32![u * 16 + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 2], glUniform.vf32![u * 16 + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 3], glUniform.vf32![u * 16 + 3]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 4], glUniform.vf32![u * 16 + 4]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 5], glUniform.vf32![u * 16 + 5]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 6], glUniform.vf32![u * 16 + 6]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 7], glUniform.vf32![u * 16 + 7]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 8], glUniform.vf32![u * 16 + 8]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 9], glUniform.vf32![u * 16 + 9]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 10], glUniform.vf32![u * 16 + 10]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 11], glUniform.vf32![u * 16 + 11]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 12], glUniform.vf32![u * 16 + 12]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 13], glUniform.vf32![u * 16 + 13]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 14], glUniform.vf32![u * 16 + 14]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 15], glUniform.vf32![u * 16 + 15])) { - if (CmpF32NotEuqal(vf32[offset], view[idx]) || - CmpF32NotEuqal(vf32[offset + 1], view[idx + 1]) || - CmpF32NotEuqal(vf32[offset + 2], view[idx + 2]) || - CmpF32NotEuqal(vf32[offset + 3], view[idx + 3]) || - CmpF32NotEuqal(vf32[offset + 4], view[idx + 4]) || - CmpF32NotEuqal(vf32[offset + 5], view[idx + 5]) || - CmpF32NotEuqal(vf32[offset + 6], view[idx + 6]) || - CmpF32NotEuqal(vf32[offset + 7], view[idx + 7]) || - CmpF32NotEuqal(vf32[offset + 8], view[idx + 8]) || - CmpF32NotEuqal(vf32[offset + 9], view[idx + 9]) || - CmpF32NotEuqal(vf32[offset + 10], view[idx + 10]) || - CmpF32NotEuqal(vf32[offset + 11], view[idx + 11]) || - CmpF32NotEuqal(vf32[offset + 12], view[idx + 12]) || - CmpF32NotEuqal(vf32[offset + 13], view[idx + 13]) || - CmpF32NotEuqal(vf32[offset + 14], view[idx + 14]) || - CmpF32NotEuqal(vf32[offset + 15], view[idx + 15])) { + _uniformValues.length = glUniform.count * 16; + for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { + _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + } - const begin = glUniform.offset / 4; - view.set(vf32.subarray(begin, begin + 16 * glUniform.count)); - gl.uniformMatrix4fv(glUniform.glLoc, false, view); + glUniform.vf32!.set(_uniformValues); + gl.uniformMatrix4fv(glUniform.glLoc, false, _uniformValues); break; } } @@ -2059,8 +2080,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } } else { if (gpuInputAssembler.gpuIndirectBuffer) { - const drawInfos = (gpuInputAssembler.gpuIndirectBuffer.buffer as IGFXIndirectBuffer).drawInfos; - for (const drawInfo of drawInfos) { + for (const drawInfo of gpuInputAssembler.gpuIndirectBuffer.indirects) { const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; if (gpuBuffer && drawInfo.indexCount > 0) { const offset = drawInfo.firstIndex * gpuBuffer.stride; diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index ca1e1c9978..3ee0573aba 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,5 +1,5 @@ import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; -import { GFXBuffer, GFXBufferSource, IGFXBufferInfo } from '../buffer'; +import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../command-buffer'; import { @@ -566,13 +566,19 @@ export class WebGLGFXDevice extends GFXDevice { size: info.size, stride: info.stride ? info.stride : 1, buffer: null, - viewF32: null, + vf32: null, + uniforms: [], + indirects: [], glTarget: 0, glBuffer: 0, }; if (buffer) { - gpuBuffer.buffer = buffer; + if (info.usage & GFXBufferUsageBit.INDIRECT) { + gpuBuffer.indirects = (buffer as IGFXIndirectBuffer).drawInfos; + } else { + gpuBuffer.buffer = buffer as ArrayBuffer; + } } // let isUBOSimulate = (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index e66513ba80..f0c338c69c 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -1,4 +1,4 @@ -import { GFXBufferSource } from '../buffer'; +import { IGFXDrawInfo } from '../buffer'; import { GFXBindingType, GFXBufferUsage, @@ -44,6 +44,15 @@ export class WebGLGPUObject { } } +export interface IWebGLGPUUniformInfo { + name: string; + type: GFXType; + count: number; + offset: number; + view: Float32Array | Int32Array; + isDirty: boolean; +} + export class WebGLGPUBuffer extends WebGLGPUObject { public usage: GFXBufferUsage = GFXBufferUsageBit.NONE; public memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; @@ -52,8 +61,10 @@ export class WebGLGPUBuffer extends WebGLGPUObject { public glTarget: GLenum = 0; public glBuffer: WebGLBuffer = 0; - public buffer: GFXBufferSource | null = null; - public viewF32: Float32Array | null = null; + public buffer: ArrayBuffer | null = null; + public vf32: Float32Array | null = null; + public uniforms: IWebGLGPUUniformInfo[] = []; + public indirects: IGFXDrawInfo[] = []; constructor () { super(WebGLGPUObjectType.BUFFER); @@ -148,26 +159,28 @@ export class WebGLGPUInput { public glLoc: GLint = 0; } -export class WebGLGPUUniform { - public binding: number = -1; - public name: string = ''; - public type: GFXType = GFXType.UNKNOWN; - public stride: number = 0; - public count: number = 0; - public size: number = 0; - public offset: number = 0; +export interface IWebGLGPUUniform { + binding: number; + name: string; + type: GFXType; + stride: number; + count: number; + size: number; + offset: number; - public glType: GLenum = 0; - public glLoc: WebGLUniformLocation = -1; - public view: Float32Array | Int32Array | null = null; + glType: GLenum; + glLoc: WebGLUniformLocation; + vi32: Int32Array | null; + vf32: Float32Array | null; + begin: number; } export class WebGLGPUUniformBlock { public binding: number = -1; public name: string = ''; public size: number = 0; - public glUniforms: WebGLGPUUniform[] = []; - public glActiveUniforms: WebGLGPUUniform[] = []; + public glUniforms: IWebGLGPUUniform[] = []; + public glActiveUniforms: IWebGLGPUUniform[] = []; public isUniformPackage: boolean = false; // Is a single uniform package? public buffer: ArrayBuffer | null = null; // for cache @@ -198,7 +211,7 @@ export class WebGLGPUShader extends WebGLGPUObject { public gpuStages: WebGLGPUShaderStage[] = []; public glProgram: WebGLProgram = 0; public glInputs: WebGLGPUInput[] = []; - public glUniforms: WebGLGPUUniform[] = []; + public glUniforms: IWebGLGPUUniform[] = []; public glBlocks: WebGLGPUUniformBlock[] = []; public glSamplers: WebGLGPUUniformSampler[] = []; From c919f5e30fddfe5152c5863e1b544e9f4aa98c56 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 21 Jan 2019 13:38:20 +0800 Subject: [PATCH 185/267] fix recycle-pool --- .../{recycle-pool.js => recycle-pool.ts} | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) rename cocos/3d/memop/{recycle-pool.js => recycle-pool.ts} (55%) diff --git a/cocos/3d/memop/recycle-pool.js b/cocos/3d/memop/recycle-pool.ts similarity index 55% rename from cocos/3d/memop/recycle-pool.js rename to cocos/3d/memop/recycle-pool.ts index 5c975e7d82..5d231f143e 100644 --- a/cocos/3d/memop/recycle-pool.js +++ b/cocos/3d/memop/recycle-pool.ts @@ -1,31 +1,32 @@ import sort from './timsort'; -export default class RecyclePool { - constructor(fn, size) { +export default class RecyclePool { + private _fn: () => T; + private _count = 0; + private _data: T[]; + + constructor (fn: () => T, size: number) { this._fn = fn; - this._count = 0; this._data = new Array(size); - this._objIdx = {}; for (let i = 0; i < size; ++i) { this._data[i] = fn(); - this._objIdx[this._data[i]] = i; } } - get length() { + get length () { return this._count; } - get data() { + get data () { return this._data; } - reset() { + public reset () { this._count = 0; } - resize(size) { + public resize (size: number) { if (size > this._data.length) { for (let i = this._data.length; i < size; ++i) { this._data[i] = this._fn(); @@ -33,7 +34,7 @@ export default class RecyclePool { } } - add() { + public add () { if (this._count >= this._data.length) { this.resize(this._data.length * 2); } @@ -41,25 +42,26 @@ export default class RecyclePool { return this._data[this._count++]; } - removeAt(idx) { + public removeAt (idx: number) { if (idx >= this._count) { return; } - let last = this._count - 1; - let tmp = this._data[idx]; + const last = this._count - 1; + const tmp = this._data[idx]; this._data[idx] = this._data[last]; this._data[last] = tmp; - this._objIdx[this._data[idx]] = idx; - this._objIdx[this._data[last]] = last; this._count -= 1; } - remove(obj) { - this.removeAt(this._objIdx[obj]); + public remove (element: T) { + const idx = this.data.indexOf(element); + if (idx >= 0) { + this.removeAt(idx); + } } - sort(cmp) { - return sort(this._data, 0, this._count, cmp); + public sort (compare: (a: T, b: T) => number) { + return sort(this._data, 0, this._count, compare); } } From b4561219057e1ad6cbbb88b32586157eba454117 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Mon, 21 Jan 2019 16:14:52 +0800 Subject: [PATCH 186/267] adapt particle submodel --- cocos/3d/assets/mesh.ts | 1 + .../particle/particle-system-component.js | 2 +- .../renderer/particle-system-renderer.ts | 315 +++++++++--------- cocos/3d/framework/renderable-component.ts | 4 +- cocos/3d/memop/recycle-pool.ts | 12 +- cocos/gfx/webgl/webgl-commands.ts | 2 +- cocos/renderer/models/particle-batch-model.ts | 45 ++- cocos/renderer/scene/model.ts | 41 ++- cocos/renderer/scene/submodel.ts | 36 +- 9 files changed, 253 insertions(+), 205 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 6b463faeed..553632a416 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -293,6 +293,7 @@ export interface IGeometricInfo { export interface IRenderingSubmesh { vertexBuffers: GFXBuffer[]; indexBuffer: GFXBuffer; + indirectBuffer?: GFXBuffer; attributes: IGFXInputAttribute[]; primitiveMode: GFXPrimitiveMode; geometricInfo?: IGeometricInfo; diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.js index ef0f1ed6db..39e32fc75a 100644 --- a/cocos/3d/framework/particle/particle-system-component.js +++ b/cocos/3d/framework/particle/particle-system-component.js @@ -368,7 +368,7 @@ export default class ParticleSystemComponent extends Component { // } // } - this._particles.remove(i); + this._particles.removeAt(i); --i; continue; } diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 0a312b1d41..b162fcc6ff 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -1,28 +1,28 @@ +import { ccclass, executeInEditMode, property } from '../../../../core/data/class-decorator'; +import { Enum, Vec2 } from '../../../../core/value-types'; +import { mat4, vec2, vec3, vec4 } from '../../../../core/vmath'; +import { GFXAttributeName, GFXFormat } from '../../../../gfx/define'; +import { IGFXInputAttribute } from '../../../../gfx/input-assembler'; import * as renderer from '../../../../renderer'; -import { vec3, vec4, vec2, mat4 } from '../../../../core/vmath'; import gfx from '../../../../renderer/gfx'; +import ParticleBatchModel from '../../../../renderer/models/particle-batch-model'; import { Material } from '../../../assets/material'; import { RecyclePool } from '../../../memop'; import Particle from '../particle'; import { RenderableComponent } from '../../renderable-component'; -import { Enum, Vec2 } from '../../../../core/value-types'; -import { property, ccclass, executeInEditMode } from '../../../../core/data/class-decorator'; import { Space } from '../particle-general-function'; -import { GFXAttributeName, GFXFormat } from '../../../../gfx/define'; -import ParticleBatchModel from '../../../../renderer/models/particle-batch-model'; -import { IGFXInputAttribute } from '../../../../gfx/input-assembler'; // import ParticleSystemComponent from '../particle-system-component'; -let _tempAttribUV: vec3 = vec3.create(); -let _tempAttribUV0: vec2 = vec2.create(); -let _tempAttribColor: vec4 = vec4.create(); -let _tempWorldTrans: mat4 = mat4.create(); +const _tempAttribUV: vec3 = vec3.create(); +const _tempAttribUV0: vec2 = vec2.create(); +const _tempAttribColor: vec4 = vec4.create(); +const _tempWorldTrans: mat4 = mat4.create(); -let _uvs = [ +const _uvs = [ 0, 0, // bottom-left 1, 0, // bottom-right 0, 1, // top-left - 1, 1 // top-right + 1, 1, // top-right ]; const RenderMode = Enum({ @@ -30,32 +30,27 @@ const RenderMode = Enum({ StrecthedBillboard: 1, HorizontalBillboard: 2, VerticalBillboard: 3, - Mesh: 4 + Mesh: 4, }); -let USE_WORLD_SPACE = 'USE_WORLD_SPACE'; -let USE_BILLBOARD = 'USE_BILLBOARD'; -let USE_STRETCHED_BILLBOARD = 'USE_STRETCHED_BILLBOARD'; -let USE_HORIZONTAL_BILLBOARD = 'USE_HORIZONTAL_BILLBOARD'; -let USE_VERTICAL_BILLBOARD = 'USE_VERTICAL_BILLBOARD'; +const USE_WORLD_SPACE = 'USE_WORLD_SPACE'; +const USE_BILLBOARD = 'USE_BILLBOARD'; +const USE_STRETCHED_BILLBOARD = 'USE_STRETCHED_BILLBOARD'; +const USE_HORIZONTAL_BILLBOARD = 'USE_HORIZONTAL_BILLBOARD'; +const USE_VERTICAL_BILLBOARD = 'USE_VERTICAL_BILLBOARD'; @ccclass('cc.ParticleSystemRenderer') @executeInEditMode export default class ParticleSystemRenderer extends RenderableComponent { @property({ - type: RenderMode + type: RenderMode, }) - private _renderMode = RenderMode.Billboard; - - @property({ - type: RenderMode - }) - public get renderMode() { + public get renderMode () { return this._renderMode; } - public set renderMode(val) { + public set renderMode (val) { if (this._renderMode === val) { return; } @@ -65,43 +60,47 @@ export default class ParticleSystemRenderer extends RenderableComponent { } @property - private _velocityScale = 1; - - @property - public get velocityScale() { + public get velocityScale () { return this._velocityScale; } - public set velocityScale(val) { + public set velocityScale (val) { this._velocityScale = val; this._updateMaterialParams(); this._updateModel(); } @property - private _lengthScale = 1; - - @property - public get lengthScale() { + public get lengthScale () { return this._lengthScale; } - public set lengthScale(val) { + public set lengthScale (val) { this._lengthScale = val; this._updateMaterialParams(); this._updateModel(); } + @property({ + type: RenderMode, + }) + private _renderMode = RenderMode.Billboard; + + @property + private _velocityScale = 1; + + @property + private _lengthScale = 1; + private _defines: { [index: string]: boolean }; private _model: ParticleBatchModel | null; private frameTile: Vec2; - private attrs: [any]; + private attrs: any[]; private _vertAttrs: IGFXInputAttribute[]; private particleSystem: any; private _particles: RecyclePool; - - constructor() { + constructor () { super(); this._model = null; @@ -111,18 +110,18 @@ export default class ParticleSystemRenderer extends RenderableComponent { { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, { name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RGB32F }, { name: GFXAttributeName.ATTR_TEX_COORD1, format: GFXFormat.RG32F }, - { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA8, isNormalized: true } + { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA8, isNormalized: true }, ]; this._defines = { USE_WORLD_SPACE: true, USE_BILLBOARD: true, USE_STRETCHED_BILLBOARD: false, USE_HORIZONTAL_BILLBOARD: false, - USE_VERTICAL_BILLBOARD: false - } + USE_VERTICAL_BILLBOARD: false, + }; } - onInit() { + public onInit () { this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent'); this._particles = new RecyclePool(() => { return new Particle(this); @@ -136,34 +135,138 @@ export default class ParticleSystemRenderer extends RenderableComponent { this._updateModel(); } - onEnable() { + public onEnable () { if (!this.particleSystem) { return; } if (this._model == null) { - this._model = this._getRenderScene().createModel(ParticleBatchModel); + this._model = this._getRenderScene().createModel(ParticleBatchModel) as ParticleBatchModel; this._model.setCapacity(this.particleSystem.capacity); this._model.setVertexAttributes(this._vertAttrs); this._model.node = this.node; } } - onDisable() { + public onDisable () { this._getRenderScene().destroyModel(this._model!); } - onDestroy() { + public onDestroy () { this._model!.destroy(); } - _updateMaterialParams() { + public _getFreeParticle () { + if (this._particles.length >= this.particleSystem._capacity) { + return null; + } + return this._particles.add(); + } + + public _setNewParticle (p) { + + } + + public _updateParticles (dt) { + this.node.getWorldMatrix(_tempWorldTrans); + if (this.particleSystem.velocityOvertimeModule.enable) { + this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); + } + if (this.particleSystem.forceOvertimeModule.enable) { + this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); + } + for (let i = 0; i < this._particles.length; ++i) { + const p = this._particles.data[i]; + p.remainingLifetime -= dt; + vec3.set(p.animatedVelocity, 0, 0, 0); + + if (p.remainingLifetime < 0.0) { + this._particles.removeAt(i); + --i; + continue; + } + + 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); + } + if (this.particleSystem.colorOverLifetimeModule.enable) { + this.particleSystem.colorOverLifetimeModule.animate(p); + } + if (this.particleSystem.forceOvertimeModule.enable) { + this.particleSystem.forceOvertimeModule.animate(p, dt); + } + if (this.particleSystem.velocityOvertimeModule.enable) { + this.particleSystem.velocityOvertimeModule.animate(p); + } else { + vec3.copy(p.ultimateVelocity, p.velocity); + } + if (this.particleSystem.limitVelocityOvertimeModule.enable) { + this.particleSystem.limitVelocityOvertimeModule.animate(p); + } + if (this.particleSystem.rotationOvertimeModule.enable) { + this.particleSystem.rotationOvertimeModule.animate(p, dt); + } + if (this.particleSystem.textureAnimationModule.enable) { + this.particleSystem.textureAnimationModule.animate(p); + } + vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. + } + } + + // internal function + public _updateRenderData () { + // update vertex buffer + let idx = 0; + const uploadVel = this._renderMode === RenderMode.StrecthedBillboard; + for (let i = 0; i < this._particles.length; ++i) { + const p = this._particles.data[i]; + let fi = 0; + if (this.particleSystem.textureAnimationModule.enable) { + fi = p.frameIndex; + } + idx = i * 4; + let attrNum = 0; + for (let j = 0; j < 4; ++j) { // four verts per particle. + attrNum = 0; + this.attrs[attrNum++] = p.position; + _tempAttribUV.x = _uvs[2 * j]; + _tempAttribUV.y = _uvs[2 * j + 1]; + _tempAttribUV.z = fi; + this.attrs[attrNum++] = _tempAttribUV; + _tempAttribUV0.x = p.size.x; + _tempAttribUV0.y = p.rotation.x; + this.attrs[attrNum++] = _tempAttribUV0; + this.attrs[attrNum++] = p.color._val; + + if (uploadVel) { + this.attrs[attrNum++] = p.ultimateVelocity; + } + + this._model!.addParticleVertexData(idx++, this.attrs); + } + } + + // because we use index buffer, per particle index count = 6. + this._model!.updateIA(this._particles.length * 6); + } + + public updateShaderUniform () { + + } + + public _onMaterialModified (index, material) { + this._updateMaterialParams(); + this._updateModel(); + } + + private _updateMaterialParams () { if (!this.particleSystem) { return; } if (this.particleSystem._simulationSpace === Space.World) { this._defines[USE_WORLD_SPACE] = true; } else { - this._defines[USE_WORLD_SPACE] = true; + this._defines[USE_WORLD_SPACE] = false; } if (this._renderMode === RenderMode.Billboard) { @@ -195,129 +298,25 @@ export default class ParticleSystemRenderer extends RenderableComponent { if (this.particleSystem.textureAnimationModule.enable) { this.sharedMaterial!.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); - } - else { + } else { this.sharedMaterial!.setProperty('frameTile', this.frameTile); } } - _updateModel() { + private _updateModel () { if (!this.particleSystem) { return; } - this._model!.material = this.sharedMaterial ? this.sharedMaterial : null; - if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') + this._model!.setSubModelMaterial(0, this.sharedMaterial ? this.sharedMaterial : null); + if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') { return; + } if (this._renderMode === RenderMode.StrecthedBillboard) { this._model!.enableStretchedBillboard(); } else { this._model!.disableStretchedBillboard(); } } - - _getFreeParticle() { - if (this._particles.length >= this.particleSystem._capacity) - return null; - return this._particles.add(); - } - - _setNewParticle(p) { - - } - - _updateParticles(dt) { - this.node.getWorldMatrix(_tempWorldTrans); - if (this.particleSystem.velocityOvertimeModule.enable) { - this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); - } - if (this.particleSystem.forceOvertimeModule.enable) { - this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); - } - for (let i = 0; i < this._particles.length; ++i) { - let p = this._particles.data[i]; - p.remainingLifetime -= dt; - vec3.set(p.animatedVelocity, 0, 0, 0); - - if (p.remainingLifetime < 0.0) { - this._particles.remove(i); - --i; - continue; - } - - 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); - } - if (this.particleSystem.colorOverLifetimeModule.enable) { - this.particleSystem.colorOverLifetimeModule.animate(p); - } - if (this.particleSystem.forceOvertimeModule.enable) { - this.particleSystem.forceOvertimeModule.animate(p, dt); - } - if (this.particleSystem.velocityOvertimeModule.enable) { - this.particleSystem.velocityOvertimeModule.animate(p); - } - else { - vec3.copy(p.ultimateVelocity, p.velocity); - } - if (this.particleSystem.limitVelocityOvertimeModule.enable) { - this.particleSystem.limitVelocityOvertimeModule.animate(p); - } - if (this.particleSystem.rotationOvertimeModule.enable) { - this.particleSystem.rotationOvertimeModule.animate(p, dt); - } - if (this.particleSystem.textureAnimationModule.enable) { - this.particleSystem.textureAnimationModule.animate(p); - } - vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. - } - } - - // internal function - _updateRenderData() { - // update vertex buffer - let idx = 0; - let uploadVel = this._renderMode == RenderMode.StrecthedBillboard; - for (let i = 0; i < this._particles.length; ++i) { - let p = this._particles.data[i]; - let fi = 0; - if (this.particleSystem.textureAnimationModule.enable) { - fi = p.frameIndex; - } - idx = i * 4; - let attrNum = 0; - for (let j = 0; j < 4; ++j) { // four verts per particle. - attrNum = 0; - this.attrs[attrNum++] = p.position; - _tempAttribUV.x = _uvs[2 * j]; - _tempAttribUV.y = _uvs[2 * j + 1]; - _tempAttribUV.z = fi; - this.attrs[attrNum++] = _tempAttribUV; - _tempAttribUV0.x = p.size.x; - _tempAttribUV0.y = p.rotation.x; - this.attrs[attrNum++] = _tempAttribUV0; - this.attrs[attrNum++] = p.color._val; - - if (uploadVel) { - this.attrs[attrNum++] = p.ultimateVelocity; - } - - this._model!.addParticleVertexData(idx++, this.attrs); - } - } - - // because we use index buffer, per particle index count = 6. - this._model!.updateIA(this._particles.length * 6); - } - - updateShaderUniform() { - - } - - _onMaterialModified(index, material) { - this._updateMaterialParams(); - this._updateModel(); - } } Object.assign(ParticleSystemRenderer, { uv: _uvs }); diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 33fd72015b..3a66658077 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -99,11 +99,11 @@ export class RenderableComponent extends Component { this._onMaterialModified(index, material); } - public _onMaterialModified (index: number, material: Material | null) { + protected _onMaterialModified (index: number, material: Material | null) { } - public _clearMaterials () { + private _clearMaterials () { } } diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/3d/memop/recycle-pool.ts index 5d231f143e..fb48e86b17 100644 --- a/cocos/3d/memop/recycle-pool.ts +++ b/cocos/3d/memop/recycle-pool.ts @@ -4,13 +4,16 @@ 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); } } @@ -51,13 +54,14 @@ 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 (element: T) { - const idx = this.data.indexOf(element); - if (idx >= 0) { - this.removeAt(idx); + public remove (obj: T) { + if (this._objIdx.has(obj)) { + this.removeAt(this._objIdx.get(obj)); } } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 4acf9b9cf2..145e81f770 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -2082,7 +2082,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (gpuInputAssembler.gpuIndirectBuffer) { for (const drawInfo of gpuInputAssembler.gpuIndirectBuffer.indirects) { const gpuBuffer = gpuInputAssembler.gpuIndexBuffer; - if (gpuBuffer && drawInfo.indexCount > 0) { + if (gpuBuffer && drawInfo.indexCount > -1) { const offset = drawInfo.firstIndex * gpuBuffer.stride; gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset); } else { diff --git a/cocos/renderer/models/particle-batch-model.ts b/cocos/renderer/models/particle-batch-model.ts index f9a0b6aedd..48789cb196 100644 --- a/cocos/renderer/models/particle-batch-model.ts +++ b/cocos/renderer/models/particle-batch-model.ts @@ -9,6 +9,7 @@ import { IGFXInputAttribute } from '../../gfx/input-assembler'; import { Node } from '../../scene-graph/node'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; +import { IRenderingSubmesh } from '../../3d/assets/mesh'; export default class ParticleBatchModel extends Model { @@ -21,6 +22,7 @@ export default class ParticleBatchModel extends Model { private _vdataUint32: Uint32Array | null; private _iaInfo: IGFXIndirectBuffer; private _iaInfoBuffer: GFXBuffer; + private _subMeshData: IRenderingSubmesh | null; constructor (scene: RenderScene, node: Node) { super(scene, node); @@ -50,6 +52,7 @@ export default class ParticleBatchModel extends Model { size: GFX_DRAW_INFO_SIZE, stride: 1, }); + this._subMeshData = null; } public setCapacity (capacity: number) { @@ -60,17 +63,20 @@ export default class ParticleBatchModel extends Model { this._vertAttrs = attrs; this._vertSize = 0; for (const a of this._vertAttrs) { - this._vertSize += GFXFormatInfos[a.format].size; + this._vertSize += GFXFormatInfos[a.format].size * GFXFormatInfos[a.format].count; } // rebuid - this._vBuffer = this._createInputAssembler(); + this._vBuffer = this._createSubMeshData(); this._vertAttrsFloatCount = this._vertSize / 4; // number of float this._vBuffer = new ArrayBuffer(this._capacity * this._vertSize * 4); this._vdataF32 = new Float32Array(this._vBuffer); this._vdataUint32 = new Uint32Array(this._vBuffer); } - public _createInputAssembler (): ArrayBuffer { + public _createSubMeshData (): ArrayBuffer { + if (this._subMeshData) { + this.destroySubMeshData(); + } const vertexBuffer = this._device.createBuffer({ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, @@ -105,15 +111,14 @@ export default class ParticleBatchModel extends Model { this._iaInfo.drawInfos[0].indexCount = this._capacity * 6; this._iaInfoBuffer.update(this._iaInfo); - this.subMeshData = { - inputAssembler: this._device.createInputAssembler({ - attributes: this._vertAttrs!, - vertexBuffers: [vertexBuffer], - indexBuffer, - indirectBuffer: this._iaInfoBuffer, - }), + this._subMeshData = { + vertexBuffers: [vertexBuffer], + indexBuffer, + indirectBuffer: this._iaInfoBuffer, + attributes: this._vertAttrs!, primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST, }; + this.setSubModelMesh(0, this._subMeshData); return vBuffer; } @@ -131,7 +136,7 @@ export default class ParticleBatchModel extends Model { } } - public addParticleVertexData (index: number, pvdata: [any]) { + public addParticleVertexData (index: number, pvdata: any[]) { // if (pvdata.length !== this._vertAttrs.length) { // console.error('particle vertex stream data not match.'); // } @@ -160,19 +165,27 @@ export default class ParticleBatchModel extends Model { } public updateIA (count: number) { - this._subMeshObject!.inputAssembler.vertexBuffers[0].update(this._vdataF32!); - this._subMeshObject!.inputAssembler.indexCount = count; - this._subMeshObject!.inputAssembler.extractDrawInfo(this._iaInfo.drawInfos[0]); + this.getSubModel(0).inputAssembler!.vertexBuffers[0].update(this._vdataF32!); + this.getSubModel(0).inputAssembler!.indexCount = count; + this.getSubModel(0).inputAssembler!.extractDrawInfo(this._iaInfo.drawInfos[0]); this._iaInfoBuffer.update(this._iaInfo); } public clear () { - this._subMeshObject!.inputAssembler.indexCount = 0; + this.getSubModel(0).inputAssembler!.indexCount = 0; + } + + private destroySubMeshData () { + for (const vb of this._subMeshData!.vertexBuffers) { + vb.destroy(); + } + this._subMeshData!.indexBuffer.destroy(); } public destroy () { + super.destroy(); this._vdataF32 = null; - this._subMeshObject!.inputAssembler.destroy(); + this.destroySubMeshData(); this._iaInfoBuffer.destroy(); } } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 6b785fdb5a..83fc3c003f 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -69,6 +69,8 @@ export class Model { subModel.destroy(); _subMeshPool.remove(subModel); } + this._matPSORecord.clear(); + this._matRefCount.clear(); } set scene (scene: RenderScene) { @@ -93,14 +95,16 @@ export class Model { } public _updateTransform () { - if (!this._node.hasChanged) { return; } - this._node.updateWorldTransformFull(); - if (!this._modelBounds) { return; } + if (!this._node.hasChanged) { + this._node.updateWorldTransformFull(); + if (!this._modelBounds) { - this._modelBounds.transform( - // @ts-ignore - this._node._mat, this._node._pos, this._node._rot, this._node._scale, - this._worldBounds); + this._modelBounds.transform( + // @ts-ignore + this._node._mat, this._node._pos, this._node._rot, this._node._scale, + this._worldBounds); + } + } } public updateUBOs () { @@ -182,19 +186,30 @@ export class Model { this._subModels[idx].initialize(subMeshData, mat, this._matPSORecord.get(mat)!); } - public setSubModelMaterial (idx: number, mat: Material) { + public setSubModelMesh (idx: number, subMeshData: IRenderingSubmesh) { + if (this._subModels[idx] == null) { + this._subModels[idx] = _subMeshPool.add(); + } + this._subModels[idx].subMeshData = subMeshData; + } + + public setSubModelMaterial (idx: number, mat: Material | null) { if (this._subModels[idx] == null) { return; } if (this._subModels[idx].material === mat) { - this.destroyPipelineState(mat, this._matPSORecord.get(mat)!); - this._matPSORecord.set(mat, this.createPipelineState(mat)); + this.destroyPipelineState(mat!, this._matPSORecord.get(mat!)!); + this._matPSORecord.set(mat!, this.createPipelineState(mat!)); } else { - this.releasePSO(this._subModels[idx].material); - this.allocatePSO(mat); + if (this._subModels[idx].material) { + this.releasePSO(this._subModels[idx].material!); + } + if (mat) { + this.allocatePSO(mat); + } } + this._subModels[idx]._psos = mat ? this._matPSORecord.get(mat)! : null; this._subModels[idx].material = mat; - this._subModels[idx].psos = this._matPSORecord.get(mat)!; } protected createPipelineState (mat: Material): GFXPipelineState[] { diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index 00962ea902..6155c9ce30 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -9,7 +9,7 @@ import { Pass } from '../core/pass'; export class SubModel { protected _subMeshObject: IRenderingSubmesh | null; - private _inputAssembler: GFXInputAssembler | null; + protected _inputAssembler: GFXInputAssembler | null; private _material: Material | null; private _cmdBuffers: GFXCommandBuffer[]; private _psos: GFXPipelineState[] | null; @@ -27,13 +27,6 @@ export class SubModel { public initialize (subMesh: IRenderingSubmesh, mat: Material, psos: GFXPipelineState[]) { this._psos = psos; this.subMeshData = subMesh; - const iaInfo = {} as IGFXInputAssemblerInfo; - iaInfo.attributes = this._subMeshObject!.attributes; - iaInfo.vertexBuffers = this._subMeshObject!.vertexBuffers; - if (this._subMeshObject!.indexBuffer) { - iaInfo.indexBuffer = this._subMeshObject!.indexBuffer; - } - this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); this.material = mat; } @@ -42,10 +35,29 @@ export class SubModel { if (this._inputAssembler) { this._inputAssembler.destroy(); } + for (let i = 0; i < this.passes.length; i++) { + this.passes[i].destroyPipelineState(this._psos![i]); + } + for (const cmdBuffer of this._cmdBuffers) { + cmdBuffer.destroy(); + } } set subMeshData (sm: IRenderingSubmesh) { + if (this._inputAssembler) { + this._inputAssembler.destroy(); + } this._subMeshObject = sm; + const iaInfo = {} as IGFXInputAssemblerInfo; + iaInfo.attributes = this._subMeshObject!.attributes; + iaInfo.vertexBuffers = this._subMeshObject!.vertexBuffers; + if (this._subMeshObject!.indexBuffer) { + iaInfo.indexBuffer = this._subMeshObject!.indexBuffer; + } + if (this._subMeshObject!.indirectBuffer) { + iaInfo.indirectBuffer = this._subMeshObject!.indirectBuffer; + } + this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); } get subMeshData () { @@ -60,7 +72,7 @@ export class SubModel { this._psos = val; } - set material (material: Material) { + set material (material: Material | null) { this._material = material; if (material == null) { return; @@ -79,10 +91,14 @@ export class SubModel { } } - get material (): Material { + get material (): Material | null { return this._material!; } + get inputAssembler (): GFXInputAssembler | null { + return this._inputAssembler; + } + get castShadow (): boolean { return this._castShadow; } From 8c7cdaf623f8220489cd62a3e15aeb6fe0ccbd7e Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 21 Jan 2019 16:28:48 +0800 Subject: [PATCH 187/267] mask-component --- cocos/3d/ui/assembler/mask-assembler.js | 144 ------------ cocos/3d/ui/assembler/mask-assembler.ts | 175 ++++++++++++++ cocos/3d/ui/components/mask-component.ts | 280 +++++++++-------------- 3 files changed, 288 insertions(+), 311 deletions(-) delete mode 100644 cocos/3d/ui/assembler/mask-assembler.js create mode 100644 cocos/3d/ui/assembler/mask-assembler.ts diff --git a/cocos/3d/ui/assembler/mask-assembler.js b/cocos/3d/ui/assembler/mask-assembler.js deleted file mode 100644 index f73ebd73dc..0000000000 --- a/cocos/3d/ui/assembler/mask-assembler.js +++ /dev/null @@ -1,144 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -const StencilManager = require('../stencil-manager'); -const Node = require('../../../CCNode'); -const Mask = require('../../../components/CCMask'); -const Graphics = require('../../../graphics/graphics'); -const RenderFlow = require('../../render-flow'); - -const spriteAssembler = require('./sprite/simple'); -const graphicsAssembler = require('./graphics'); - -let _stencilMgr = StencilManager.sharedManager; -// for nested mask, we might need multiple graphics component to avoid data conflict -let _graphicsPool = []; -let _graphicsUsing = []; - -function getGraphics () { - let graphics = _graphicsPool.pop(); - - if (!graphics) { - let graphicsNode = new Node(); - graphics = graphicsNode.addComponent(Graphics); - graphics._activateMaterial(); - graphics.lineWidth = 0; - graphics.rect(0, 0, cc.visibleRect.width, cc.visibleRect.height); - graphics.fill(); - graphicsAssembler.updateRenderData(graphics); - } - return graphics; -} - -let maskFrontAssembler = { - updateRenderData (mask) { - if (!mask._renderData) { - if (mask._type === Mask.Type.IMAGE_STENCIL) { - mask._renderData = spriteAssembler.createData(mask); - } - else { - // for updateGraphics calculation - mask._renderData = mask.requestRenderData(); - } - } - let renderData = mask._renderData; - - if (mask._type === Mask.Type.IMAGE_STENCIL) { - if (mask.spriteFrame) { - let size = mask.node._contentSize; - let anchor = mask.node._anchorPoint; - renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); - renderData.dataLength = 4; - spriteAssembler.updateRenderData(mask); - renderData.material = mask._material; - } - else { - mask._material = null; - } - } - else { - mask._graphics._material = mask._material; - graphicsAssembler.updateRenderData(mask._graphics); - } - }, - - fillBuffers (mask, renderer) { - // Invalid state - if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) { - // HACK: Must push mask after batch, so we can only put this logic in fillVertexBuffer or fillIndexBuffer - _stencilMgr.pushMask(mask); - _stencilMgr.clear(); - - mask._clearGraphics = getGraphics(); - graphicsAssembler.fillBuffers(mask._clearGraphics, renderer); - - _stencilMgr.enterLevel(); - - // vertex buffer - renderer.node = mask.node; - renderer.material = mask._material; - if (mask._type === Mask.Type.IMAGE_STENCIL) { - spriteAssembler.fillBuffers(mask, renderer); - renderer._flush(); - } - else { - graphicsAssembler.fillBuffers(mask._graphics, renderer); - } - } - - mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - } -}; - -let maskEndAssembler = { - fillBuffers (mask, renderer) { - // Invalid state - if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) { - // HACK: Must pop mask after batch, so we can only put this logic in fillBuffers - _stencilMgr.exitMask(); - - _graphicsUsing.push(mask._clearGraphics); - mask._clearGraphics = null; - - // Clear graphics can only be recycled after the mask stack exits entirely. - if (_stencilMgr.stage === StencilManager.Stage.DISABLED) { - for (let i = 0; i < _graphicsUsing.length; i++) { - _graphicsPool.push(_graphicsUsing[i]); - } - _graphicsUsing.length = 0; - } - } - - mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - } -}; - -Mask._assembler = maskFrontAssembler; -Mask._postAssembler = maskEndAssembler; - -module.exports = { - front: maskFrontAssembler, - end: maskEndAssembler -} \ No newline at end of file diff --git a/cocos/3d/ui/assembler/mask-assembler.ts b/cocos/3d/ui/assembler/mask-assembler.ts new file mode 100644 index 0000000000..3663021549 --- /dev/null +++ b/cocos/3d/ui/assembler/mask-assembler.ts @@ -0,0 +1,175 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { GFXComparisonFunc, GFXStencilOp } from '../../../gfx/define'; +import { UI } from '../../../renderer/ui/ui'; +import { Material } from '../../assets/material'; +import { MaskComponent } from '../components/mask-component'; +import { MeshBuffer } from '../mesh-buffer'; +import { IAssembler } from './assembler'; + +interface IStencilState { + stencilTest?: boolean; + func?: GFXComparisonFunc; + readMask?: number; + writeMask?: number; + failOp?: GFXStencilOp; + zFailOp?: GFXStencilOp; + passOp?: GFXStencilOp; + ref?: number; +} + +interface IStencilStateUpdate { + func: GFXComparisonFunc; + writeMask: number; + ref: number; +} + +function overrideStencilState (material: Material, state: IStencilState) { + material.overridePipelineStates({ + depthStencilState: { + stencilTestFront: state.stencilTest, + stencilFuncFront: state.func, + stencilReadMaskFront: state.readMask, + stencilWriteMaskFront: state.writeMask, + stencilFailOpFront: state.failOp, + stencilZFailOpFront: state.zFailOp, + stencilPassOpFront: state.passOp, + stencilRefFront: state.ref, + stencilTestBack: state.stencilTest, + stencilFuncBack: state.func, + stencilReadMaskBack: state.readMask, + stencilWriteMaskBack: state.writeMask, + stencilFailOpBack: state.failOp, + stencilZFailOpBack: state.zFailOp, + stencilPassOpBack: state.passOp, + stencilRefBack: state.ref, + }, + }); +} + +function updateDynamicStencilStates (material: Material, state: IStencilStateUpdate) { + +} + +class StencilManager { + private _maskStack: MaskComponent[] = []; + + public enter (mask: MaskComponent) { + this._maskStack.push(mask); + } + + public exit () { + this._maskStack.pop(); + } + + public updateMaskMaterial (material: Material) { + updateDynamicStencilStates(material, { + func: GFXComparisonFunc.ALWAYS, + writeMask: this._protectAncestorMasks(), + ref: this._getWriteMaskForTopMask(), + }); + } + + public updateClearMaskMaterial (material: Material) { + updateDynamicStencilStates(material, { + func: GFXComparisonFunc.ALWAYS, + writeMask: this._protectAncestorMasks(), + ref: 0, + }); + } + + private _readAncestorMasks (): number { + let result = 0; + this._maskStack.forEach((mask, iBit) => { + result |= (1 << iBit); + }); + return result; + } + + private _protectAncestorMasks (): number { + return ~this._readAncestorMasks(); + } + + private _getWriteMaskForTopMask (): number { + return 1 << this._maskStack.length; + } +} + +const stencilManager = new StencilManager(); + +export const maskAssembler: IAssembler = { + useModel : false, + + updateRenderData (mask: MaskComponent) { + }, + + fillBuffers (mask: MaskComponent, ui: UI) { + stencilManager.enter(mask); + mask._createRenderData(ui); + }, +}; + +export const maskEndAssembler: IAssembler = { + fillBuffers (mask: MaskComponent, meshBuffer: MeshBuffer) { + stencilManager.exit(); + }, +}; + +export function setupMaskMaterial (material: Material) { + overrideStencilState(material, { + stencilTest: true, + func: GFXComparisonFunc.ALWAYS, + readMask: 0xffffffff, + failOp: GFXStencilOp.KEEP, + zFailOp: GFXStencilOp.KEEP, + passOp: GFXStencilOp.REPLACE, + }); +} + +export function setupClearMaskMaterial (material: Material) { + overrideStencilState(material, { + stencilTest: true, + func: GFXComparisonFunc.ALWAYS, + readMask: 0xffffffff, + failOp: GFXStencilOp.KEEP, + zFailOp: GFXStencilOp.KEEP, + passOp: GFXStencilOp.REPLACE, + ref: 0, + }); +} + +export function setupMaskTargetMaterial (material: Material) { + overrideStencilState(material, { + stencilTest: true, + func: GFXComparisonFunc.NOT_EQUAL, + readMask: 0xffffffff, + writeMask: 0xffffffff, + failOp: GFXStencilOp.KEEP, + zFailOp: GFXStencilOp.KEEP, + passOp: GFXStencilOp.KEEP, + ref: 0, + }); +} diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index 577f0cbfc2..4694738b39 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -27,18 +27,19 @@ import {SpriteFrame} from '../../../assets/CCSpriteFrame'; import { ccclass, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../../core/data/class-decorator'; import { ccenum } from '../../../core/value-types/enum'; -import { clamp } from '../../../core/vmath'; +import { clamp, vec3 } from '../../../core/vmath'; +import { GFXPrimitiveMode } from '../../../gfx/define'; +import { IUIRenderData, UI } from '../../../renderer/ui/ui'; import { Node } from '../../../scene-graph/node'; +import { Material } from '../../assets/material'; +import circle from '../../primitive/circle'; +import { IGeometry } from '../../primitive/define'; +import quad from '../../primitive/quad'; +import { scale, translate } from '../../primitive/transform'; +import { setupClearMaskMaterial, setupMaskMaterial } from '../assembler/mask-assembler'; +import { MeshBuffer } from '../mesh-buffer'; import { UIRenderComponent } from './ui-render-component'; import { UITransformComponent } from './ui-transfrom-component'; -const renderEngine = require('../../../2d/renderer/render-engine'); -const math = renderEngine.math; -const StencilMaterial = renderEngine.StencilMaterial; -// const RenderFlow = require('../../../2d/renderer/render-flow'); -const Graphics = require('../../../2d/graphics/graphics'); - -const _vec2_temp = cc.v2(); -const _mat4_temp = math.mat4.create(); /** * !#en the type for mask. @@ -112,18 +113,10 @@ export class MaskComponent extends UIRenderComponent { } public set spriteFrame (value) { - const lastSprite = this._spriteFrame; - if (CC_EDITOR) { - if ((lastSprite && lastSprite._uuid) === (value && value._uuid)) { - return; - } - } else { - if (lastSprite === value) { - return; - } + if (this._spriteFrame === value) { + return; } - this._spriteFrame = value; - this._applySpriteFrame(lastSprite); + this._applySpriteFrame(value); } /** @@ -149,14 +142,6 @@ export class MaskComponent extends UIRenderComponent { public set alphaThreshold (value) { this._alphaThreshold = value; - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - cc.warnID(4201); - return; - } - if (this._material) { - this._material.alphaThreshold = this.alphaThreshold; - this._material.updateHash(); - } } /** @@ -189,15 +174,6 @@ export class MaskComponent extends UIRenderComponent { this._segments = clamp(value, SEGEMENTS_MIN, SEGEMENTS_MAX); } - // _resizeToTarget: { - // animatable: false, - // set (value) { - // if (value) { - // this._resizeNodeToTargetNode(); - // } - // }, - // }, - @property private _spriteFrame: SpriteFrame | null = null; @@ -213,68 +189,35 @@ export class MaskComponent extends UIRenderComponent { @property private _segments: number = 64; - private _graphics: Graphics | null = null; + private _maskMaterial: Material | null = null; - private _material: StencilMaterial | null = null; + private _clearMaskMaterial: Material | null = null; + + private _maskGeometry: IGeometry | null = null; public onLoad () { - this._graphics = new Graphics(); - this._graphics.node = this.node; - this._graphics.lineWidth = 0; - this._graphics.strokeColor = cc.color(0, 0, 0, 0); - } - - public onRestore () { - if (!this._graphics) { - this._graphics = new Graphics(); - this._graphics.node = this.node; - this._graphics.lineWidth = 0; - } - if (this._type !== MaskType.IMAGE_STENCIL) { - this._updateGraphics(); - } + this._activateMaterial(); } public onEnable () { super.onEnable(); - if (this._type === MaskType.IMAGE_STENCIL) { - if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { - // Do not render when sprite frame is not ready - this.markForRender(false); - if (this._spriteFrame) { - this._spriteFrame.once('load', this._onTextureLoaded, this); - this._spriteFrame.ensureLoadTexture(); - } - } - } else { - this._updateGraphics(); - } - - this.node.on(Node.EventType.POSITION_CHANGED, this._updateGraphics, this); - this.node.on(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); - this.node.on(Node.EventType.SCALE_CHANGED, this._updateGraphics, this); - this.node.on(Node.EventType.SIZE_CHANGED, this._updateGraphics, this); - this.node.on(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); - - // this.node._renderFlag |= RenderFlow.FLAG_POST_RENDER; this._activateMaterial(); } public onDisable () { super.onDisable(); - this.node.off(Node.EventType.POSITION_CHANGED, this._updateGraphics, this); - this.node.off(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); - this.node.off(Node.EventType.SCALE_CHANGED, this._updateGraphics, this); - this.node.off(Node.EventType.SIZE_CHANGED, this._updateGraphics, this); - this.node.off(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); + // this.node.off(Node.EventType.POSITION_CHANGED, this._updateGraphics, this); + // this.node.off(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this); + // this.node.off(Node.EventType.SCALE_CHANGED, this._updateGraphics, this); + // this.node.off(Node.EventType.SIZE_CHANGED, this._updateGraphics, this); + // this.node.off(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this); // this.node._renderFlag &= ~RenderFlow.FLAG_POST_RENDER; } public onDestroy () { super.onDestroy(); - this._graphics.destroy(); } // _resizeNodeToTargetNode: CC_EDITOR && function () { @@ -289,7 +232,6 @@ export class MaskComponent extends UIRenderComponent { if (this._renderData) { this._renderData.uvDirty = true; this._renderData.vertDirty = true; - this.markForUpdateRenderData(true); } // Reactivate material if (this.enabledInHierarchy) { @@ -313,106 +255,110 @@ export class MaskComponent extends UIRenderComponent { } public _activateMaterial () { - // cannot be activated if texture not loaded yet - if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) { - this.markForRender(false); - return; + if (!this._maskMaterial) { + this._maskMaterial = Material.getInstantiatedMaterial(cc.BuiltinResMgr['sprite-material'], this); + setupMaskMaterial(this._maskMaterial); } - // WebGL - if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { - // Init material - if (!this._material) { - this._material = new StencilMaterial(); - } - - // Reset material - if (this._type === MaskType.IMAGE_STENCIL) { - const texture = this._spriteFrame; - this._material.useModel = false; - this._material.useTexture = true; - this._material.useColor = true; - this._material.texture = texture; - this._material.alphaThreshold = this.alphaThreshold; - } else { - this._material.useModel = true; - this._material.useTexture = false; - this._material.useColor = false; - } - } - - this.markForRender(true); - } - - public _updateGraphics () { - const node = this.node; - const graphics = this._graphics; - // Share render data with graphics content - graphics.clear(false); - const width = node._contentSize.width; - const height = node._contentSize.height; - const x = -width * node._anchorPoint.x; - const y = -height * node._anchorPoint.y; - if (this._type === MaskType.RECT) { - graphics.rect(x, y, width, height); - } else if (this._type === MaskType.ELLIPSE) { - const cx = x + width / 2; - const cy = y + height / 2; - const rx = width / 2; - const ry = height / 2; - graphics.ellipse(cx, cy, rx, ry); - } - if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) { - graphics.stroke(); - } else { - graphics.fill(); + if (!this._clearMaskMaterial) { + this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.BuiltinResMgr['sprite-material'], this); + setupClearMaskMaterial(this._clearMaskMaterial); } } - public _hitTest (cameraPt) { - const node = this.node; - const size = node.getContentSize(); - const w = size.width; - const h = size.height; - const testPt = _vec2_temp; + public _createRenderData (ui: UI) { + if (!this._maskGeometry || !this._maskMaterial || !this._clearMaskMaterial) { + return null; + } - node._updateWorldMatrix(); - math.mat4.invert(_mat4_temp, node._worldMatrix); - math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); - testPt.x += node._anchorPoint.x * w; - testPt.y += node._anchorPoint.y * h; + const maskMeshBuffer = this._createMeshBuffer(ui, this._maskGeometry); + this._fillMaskMeshBuffer(maskMeshBuffer, this._maskGeometry); + const maskRenderData = ui.createUIRenderData() as IUIRenderData; + maskRenderData.meshBuffer = maskMeshBuffer; + maskRenderData.material = this._maskMaterial; - if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) { - return testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h; - } else if (this.type === MaskType.ELLIPSE) { - const rx = w / 2; - const ry = h / 2; - const px = testPt.x - 0.5 * w; - const py = testPt.y - 0.5 * h; - return px * px / (rx * rx) + py * py / (ry * ry) < 1; + const clearMaskGeometry = this._drawRect(0, 0, cc.visibleRect.width, cc.visibleRect.height); + const clearMaskMeshBuffer = this._createMeshBuffer(ui, clearMaskGeometry); + this._fillClearMaskMeshBuffer(clearMaskMeshBuffer, clearMaskGeometry); + const clearMaskRenderData = ui.createUIRenderData() as IUIRenderData; + clearMaskRenderData.meshBuffer = clearMaskMeshBuffer; + clearMaskRenderData.material = this._clearMaskMaterial; + } + + public _getMaskMaterial (): Material | null { + return this._maskMaterial; + } + + public _getClearMaterial (): Material | null { + return this._clearMaskMaterial; + } + + private _updateGraphics () { + this._maskGeometry = this._getGraphics(); + } + + private _getGraphics () { + const uiTransform = this.node.getComponent(UITransformComponent); + if (!uiTransform) { + return null; + } + const width = uiTransform.width; + const height = uiTransform.height; + const x = -width * uiTransform.anchorPoint.x; + const y = -height * uiTransform.anchorPoint.y; + switch (this._type) { + case MaskType.RECT: + case MaskType.IMAGE_STENCIL: + return this._drawRect(x, y, width, height); + case MaskType.ELLIPSE: + const cx = x + width / 2; + const cy = y + height / 2; + const rx = width / 2; + const ry = height / 2; + return this._drawEllipse(cx, cy, rx, ry); + } + return null; + } + + private _fillMaskMeshBuffer (meshBuffer: MeshBuffer, geometry: IGeometry) { + const nVert = Math.floor(geometry.positions.length / 3); + const v = new vec3(); + const worldMatrix = this.node.getWorldMatrix(); + for (let i = 0; i < nVert; ++i) { + vec3.set(v, geometry.positions[3 * i + 0], geometry.positions[3 * i + 1], geometry.positions[3 * i + 2]); + vec3.transformMat4(v, v, worldMatrix); + meshBuffer.vData![3 * i + 0] = v.x; + meshBuffer.vData![3 * i + 1] = v.y; + meshBuffer.vData![3 * i + 2] = v.z; } } - public markForUpdateRenderData (enable) { - // if (enable && this.enabledInHierarchy) { - // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA; - // } else if (!enable) { - // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA; - // } + private _fillClearMaskMeshBuffer (meshBuffer: MeshBuffer, geometry: IGeometry) { + meshBuffer.vData!.set(geometry.positions); } - public markForRender (enable) { - // if (enable && this.enabledInHierarchy) { - // this.node._renderFlag |= (RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | - // RenderFlow.FLAG_POST_RENDER); - // } else if (!enable) { - // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_POST_RENDER); - // } + private _createMeshBuffer (ui: UI, geometry: IGeometry) { + const nVert = Math.floor(geometry.positions.length / 3); + const meshBuffer = ui.createBuffer(nVert, geometry.indices ? geometry.indices.length : 0); + if (geometry.indices) { + meshBuffer.iData!.set(geometry.indices); + } + // geometry.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : geometry.primitiveMode; + return meshBuffer; } - public disableRender () { - // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | - // RenderFlow.FLAG_POST_RENDER); + private _drawRect (x: number, y: number, width: number, height: number) { + const geometry = quad({ includeNormal: false, includeUV: false }); + scale(geometry, { x: width, y: height }); + translate(geometry, { x: x + width / 2, y: y + height / 2 }); + return geometry; + } + + private _drawEllipse (cx: number, cy: number, rx: number, ry: number) { + const geometry = circle({ includeNormal: false, includeUV: false }); + scale(geometry, { x: rx, y: ry }); + translate(geometry, { x: cx, y: cy }); + return geometry; } } From f025a6c9359eb5f801e8d594385d5fae4ef7165e Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 21 Jan 2019 16:56:26 +0800 Subject: [PATCH 188/267] move most meshbuffer logic to assembler --- cocos/3d/ui/assembler/mask-assembler.ts | 55 ++++++++++++++++++---- cocos/3d/ui/components/mask-component.ts | 58 ++++-------------------- 2 files changed, 56 insertions(+), 57 deletions(-) diff --git a/cocos/3d/ui/assembler/mask-assembler.ts b/cocos/3d/ui/assembler/mask-assembler.ts index 3663021549..412466ffd6 100644 --- a/cocos/3d/ui/assembler/mask-assembler.ts +++ b/cocos/3d/ui/assembler/mask-assembler.ts @@ -23,11 +23,12 @@ THE SOFTWARE. ****************************************************************************/ +import { vec3 } from '../../../core/vmath'; import { GFXComparisonFunc, GFXStencilOp } from '../../../gfx/define'; -import { UI } from '../../../renderer/ui/ui'; +import { IUIRenderData, UI } from '../../../renderer/ui/ui'; import { Material } from '../../assets/material'; +import { IGeometry } from '../../primitive/define'; import { MaskComponent } from '../components/mask-component'; -import { MeshBuffer } from '../mesh-buffer'; import { IAssembler } from './assembler'; interface IStencilState { @@ -121,20 +122,46 @@ class StencilManager { const stencilManager = new StencilManager(); export const maskAssembler: IAssembler = { - useModel : false, - - updateRenderData (mask: MaskComponent) { - }, - fillBuffers (mask: MaskComponent, ui: UI) { stencilManager.enter(mask); - mask._createRenderData(ui); + + const maskGeometry = mask._getMaskGeometry(); + const maskMaterial = mask._getMaskMaterial(); + if (maskGeometry && maskMaterial) { + const meshBuffer = createMeshBuffer(ui, maskGeometry); + const nVert = Math.floor(maskGeometry.positions.length / 3); + const v = new vec3(); + const worldMatrix = mask.node.getWorldMatrix(); + for (let i = 0; i < nVert; ++i) { + vec3.set(v, + maskGeometry.positions[3 * i + 0], + maskGeometry.positions[3 * i + 1], + maskGeometry.positions[3 * i + 2]); + vec3.transformMat4(v, v, worldMatrix); + meshBuffer.vData![3 * i + 0] = v.x; + meshBuffer.vData![3 * i + 1] = v.y; + meshBuffer.vData![3 * i + 2] = v.z; + } + const maskRenderData = ui.createUIRenderData() as IUIRenderData; + maskRenderData.meshBuffer = meshBuffer; + maskRenderData.material = maskMaterial; + } }, }; export const maskEndAssembler: IAssembler = { - fillBuffers (mask: MaskComponent, meshBuffer: MeshBuffer) { + fillBuffers (mask: MaskComponent, ui: UI) { stencilManager.exit(); + + const clearGeometry = mask._getClearGeometry(); + const clearMaterial = mask._getClearMaterial(); + if (clearGeometry && clearMaterial) { + const meshBuffer = createMeshBuffer(ui, clearGeometry); + meshBuffer.vData!.set(clearGeometry.positions); + const clearMaskRenderData = ui.createUIRenderData() as IUIRenderData; + clearMaskRenderData.meshBuffer = meshBuffer; + clearMaskRenderData.material = clearMaterial; + } }, }; @@ -173,3 +200,13 @@ export function setupMaskTargetMaterial (material: Material) { ref: 0, }); } + +function createMeshBuffer (ui: UI, geometry: IGeometry) { + const nVert = Math.floor(geometry.positions.length / 3); + const meshBuffer = ui.createBuffer(nVert, geometry.indices ? geometry.indices.length : 0); + if (geometry.indices) { + meshBuffer.iData!.set(geometry.indices); + } + // geometry.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : geometry.primitiveMode; + return meshBuffer; +} diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index 4694738b39..807aee1a46 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -27,17 +27,13 @@ import {SpriteFrame} from '../../../assets/CCSpriteFrame'; import { ccclass, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../../core/data/class-decorator'; import { ccenum } from '../../../core/value-types/enum'; -import { clamp, vec3 } from '../../../core/vmath'; -import { GFXPrimitiveMode } from '../../../gfx/define'; -import { IUIRenderData, UI } from '../../../renderer/ui/ui'; -import { Node } from '../../../scene-graph/node'; +import { clamp } from '../../../core/vmath'; import { Material } from '../../assets/material'; import circle from '../../primitive/circle'; import { IGeometry } from '../../primitive/define'; import quad from '../../primitive/quad'; import { scale, translate } from '../../primitive/transform'; import { setupClearMaskMaterial, setupMaskMaterial } from '../assembler/mask-assembler'; -import { MeshBuffer } from '../mesh-buffer'; import { UIRenderComponent } from './ui-render-component'; import { UITransformComponent } from './ui-transfrom-component'; @@ -195,6 +191,8 @@ export class MaskComponent extends UIRenderComponent { private _maskGeometry: IGeometry | null = null; + private _clearGeometry: IGeometry | null = null; + public onLoad () { this._activateMaterial(); } @@ -266,23 +264,12 @@ export class MaskComponent extends UIRenderComponent { } } - public _createRenderData (ui: UI) { - if (!this._maskGeometry || !this._maskMaterial || !this._clearMaskMaterial) { - return null; - } + public _getMaskGeometry () { + return this._maskGeometry; + } - const maskMeshBuffer = this._createMeshBuffer(ui, this._maskGeometry); - this._fillMaskMeshBuffer(maskMeshBuffer, this._maskGeometry); - const maskRenderData = ui.createUIRenderData() as IUIRenderData; - maskRenderData.meshBuffer = maskMeshBuffer; - maskRenderData.material = this._maskMaterial; - - const clearMaskGeometry = this._drawRect(0, 0, cc.visibleRect.width, cc.visibleRect.height); - const clearMaskMeshBuffer = this._createMeshBuffer(ui, clearMaskGeometry); - this._fillClearMaskMeshBuffer(clearMaskMeshBuffer, clearMaskGeometry); - const clearMaskRenderData = ui.createUIRenderData() as IUIRenderData; - clearMaskRenderData.meshBuffer = clearMaskMeshBuffer; - clearMaskRenderData.material = this._clearMaskMaterial; + public _getClearGeometry () { + return this._clearGeometry; } public _getMaskMaterial (): Material | null { @@ -295,6 +282,8 @@ export class MaskComponent extends UIRenderComponent { private _updateGraphics () { this._maskGeometry = this._getGraphics(); + this._clearGeometry = this._drawRect( + 0, 0, cc.visibleRect.width, cc.visibleRect.height); } private _getGraphics () { @@ -320,33 +309,6 @@ export class MaskComponent extends UIRenderComponent { return null; } - private _fillMaskMeshBuffer (meshBuffer: MeshBuffer, geometry: IGeometry) { - const nVert = Math.floor(geometry.positions.length / 3); - const v = new vec3(); - const worldMatrix = this.node.getWorldMatrix(); - for (let i = 0; i < nVert; ++i) { - vec3.set(v, geometry.positions[3 * i + 0], geometry.positions[3 * i + 1], geometry.positions[3 * i + 2]); - vec3.transformMat4(v, v, worldMatrix); - meshBuffer.vData![3 * i + 0] = v.x; - meshBuffer.vData![3 * i + 1] = v.y; - meshBuffer.vData![3 * i + 2] = v.z; - } - } - - private _fillClearMaskMeshBuffer (meshBuffer: MeshBuffer, geometry: IGeometry) { - meshBuffer.vData!.set(geometry.positions); - } - - private _createMeshBuffer (ui: UI, geometry: IGeometry) { - const nVert = Math.floor(geometry.positions.length / 3); - const meshBuffer = ui.createBuffer(nVert, geometry.indices ? geometry.indices.length : 0); - if (geometry.indices) { - meshBuffer.iData!.set(geometry.indices); - } - // geometry.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : geometry.primitiveMode; - return meshBuffer; - } - private _drawRect (x: number, y: number, width: number, height: number) { const geometry = quad({ includeNormal: false, includeUV: false }); scale(geometry, { x: width, y: height }); From 34cfd8ae6b6e54058ceaf8010397d8c14512182d Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 21 Jan 2019 14:00:28 +0800 Subject: [PATCH 189/267] material defines --- cocos/3d/assets/material.ts | 12 ++++++------ cocos/3d/framework/model-component.js | 9 ++++++--- .../particle/renderer/particle-system-renderer.ts | 2 +- cocos/components/component.d.ts | 2 +- cocos/renderer/core/effect.ts | 4 ++-- cocos/renderer/models/particle-batch-model.ts | 2 +- cocos/renderer/scene/submodel.ts | 2 +- playground/gizmo.html | 9 +++++---- 8 files changed, 23 insertions(+), 19 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 676ea135d6..1b9b95941d 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -26,14 +26,14 @@ import { Asset } from '../../assets/asset'; 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 { Effect, IDefineMap } from '../../renderer/core/effect'; import { Pass, PassOverrides } from '../../renderer/core/pass'; import { RenderableComponent } from '../framework/renderable-component'; import { EffectAsset } from './effect-asset'; export interface IMaterialInfo { technique?: number; - defines?: Record; + defines?: IDefineMap[]; effectName?: string; } @@ -56,7 +56,7 @@ export class Material extends Asset { @property protected _techIdx = 0; @property - protected _defines: Record = {}; + protected _defines: IDefineMap[] = []; @property protected _props: Array> = []; @@ -68,7 +68,7 @@ export class Material extends Asset { super(); if (info) { if (info.technique) { this._techIdx = info.technique; } - if (info.defines) { this._defines = info.defines; } + if (info.defines) { this.setDefines(info.defines); } if (info.effectName) { this.effectName = info.effectName; } } } @@ -109,8 +109,8 @@ export class Material extends Asset { return this._hash; } - public setDefines (defines: Record) { - this._defines = defines; + public setDefines (defines: IDefineMap | IDefineMap[]) { + this._defines = Array.isArray(defines) ? defines : [defines]; this.update(); } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 3eda1188bc..5abf7ec4d6 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -182,20 +182,23 @@ export class ModelComponent extends RenderableComponent { } _updateModels() { - if (!this.node._scene) { + if (!this.enabled || !this.node._scene) { return; } + if (this._model) { + this._getRenderScene().destroyModel(this._model); + } + let model = this._createModel(); model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._model = model; - this._model.node = this.node; this._updateModelParams(); } _createModel() { - return this._getRenderScene().createModel(Model); + return this._getRenderScene().createModel(Model, this.node); } _updateModelParams() { diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index b162fcc6ff..66f301cfa4 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -140,7 +140,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { return; } if (this._model == null) { - this._model = this._getRenderScene().createModel(ParticleBatchModel) as ParticleBatchModel; + this._model = this._getRenderScene().createModel(ParticleBatchModel, this.node) as ParticleBatchModel; this._model.setCapacity(this.particleSystem.capacity); this._model.setVertexAttributes(this._vertAttrs); this._model.node = this.node; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index 746c5890cc..a08b6af267 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -28,7 +28,7 @@ import { CCObject } from '../core/data/object'; import { getClassName, value } from '../core/utils/js'; import IDGenerator from '../core/utils/id-generator'; import { ccclass, property } from '../core/data/class-decorator'; -import { Node } from '../scene-graph/node'; +import { Node } from '../scene-graph'; import { RenderScene } from '../renderer/scene/render-scene'; export class Component extends CCObject { diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 1300a0ba6d..82f375b1de 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -7,7 +7,7 @@ import { IPassInfoFull, Pass } from './pass'; export interface IDefineMap { [name: string]: number | boolean; } export interface IEffectInfo { techIdx?: number; - defines?: IDefineMap; + defines?: IDefineMap[]; } export class Effect { @@ -24,7 +24,7 @@ export class Effect { for (let k = 0; k < passNum; ++k) { const passInfo = tech.passes[k] as IPassInfoFull; const prog = cc.game._programLib.getTemplate(passInfo.program); - passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines || {}); + passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines && defines[k] || {}); passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); passInfo.globals = cc.director.root.pipeline.globalUBO; passInfo.blocks = prog!.blocks; diff --git a/cocos/renderer/models/particle-batch-model.ts b/cocos/renderer/models/particle-batch-model.ts index 48789cb196..d56794d8e2 100644 --- a/cocos/renderer/models/particle-batch-model.ts +++ b/cocos/renderer/models/particle-batch-model.ts @@ -6,7 +6,7 @@ import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../gfx/buf import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; import { IGFXInputAttribute } from '../../gfx/input-assembler'; -import { Node } from '../../scene-graph/node'; +import { Node } from '../../scene-graph'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; import { IRenderingSubmesh } from '../../3d/assets/mesh'; diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index 6155c9ce30..0006f0e737 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -79,7 +79,7 @@ export class SubModel { } for (let i = 0; i < this._material!.passes.length; i++) { if (this._material!.passes[i].primitive !== this._subMeshObject!.primitiveMode) { - cc.error('the model(%d)\'s primitive type doesn\'t match its pass\'s', i); + cc.error(`the model(%d)'s primitive type doesn't match its pass's`, i); } this.recordCommandBuffer(i); } diff --git a/playground/gizmo.html b/playground/gizmo.html index faf583c1dc..774bbb2486 100644 --- a/playground/gizmo.html +++ b/playground/gizmo.html @@ -52,12 +52,13 @@ cameraNode.parent = scene; cameraNode.setPosition(20, 20, 20); cameraNode.lookAt(cc.v3()); - cameraNode.addComponent(FirstPersonCamera); + // cameraNode.addComponent(FirstPersonCamera); const camComp = cameraNode.addComponent(cc.CameraComponent); - const material = new cc.Material(); - material.setDefines({ USE_COLOR: true }); - material.effectName = 'builtin-effect-unlit'; + const material = new cc.Material({ + effectName: 'builtin-effect-unlit', + defines: { USE_COLOR: true }, + }); const createArrow = (color, rotation) => { From 3af729681b87745531b4e1573760532fe731addf Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 21 Jan 2019 17:05:57 +0800 Subject: [PATCH 190/267] fix eventlistener this undefined --- cocos/core/platform/event-manager/CCEventListener.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/core/platform/event-manager/CCEventListener.ts b/cocos/core/platform/event-manager/CCEventListener.ts index 2a1bb16e14..df8636f435 100644 --- a/cocos/core/platform/event-manager/CCEventListener.ts +++ b/cocos/core/platform/event-manager/CCEventListener.ts @@ -315,7 +315,7 @@ export class Mouse extends EventListener { constructor () { super(EventListener.MOUSE, ListenerID.MOUSE, null); - this._onEvent = this._callback; + this._onEvent = (event: any) => this._callback(event); } public _callback (event) { @@ -435,7 +435,7 @@ export class Acceleration extends EventListener { constructor (callback: Function | null) { super(EventListener.ACCELERATION, ListenerID.ACCELERATION, null); - this._onEvent = this._callback; + this._onEvent = (event: any) => this._callback(event); this._onAccelerationEvent = callback; } @@ -462,7 +462,7 @@ export class Keyboard extends EventListener { constructor () { super(EventListener.KEYBOARD, ListenerID.KEYBOARD, null); - this._onEvent = this._callback; + this._onEvent = (event: any) => this._callback(event); } public _callback (event) { From 65026bf0d4fec13386b32681bd339a71c3280391 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 21 Jan 2019 17:07:24 +0800 Subject: [PATCH 191/267] fix model --- cocos/renderer/scene/model.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 83fc3c003f..b601af39d1 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -95,9 +95,9 @@ export class Model { } public _updateTransform () { - if (!this._node.hasChanged) { + if (this._node.hasChanged) { this._node.updateWorldTransformFull(); - if (!this._modelBounds) { + if (this._modelBounds) { this._modelBounds.transform( // @ts-ignore From 260e43c5111eb9d2690354997e29667e1e3fb310 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 17:10:21 +0800 Subject: [PATCH 192/267] optimize --- cocos/gfx/webgl/webgl-commands.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 4acf9b9cf2..acaf959180 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -567,8 +567,7 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: We export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { - const buff = buffer as ArrayBuffer; - gpuBuffer.vf32!.set(new Float32Array(buff.slice(0, size)), offset); + gpuBuffer.vf32!.set(buffer as Float32Array, offset); } else if (gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) { gpuBuffer.indirects = (buffer as IGFXIndirectBuffer).drawInfos; } else { From 1a583480e536fc45041ea42c2ab57d9c75c83910 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 21 Jan 2019 17:13:43 +0800 Subject: [PATCH 193/267] gizmo bug --- playground/gizmo.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/playground/gizmo.html b/playground/gizmo.html index 774bbb2486..300b5094f4 100644 --- a/playground/gizmo.html +++ b/playground/gizmo.html @@ -52,7 +52,7 @@ cameraNode.parent = scene; cameraNode.setPosition(20, 20, 20); cameraNode.lookAt(cc.v3()); - // cameraNode.addComponent(FirstPersonCamera); + cameraNode.addComponent(FirstPersonCamera); const camComp = cameraNode.addComponent(cc.CameraComponent); const material = new cc.Material({ @@ -60,7 +60,6 @@ defines: { USE_COLOR: true }, }); - const createArrow = (color, rotation) => { const arrow = new cc.Node('arrow'); arrow.setRotation(rotation); @@ -143,7 +142,8 @@ }); cc.director.on(cc.Director.EVENT_AFTER_UPDATE, () => { moveTool.setPosition(vec3.add(moveTool._lpos, moveTool._lpos, vel)); - }) + }); + setInterval(()=> moveTool.active = !moveTool.active, 1000); cc.director.runSceneImmediate(scene); } From 261c25fa349068ffbc8d6a584beaaa7f54d55b02 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 21 Jan 2019 17:26:21 +0800 Subject: [PATCH 194/267] fix model OnDisable --- cocos/3d/framework/model-component.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 5abf7ec4d6..e5209b81d9 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -116,7 +116,7 @@ export class ModelComponent extends RenderableComponent { set mesh(val) { this._mesh = val; - this._updateModels(); + this._updateModels(true); } /** @@ -174,15 +174,14 @@ export class ModelComponent extends RenderableComponent { } onDisable() { - this._getRenderScene().destroyModel(this._model); } onDestroy() { - + this._getRenderScene().destroyModel(this._model); } - _updateModels() { - if (!this.enabled || !this.node._scene) { + _updateModels(forceUpdate) { + if (!this.enabled || !this.node._scene || (this._model && !forceUpdate)) { return; } From 45659efaa0578c5f561137c6e3a562d4b9055c46 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 17:34:54 +0800 Subject: [PATCH 195/267] add model validate check on render pipeline --- cocos/pipeline/render-pipeline.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 9706278cbd..38236e63f7 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -350,7 +350,9 @@ export abstract class RenderPipeline { for (const model of scene.models) { // filter model by view visibility - if (view.visibility > 0 && model.viewID !== view.visibility) { + if (view.visibility > 0 && model.viewID !== view.visibility || + !model.isEnable() || + !model.node.active) { continue; } From 348756c5da576a2403979ae305d7cc0cc7b82ef4 Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Mon, 21 Jan 2019 17:45:44 +0800 Subject: [PATCH 196/267] fix component and fix some bug --- cocos/3d/builtin/init.js | 2 + cocos/3d/ui/assembler/label/ttf.ts | 2 +- cocos/3d/ui/assembler/sprite/simple.ts | 1 - cocos/3d/ui/assembler/utils.js | 53 ++- cocos/3d/ui/components/button-component.ts | 93 ++--- .../components/editbox/edit-box-component.ts | 337 ++++++++---------- .../3d/ui/components/editbox/edit-box-impl.ts | 40 ++- .../ui/components/progress-bar-component.ts | 6 +- cocos/3d/ui/components/slider-component.ts | 38 +- cocos/3d/ui/components/sprite-component.ts | 5 +- cocos/3d/ui/components/toggle-component.ts | 8 +- .../components/toggle-container-component.ts | 2 +- .../ui/components/toggle-group-component.ts | 4 +- cocos/3d/ui/components/ui-render-component.ts | 2 - .../ui/components/ui-transfrom-component.ts | 50 ++- cocos/3d/ui/mesh-buffer.ts | 49 ++- cocos/assets/CCSpriteFrame.ts | 4 +- cocos/renderer/ui/ui.ts | 2 +- 18 files changed, 380 insertions(+), 318 deletions(-) diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index 304ccf62ee..62843f198f 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -76,6 +76,8 @@ let builtinResMgr = { spriteFrame.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); spriteFrame.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); spriteFrame._uuid = 'default-spriteframe'; + spriteFrame.setOriginalSize(cc.size(canvasImage.width, canvasImage.height)); + spriteFrame.setRect(0, 0, canvasImage.width, canvasImage.height); spriteFrame.image = canvasImage; if (spriteFrame.onLoaded) { spriteFrame.onLoaded(); diff --git a/cocos/3d/ui/assembler/label/ttf.ts b/cocos/3d/ui/assembler/label/ttf.ts index 632119da61..b8f9ac8dfa 100644 --- a/cocos/3d/ui/assembler/label/ttf.ts +++ b/cocos/3d/ui/assembler/label/ttf.ts @@ -56,7 +56,7 @@ export const ttf: IAssembler = { }, fillBuffers (comp: LabelComponent, /*renderer*/buffer: MeshBuffer) { - fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp._renderData, WHITE._val); + fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp.renderData, WHITE); }, updateVerts (comp: LabelComponent) { diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts index f0083e322e..802c92cb04 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -24,7 +24,6 @@ ****************************************************************************/ import { vec3 } from '../../../../core/vmath/index'; -import { UIRenderComponent } from '../../components/ui-render-component'; import { SpriteComponent } from '../../components/sprite-component'; import { Vec3, Color } from '../../../../core/value-types'; import { Node } from '../../../../scene-graph/node'; diff --git a/cocos/3d/ui/assembler/utils.js b/cocos/3d/ui/assembler/utils.js index e69ffdae82..05ab64cd8a 100644 --- a/cocos/3d/ui/assembler/utils.js +++ b/cocos/3d/ui/assembler/utils.js @@ -26,7 +26,11 @@ export function fillVertices(node, buffer, renderData, color) { vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; - uintbuf[vertexOffset++] = color; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; } } @@ -56,7 +60,11 @@ export function fillMeshVertices(node, buffer, renderData, color) { vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; - uintbuf[vertexOffset++] = color; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; } // fill indice data @@ -83,18 +91,22 @@ export function fillVertices3D(node, buffer, renderData, color) { uintbuf = buffer._uintVData; // let matrix = node._worldMatrix; - // node.getWorldMatrix(_worldMatrix); + node.getWorldMatrix(_worldMatrix); for (let i = 0; i < vertexCount; i++) { let vert = data[i]; vec3.set(vec3_temp, vert.x, vert.y, 0); - // vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); + vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); vbuf[vertexOffset++] = vec3_temp.x; vbuf[vertexOffset++] = vec3_temp.y; vbuf[vertexOffset++] = vec3_temp.z; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; - uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + // uintbuf[vertexOffset++] = color; } } @@ -114,18 +126,22 @@ export function fillMeshVertices3D(node, buffer, renderData, color) { ibuf = buffer._iData; // let matrix = node._worldMatrix; - // node.getWorldMatrix(_worldMatrix); + node.getWorldMatrix(_worldMatrix); for (let i = 0; i < vertexCount; i++) { let vert = data[i]; vec3.set(vec3_temp, vert.x, vert.y, 0); - // vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); + vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); vbuf[vertexOffset++] = vec3_temp.x; vbuf[vertexOffset++] = vec3_temp.y; vbuf[vertexOffset++] = vec3_temp.z; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; - uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; + // uintbuf[vertexOffset++] = color; } // fill indice data @@ -157,7 +173,11 @@ export function fillVerticesWithoutCalc(node, buffer, renderData, color) { vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; - uintbuf[vertexOffset++] = color; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; } } @@ -179,15 +199,10 @@ export function fillVerticesWithoutCalc3D(node, buffer, renderData, color) { vbuf[vertexOffset++] = vert.z; vbuf[vertexOffset++] = vert.u; vbuf[vertexOffset++] = vert.v; - uintbuf[vertexOffset++] = color; + // uintbuf[vertexOffset++] = color; + vbuf[vertexOffset++] = color.r; + vbuf[vertexOffset++] = color.g; + vbuf[vertexOffset++] = color.b; + vbuf[vertexOffset++] = color.a; } } - -// module.exports = { -// fillVertices: fillVertices, -// fillMeshVertices: fillMeshVertices, -// fillVertices3D: fillVertices3D, -// fillMeshVertices3D: fillMeshVertices3D, -// fillVerticesWithoutCalc: fillVerticesWithoutCalc, -// fillVerticesWithoutCalc3D: fillVerticesWithoutCalc3D -// }; diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts index d9a5c2b319..d68c5bf95c 100644 --- a/cocos/3d/ui/components/button-component.ts +++ b/cocos/3d/ui/components/button-component.ts @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import SpriteFrame from '../../../assets/CCSpriteFrame'; +import { SpriteFrame } from '../../../assets/CCSpriteFrame'; import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; @@ -33,7 +33,8 @@ import { lerp } from '../../../core/utils/misc'; import { Color, Vec3 } from '../../../core/value-types/index'; import * as math from '../../../core/vmath/index'; import { Node } from '../../../scene-graph'; -import SpriteComponent from './sprite-component'; +import { SpriteComponent } from './sprite-component'; +import { EventTouch } from '../../../core/platform/event-manager'; /** * !#en Enum for transition type. @@ -96,24 +97,24 @@ const Transition = cc.Enum({ * * 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):
* // 以下事件可以在全平台上都触发
- * -cc.NodeUI.EventType.TOUCH_START // 按下时事件
- * -cc.NodeUI.EventType.TOUCH_Move // 按住移动后事件
- * -cc.NodeUI.EventType.TOUCH_END // 按下后松开后事件
- * -cc.NodeUI.EventType.TOUCH_CANCEL // 按下取消事件
+ * -cc.Node.EventType.TOUCH_START // 按下时事件
+ * -cc.Node.EventType.TOUCH_Move // 按住移动后事件
+ * -cc.Node.EventType.TOUCH_END // 按下后松开后事件
+ * -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件
* // 以下事件只在 PC 平台上触发
- * -cc.NodeUI.EventType.MOUSE_DOWN // 鼠标按下时事件
- * -cc.NodeUI.EventType.MOUSE_MOVE // 鼠标按住移动后事件
- * -cc.NodeUI.EventType.MOUSE_ENTER // 鼠标进入目标事件
- * -cc.NodeUI.EventType.MOUSE_LEAVE // 鼠标离开目标事件
- * -cc.NodeUI.EventType.MOUSE_UP // 鼠标松开事件
- * -cc.NodeUI.EventType.MOUSE_WHEEL // 鼠标滚轮事件
+ * -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件
+ * -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件
+ * -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件
+ * -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件
+ * -cc.Node.EventType.MOUSE_UP // 鼠标松开事件
+ * -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件
* * @class Button * @extends Component * @example * * // Add an event to the button. - * button.node.on(cc.NodeUI.EventType.TOUCH_START, function (event) { + * button.node.on(cc.Node.EventType.TOUCH_START, function (event) { * cc.log("This is a callback after the trigger event"); * }); * // You could also add a click event @@ -451,13 +452,13 @@ export default class ButtonComponent extends Component { @property public _transition: number = Transition.NONE; @property - public _normalColor: Color = cc.color(214, 214, 214); + public _normalColor: Color = new Color(214, 214, 214); @property - public _hoverColor: Color = cc.color(211, 211, 211); + public _hoverColor: Color = new Color(211, 211, 211); @property - public _pressColor: Color = cc.Color.WHITE; + public _pressColor: Color = Color.WHITE; @property - public _disabledColor: Color = cc.color(124, 124, 124); + public _disabledColor: Color = new Color(124, 124, 124); @property public _normalSprite: SpriteFrame | null = null; @property @@ -465,7 +466,7 @@ export default class ButtonComponent extends Component { @property public _pressedSprite: SpriteFrame | null = null; @property - public _disabledSprite = null; + public _disabledSprite: SpriteFrame | null = null; @property public _duration: number = 0.1; @property @@ -477,13 +478,13 @@ export default class ButtonComponent extends Component { public _pressed: boolean = false; public _hovered: boolean = false; - public _fromColor: Color = cc.color(); - public _toColor: Color = cc.color(); + public _fromColor: Color = new Color(); + public _toColor: Color = new Color(); public _time: number = 0; public _transitionFinished: boolean = true; - public _fromScale: Vec3 = cc.v3(); - public _toScale: Vec3 = cc.v3(); - public _originalScale: Vec3 = cc.v3(); + public _fromScale: Vec3 = new Vec3(); + public _toScale: Vec3 = new Vec3(); + public _originalScale: Vec3 = new Vec3(); public _sprite: SpriteComponent | null = null; public _previousNormalSprite: SpriteFrame | null = null; @@ -535,11 +536,11 @@ export default class ButtonComponent extends Component { if (!CC_EDITOR) { this._registerEvent(); } else { - this.node.on('spriteframe-changed', function (comp) { + this.node.on('spriteframe-changed', (comp) => { if (this._transition === Transition.SPRITE) { this._normalSprite = comp.spriteFrame; } - }.bind(this)); + }, this); } } @@ -547,19 +548,19 @@ export default class ButtonComponent extends Component { this._resetState(); if (!CC_EDITOR) { - this.node.off(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMove, this); - this.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); - this.node.off(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancel, this); + this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this); + this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this); - this.node.off(cc.NodeUI.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); - this.node.off(cc.NodeUI.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); + this.node.off(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); + this.node.off(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); } else { this.node.off('spriteframe-changed'); } } - public update (dt) { + public update (dt: number) { const target = this._target; if (this._transitionFinished) { return; @@ -591,13 +592,13 @@ export default class ButtonComponent extends Component { } public _registerEvent () { - this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMove, this); - this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); - this.node.on(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancel, this); + this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this); + this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this); - this.node.on(cc.NodeUI.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); - this.node.on(cc.NodeUI.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); + this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this); + this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); } public _getTargetSprite (target: Node | null) { @@ -621,15 +622,23 @@ export default class ButtonComponent extends Component { this._pressed = true; this._updateState(); - event.stopPropagation(); + event && event.stopPropagation(); } public _onTouchMove (event: Event | null) { if (!this._interactable || !this.enabledInHierarchy || !this._pressed) { return; } // mobile phone will not emit _onMouseMoveOut, // so we have to do hit test when touch moving - const touch = event.touch; - const hit = this.node._hitTest(touch.getLocation()); + if (!event) { + return false; + } + + const touch = (event as EventTouch).touch; + if (!touch) { + return false; + } + + const hit = this.node.uiTransfromComp!.isHit(touch.getLocation()); if (this._transition === Transition.SCALE && this._target) { if (hit) { @@ -663,7 +672,7 @@ export default class ButtonComponent extends Component { } this._pressed = false; this._updateState(); - event.stopPropagation(); + event && event.stopPropagation(); } public _onTouchCancel () { diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts index a5f31b283b..71d9a1b5fb 100644 --- a/cocos/3d/ui/components/editbox/edit-box-component.ts +++ b/cocos/3d/ui/components/editbox/edit-box-component.ts @@ -25,16 +25,18 @@ ****************************************************************************/ import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../../core/data/class-decorator'; -import Component from '../../../../components/component'; +import { Component } from '../../../../components/component'; import Color from '../../../../core/value-types/color'; import macro from '../../../../core/platform/CCMacro'; -import EditBoxImpl from './edit-box-impl'; -import LabelComponent from '../label-component'; +import { EditBoxImpl} from './edit-box-impl'; +import { LabelComponent } from '../label-component'; // import { InputMode, InputFlag, KeyboardReturnType } from './types'; import * as Types from './types'; -import SpriteFrame from '../../../../assets/CCSpriteFrame'; +import { SpriteFrame } from '../../../../assets/CCSpriteFrame'; import ComponentEventHandler from '../../../../components/CCComponentEventHandler'; -import SpriteComponent from '../sprite-component'; +import { SpriteComponent } from '../sprite-component'; +import { UIRenderComponent } from '../ui-render-component'; +import { UITransformComponent } from '../ui-transfrom-component'; const InputMode = Types.InputMode; const InputFlag = Types.InputFlag; const KeyboardReturnType = Types.KeyboardReturnType; @@ -61,46 +63,69 @@ function capitalizeFirstLetter(string) { @executionOrder(100) @menu('UI/EditBox') @executeInEditMode -export default class EditBoxComponent extends Component { +export class EditBoxComponent extends Component { @property - _useOriginalSize: boolean = true; + _useOriginalSize = true; @property - _string: string = ''; + _string = ''; @property - _tabIndex: number = 0; + _tabIndex = 0; @property _backgroundImage: SpriteFrame | null = null; @property - _returnType: number = KeyboardReturnType.DEFAULT; + _returnType = KeyboardReturnType.DEFAULT; @property - _inputFlag: number = InputFlag.DEFAULT; + _inputFlag = InputFlag.DEFAULT; @property - _inputMode: number = InputMode.SINGLE_LINE; + _inputMode = InputMode.SINGLE_LINE; @property - _fontSize: number = 20; + _fontSize = 20; @property - _lineHeight: number = 40; + _lineHeight = 40; @property - _maxLength: number = 20; + _maxLength = 20; @property _fontColor: Color = Color.WHITE; @property - _placeholder: string = 'Enter text here...'; + _placeholder = 'Enter text here...'; @property - _placeholderFontSize: number = 20; + _placeholderFontSize = 20; @property _placeholderFontColor: Color = Color.GRAY; @property - _stayOnTop: boolean = false; + _stayOnTop = false; + /** + * !#en The event handler to be called when EditBox began to edit text. + * !#zh 开始编辑文本输入框触发的事件回调。 + * @property {Component.EventHandler[]} editingDidBegan + */ @property editingDidBegan: ComponentEventHandler[] = []; - @property - editingDidEnded: ComponentEventHandler[] = []; - @property - editingReturn: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when EditBox text changes. + * !#zh 编辑文本输入框时触发的事件回调。 + * @property {Component.EventHandler[]} textChanged + */ @property textChanged: ComponentEventHandler[] = []; + /** + * !#en The event handler to be called when EditBox edit ends. + * !#zh 结束编辑文本输入框时触发的事件回调。 + * @property {Component.EventHandler[]} editingDidEnded + */ + @property + editingDidEnded: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when return key is pressed. Windows is not supported. + * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 + * @property {Component.EventHandler[]} editingReturn + */ + @property + editingReturn: ComponentEventHandler[] = []; + _impl: EditBoxImpl | null = null; _textLabel: LabelComponent | null = null; _placeholderLabel: LabelComponent | null = null; @@ -116,7 +141,7 @@ export default class EditBoxComponent extends Component { return this._string; } - set string(value: string) { + set string(value) { if (this._maxLength >= 0 && value.length >= this._maxLength) { value = value.slice(0, this._maxLength); } @@ -165,7 +190,7 @@ export default class EditBoxComponent extends Component { return this._returnType; } - set returnType(value: number) { + set returnType(value) { this._returnType = value; if (this._impl) { this._impl.returnType = this._returnType; @@ -186,7 +211,7 @@ export default class EditBoxComponent extends Component { return this._inputFlag; } - set inputFlag(value: number) { + set inputFlag(value) { this._inputFlag = value; if (this._impl) { this._impl.setInputFlag(this._inputFlag); @@ -209,7 +234,7 @@ export default class EditBoxComponent extends Component { return this._inputMode; } - set inputMode(value: number) { + set inputMode(value) { this._inputMode = value; if (this._impl) { this._impl.setInputMode(this._inputMode); @@ -226,7 +251,7 @@ export default class EditBoxComponent extends Component { return this._fontSize; } - set fontSize(value: number) { + set fontSize(value) { if (this._fontSize === value) { return; } @@ -251,7 +276,7 @@ export default class EditBoxComponent extends Component { return this._lineHeight; } - set lineHeight(value: number) { + set lineHeight(value) { if (this._lineHeight === value) { return; } @@ -282,8 +307,11 @@ export default class EditBoxComponent extends Component { this._fontColor = value; if (this._textLabel) { - this._textLabel.node.opacity = this._fontColor.a; - this._textLabel.node.color = this._fontColor; + // this._textLabel.node.opacity = this._fontColor.a; + let renderComp = this._textLabel.node.getComponent(UIRenderComponent); + if (renderComp) { + renderComp.color = this._fontColor; + } } if (this._impl) { this._impl.setFontColor(this._fontColor); @@ -300,7 +328,7 @@ export default class EditBoxComponent extends Component { return this._placeholder; } - set placeholder(value: string) { + set placeholder(value) { if (this._placeholder === value) { return; } @@ -324,7 +352,7 @@ export default class EditBoxComponent extends Component { return this._placeholderFontSize; } - set placeholderFontSize(value: number) { + set placeholderFontSize(value) { if (this._placeholderFontSize === value) { return; } @@ -352,8 +380,11 @@ export default class EditBoxComponent extends Component { this._placeholderFontColor = value; if (this._placeholderLabel) { - this._placeholderLabel.node.color = this._placeholderFontColor; - this._placeholderLabel.node.opacity = this._placeholderFontColor.a; + let comp = this._placeholderLabel.node.getComponent(UIRenderComponent); + if (comp) { + comp.color = this._placeholderFontColor + }; + // this._placeholderLabel.node.opacity = this._placeholderFontColor.a; } } @@ -370,7 +401,7 @@ export default class EditBoxComponent extends Component { get maxLength() { return this._maxLength; } - set maxLength(value: number) { + set maxLength(value) { if (this._maxLength === value) { return } @@ -392,7 +423,7 @@ export default class EditBoxComponent extends Component { return this._stayOnTop; } - set stayOnTop(value: boolean) { + set stayOnTop(value) { this._stayOnTop = value; if (this._impl) { this._updateStayOnTop(); @@ -409,81 +440,13 @@ export default class EditBoxComponent extends Component { return this._tabIndex; } - set tabIndex(value: number) { + set tabIndex(value) { this._tabIndex = value; if (this._impl) { this._impl.setTabIndex(value); } } - /** - * !#en The event handler to be called when EditBox began to edit text. - * !#zh 开始编辑文本输入框触发的事件回调。 - * @property {Component.EventHandler[]} editingDidBegan - */ - // @property({ - // default: [], - // type: [ComponentEventHandler] - // }) - // get editingDidBegan() { - // return this._editingDidBegan; - // } - - // set editingDidBegan(value: ComponentEventHandler[]) { - // this._editingDidBegan = value; - // } - - /** - * !#en The event handler to be called when EditBox text changes. - * !#zh 编辑文本输入框时触发的事件回调。 - * @property {Component.EventHandler[]} textChanged - */ - // @property({ - // default: [], - // type: [ComponentEventHandler] - // }) - // get textChanged() { - // return this._textChanged; - // } - - // set textChanged(value: ComponentEventHandler[]) { - // this._textChanged = value; - // } - - /** - * !#en The event handler to be called when EditBox edit ends. - * !#zh 结束编辑文本输入框时触发的事件回调。 - * @property {Component.EventHandler[]} editingDidEnded - */ - // @property({ - // default: [], - // type: [ComponentEventHandler] - // }) - // get editingDidEnded() { - // return this._editingDidEnded; - // } - - // set editingDidEnded(value: ComponentEventHandler[]) { - // this._editingDidEnded = value; - // } - - /** - * !#en The event handler to be called when return key is pressed. Windows is not supported. - * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 - * @property {Component.EventHandler[]} editingReturn - */ - // @property({ - // default: [], - // type: [ComponentEventHandler] - // }) - // get editingReturn() { - // return this._editingReturn; - // } - - // set editingReturn(value: ComponentEventHandler[]) { - // this._editingReturn = value; - // } - static _EditBoxImpl = EditBoxImpl; static KeyboardReturnType = KeyboardReturnType; static InputFlag = InputFlag; @@ -498,13 +461,13 @@ export default class EditBoxComponent extends Component { } onDestroy() { - this._impl.clear(); + this._impl && this._impl.clear(); } _init() { this._createBackgroundSprite(); this._createLabels(); - this.node.on(cc.NodeUI.EventType.SIZE_CHANGED, this._resizeChildNodes, this); + this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this); let impl = this._impl = new EditBoxImpl(); @@ -532,8 +495,8 @@ export default class EditBoxComponent extends Component { } _registerEvent() { - this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); + this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } _updateStayOnTop() { @@ -543,17 +506,17 @@ export default class EditBoxComponent extends Component { else { this._showLabels(); } - this._impl.stayOnTop(this.stayOnTop); + this._impl && this._impl.stayOnTop(this.stayOnTop); } _syncSize() { let size = this.node.getContentSize(); - this._background.node.setAnchorPoint(this.node.getAnchorPoint()); - this._background.node.setContentSize(size); + this._background && this._background.node.setAnchorPoint(this.node.getAnchorPoint()); + this._background && this._background.node.setContentSize(size); this._updateLabelPosition(size); - this._impl.setSize(size.width, size.height); + this._impl && this._impl.setSize(size.width, size.height); } _updateLabelPosition(size) { @@ -563,25 +526,20 @@ export default class EditBoxComponent extends Component { let placeholderLabel = this._placeholderLabel; let textLabel = this._textLabel; - - textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); - placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); - placeholderLabel.lineHeight = size.height; - - placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); - textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height); - - if (this._inputMode === InputMode.ANY) { - placeholderLabel.verticalAlign = macro.VerticalTextAlignment.TOP; - placeholderLabel.enableWrapText = true; - textLabel.verticalAlign = macro.VerticalTextAlignment.TOP; - textLabel.enableWrapText = true; + if (textLabel) { + textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, textLabel.node.getPosition().z); + textLabel.verticalAlign = this._inputMode === InputMode.ANY ? macro.VerticalTextAlignment.TOP : macro.VerticalTextAlignment.CENTER; + textLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; } - else { - placeholderLabel.verticalAlign = macro.VerticalTextAlignment.CENTER; - placeholderLabel.enableWrapText = false; - textLabel.verticalAlign = macro.VerticalTextAlignment.CENTER; - textLabel.enableWrapText = false; + + if (placeholderLabel) { + placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); + placeholderLabel.lineHeight = size.height; + placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, placeholderLabel.node.getPosition().z); + placeholderLabel.verticalAlign = this._inputMode === InputMode.ANY ? + macro.VerticalTextAlignment.TOP : macro.VerticalTextAlignment.CENTER; + placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false; } } @@ -591,15 +549,16 @@ export default class EditBoxComponent extends Component { if (!this._background) { this._background = this.node.addComponent(cc.SpriteComponent); } - this._background.type = cc.SpriteComponent.Type.SLICED; + } - this._background.spriteFrame = this._backgroundImage; + this._background!.type = cc.SpriteComponent.Type.SLICED; + this._background!.spriteFrame = this._backgroundImage; // let background = this._background; // if (!background) { // let node = this.node.getChildByName('BACKGROUND_SPRITE'); // if (!node) { - // node = new cc.NodeUI('BACKGROUND_SPRITE'); + // node = new cc.Node('BACKGROUND_SPRITE'); // } // background = node.getComponent(cc.SpriteComponent); @@ -618,70 +577,84 @@ export default class EditBoxComponent extends Component { if (!this._textLabel) { let node = this.node.getChildByName('TEXT_LABEL'); if (!node) { - node = new cc.NodeUI('TEXT_LABEL'); + node = new cc.Node('TEXT_LABEL'); } - node.color = this._fontColor; - node.parent = this.node; - node.setAnchorPoint(0, 1); + let textLabel = node!.getComponent(LabelComponent); + node!.parent = this.node; - let textLabel = node.getComponent(LabelComponent); if (!textLabel) { - textLabel = node.addComponent(LabelComponent); + textLabel = node!.addComponent(LabelComponent); } - textLabel.overflow = LabelComponent.Overflow.CLAMP; - textLabel.fontSize = this._fontSize; - textLabel.lineHeight = this.lineHeight; + + let transformComp = node!.getComponent(UITransformComponent); + transformComp!.setAnchorPoint(0, 1); + textLabel!.color = this._fontColor; + textLabel!.overflow = LabelComponent.Overflow.CLAMP; + textLabel!.fontSize = this._fontSize; + textLabel!.lineHeight = this.lineHeight; this._textLabel = textLabel; } if (!this._placeholderLabel) { let node = this.node.getChildByName('PLACEHOLDER_LABEL'); if (!node) { - node = new cc.NodeUI('PLACEHOLDER_LABEL'); + node = new cc.Node('PLACEHOLDER_LABEL'); } - node.color = this._placeholderFontColor; - node.parent = this.node; - node.setAnchorPoint(0, 1); - - let placeholderLabel = node.getComponent(LabelComponent); + let placeholderLabel = node!.getComponent(LabelComponent); if (!placeholderLabel) { - placeholderLabel = node.addComponent(LabelComponent); + placeholderLabel = node!.addComponent(LabelComponent); } - placeholderLabel.overflow = LabelComponent.Overflow.CLAMP; - placeholderLabel.fontSize = this._placeholderFontSize; - placeholderLabel.string = this._placeholder; + let transform = node!.getComponent(UITransformComponent); + + node!.parent = this.node; + placeholderLabel!.color = this._placeholderFontColor; + transform!.setAnchorPoint(0, 1); + + + placeholderLabel!.overflow = LabelComponent.Overflow.CLAMP; + placeholderLabel!.fontSize = this._placeholderFontSize; + placeholderLabel!.string = this._placeholder; this._placeholderLabel = placeholderLabel; } } _resizeChildNodes() { - let textLabelNode = this._textLabel.node, - placeholderLabelNode = this._placeholderLabel.node, - backgroundNode = this._background.node; - - textLabelNode.x = -this.node.width / 2; - textLabelNode.y = this.node.height / 2; - textLabelNode.width = this.node.width; - textLabelNode.height = this.node.height; - - placeholderLabelNode.x = -this.node.width / 2; - placeholderLabelNode.y = this.node.height / 2; - placeholderLabelNode.width = this.node.width; - placeholderLabelNode.height = this.node.height; - - backgroundNode.width = this.node.width; - backgroundNode.height = this.node.height; + const textLabelNode = this._textLabel && this._textLabel.node; + if (textLabelNode) { + textLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, textLabelNode.getPosition().z); + textLabelNode.width = this.node.width; + textLabelNode.height = this.node.height; + } + const placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node; + if (placeholderLabelNode) { + placeholderLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, placeholderLabelNode.getPosition().z); + placeholderLabelNode.width = this.node.width; + placeholderLabelNode.height = this.node.height; + } + const backgroundNode = this._background && this._background.node; + if (backgroundNode) { + backgroundNode.width = this.node.width; + backgroundNode.height = this.node.height; + } } _showLabels() { - let displayText = this._textLabel.string; - this._textLabel.node.active = displayText !== ''; - this._placeholderLabel.node.active = displayText === ''; + if (this._textLabel) { + let displayText = this._textLabel.string; + this._textLabel.node.active = displayText !== ''; + if (this._placeholderLabel) { + this._placeholderLabel.node.active = displayText === ''; + } + } } _hideLabels() { - this._textLabel.node.active = false; - this._placeholderLabel.node.active = false; + if (this._textLabel) { + this._textLabel.node.active = false; + } + if (this._placeholderLabel) { + this._placeholderLabel.node.active = false; + } } _updateString(text) { @@ -697,13 +670,15 @@ export default class EditBoxComponent extends Component { } textLabel.string = displayText; - this._impl.setString(text); - if (!this._impl._editing && !this.stayOnTop) { - this._showLabels(); + if (this._impl) { + this._impl.setString(text); + if (!this._impl._editing && !this.stayOnTop) { + this._showLabels(); + } } } - _updateLabelStringStyle(text, ignorePassword) { + _updateLabelStringStyle(text: string, ignorePassword: boolean = false) { let inputFlag = this._inputFlag; if (!ignorePassword && inputFlag === InputFlag.PASSWORD) { let passwordString = ''; @@ -760,9 +735,9 @@ export default class EditBoxComponent extends Component { } _onTouchCancel(event) { - if (this._impl) { - this._impl._onTouchCancel(); - } + // if (this._impl) { + // this._impl._onTouchCancel(); + // } event.stopPropagation(); } diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts index 91c128f001..77d2fa9278 100644 --- a/cocos/3d/ui/components/editbox/edit-box-impl.ts +++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts @@ -34,7 +34,7 @@ import * as Types from './types'; import * as math from '../../../../core/vmath'; import { Size, Color } from '../../../../core/value-types'; import { Node } from '../../../../scene-graph'; -import EditBoxComponent from './edit-box-component'; +import { EditBoxComponent} from './edit-box-component'; const InputMode = Types.InputMode; const InputFlag = Types.InputFlag; const KeyboardReturnType = Types.KeyboardReturnType; @@ -81,25 +81,26 @@ function getKeyboardReturnType(type) { } @ccclass -export default class EditBoxImpl { +export class EditBoxImpl { _delegate: EditBoxComponent | null = null; - _inputMode: number = -1; - _inputFlag: number = -1; - _returnType: number = KeyboardReturnType.DEFAULT; - _maxLength: number = 50; - _text: string = ''; - _placeholderText: string = ''; - _alwaysOnTop: boolean = false; + _inputMode= -1; + _inputFlag= -1; + _returnType= KeyboardReturnType.DEFAULT; + _maxLength= 50; + _text = ''; + _placeholderText = ''; + _alwaysOnTop = false; _size: Size = cc.size(); _node: Node = null; - _editing: boolean = false; + _editing = false; __eventListeners: object = {}; - __fullscreen: boolean = false; - __autoResize: boolean = false; - __rotateScreen: boolean = false; + __fullscreen = false; + __autoResize = false; + __rotateScreen = false; __orientationChanged: Function | null = null; _edTxt: HTMLElement | null = null; _textColor: Color = Color.WHITE; + _edFontSize = 14; onEnable() { if (!this._edTxt) { @@ -271,7 +272,7 @@ export default class EditBoxImpl { let self = this; function startFocus() { - self._edTxt.focus(); + self._edTxt!.focus(); } if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { @@ -319,7 +320,7 @@ export default class EditBoxImpl { if (!edTxt) return; if (this._inputFlag === InputFlag.PASSWORD) { - edTxt.type = 'password'; + edTxt!.type = 'password'; return; } @@ -367,7 +368,7 @@ export default class EditBoxImpl { math.mat4.translate(_matrix, _matrix, _vec3); - let camera; + // let camera; // can't find camera in editor // if (CC_EDITOR) { // camera = cc.Camera.main; @@ -379,7 +380,8 @@ export default class EditBoxImpl { if (!renderComp) { return false; } - let canvas = cc.CanvasComponent.findView(renderComp); + // let canvas = cc.CanvasComponent.findView(renderComp); + let canvas = cc.director.root.ui.getScreen() if (!canvas) { return; } @@ -532,7 +534,7 @@ export default class EditBoxImpl { tmpEdTxt.type = 'text'; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = 0; + tmpEdTxt.style.border = '0'; tmpEdTxt.style.background = 'transparent'; tmpEdTxt.style.width = '100%'; tmpEdTxt.style.height = '100%'; @@ -597,7 +599,7 @@ function _inputValueHandle(input, editBoxImpl) { } } -function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea: boolean = false) { +function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) { let inputLock = false; let cbs = editBoxImpl.__eventListeners; cbs.compositionstart = function () { diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/3d/ui/components/progress-bar-component.ts index d8a6bffb2d..d7607d785a 100644 --- a/cocos/3d/ui/components/progress-bar-component.ts +++ b/cocos/3d/ui/components/progress-bar-component.ts @@ -27,7 +27,7 @@ import { Component} from '../../../components/component'; import { clamp01 } from '../../../core/utils/misc'; import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; -import SpriteComponent from './sprite-component'; +import { SpriteComponent } from './sprite-component'; /** @@ -83,7 +83,7 @@ var Mode = cc.Enum({ @executionOrder(100) @menu('UI/ProgressBar') // @executeInEditMode -export default class ProgressBarComponent extends Component { +export class ProgressBarComponent extends Component { @property _barSprite: SpriteComponent | null = null; @property @@ -300,7 +300,7 @@ export default class ProgressBarComponent extends Component { var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; var finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); - entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y); + entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entity.getPosition().z); entity.setAnchorPoint(anchorPoint); entity.setContentSize(finalContentSize); diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index a981d1fb63..fca5e176d5 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -27,11 +27,12 @@ import { Component} from '../../../components/component'; import { clamp01 } from '../../../core/utils/misc'; import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; -import SpriteComponent from './sprite-component'; +import { SpriteComponent} from './sprite-component'; import { Vec2 } from '../../../core/value-types/index'; import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import Event from '../../../core/event/event'; import { EventTouch } from '../../../core/platform/event-manager/CCEvent'; +import { UITransformComponent } from './ui-transfrom-component'; /** * !#en The Slider Direction * !#zh 滑动器方向 @@ -62,7 +63,7 @@ var Direction = cc.Enum({ @executionOrder(100) @menu('UI/Slider') // @executeInEditMode -export default class SliderComponent extends Component { +export class SliderComponent extends Component { @property _handle: SpriteComponent | null = null; @property @@ -72,7 +73,7 @@ export default class SliderComponent extends Component { @property _slideEvents: ComponentEventHandler[] = []; - _offset: Vec2 = cc.v2(); + _offset: Vec2 = new Vec2(); _dragging = false; _touchHandle = false; @@ -186,38 +187,42 @@ export default class SliderComponent extends Component { } } - _onHandleDragStart(event: Event | null) { + _onHandleDragStart(event: Event) { + if (!event){ + return; + } + this._dragging = true; this._touchHandle = true; - this._offset = this._handle.node.convertToNodeSpaceAR(event.touch.getLocation()); + this._offset = this._handle && this._handle.node.uiTransfromComp && this._handle.node.uiTransfromComp.convertToNodeSpaceAR((event as EventTouch).touch.getLocation()); event.stopPropagation(); } - _onTouchBegan(event: Event | null) { + _onTouchBegan(event: Event) { if (!this._handle) { return; } this._dragging = true; if (!this._touchHandle) { - this._handleSliderLogic(event.touch); + this._handleSliderLogic((event as EventTouch).touch); } event.stopPropagation(); } - _onTouchMoved(event: Event | null) { + _onTouchMoved(event: Event) { if (!this._dragging) { return; } - this._handleSliderLogic(event.touch); + this._handleSliderLogic((event as EventTouch).touch); event.stopPropagation(); } - _onTouchEnded(event: Event | null) { + _onTouchEnded(event: Event) { this._dragging = false; this._touchHandle = false; this._offset = cc.v2(); event.stopPropagation(); } - _onTouchCancelled(event: Event | null) { + _onTouchCancelled(event: Event) { this._dragging = false; event.stopPropagation(); } @@ -232,9 +237,9 @@ export default class SliderComponent extends Component { this.node.emit('slide', this); } - _updateProgress(touch: EventTouch | null) { + _updateProgress(touch: EventTouch) { if (!this._handle) { return; } - var localTouchPos = this.node.convertToNodeSpaceAR(touch.getLocation()); + var localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR((touch as EventTouch).getLocation()); if (this.direction === Direction.Horizontal) { this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width); } @@ -252,8 +257,11 @@ export default class SliderComponent extends Component { else { handlelocalPos = cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height); } - var worldSpacePos = this.node.convertToWorldSpaceAR(handlelocalPos); - this._handle.node.setPosition(this._handle.node.parent.convertToNodeSpaceAR(worldSpacePos)); + var worldSpacePos = this.node.uiTransfromComp!.convertToWorldSpaceAR(handlelocalPos); + let transform: UITransformComponent | null = this._handle.node.parent && this._handle.node.parent.getComponent(cc.UITransformComponent); + if(transform){ + this._handle.node.setPosition(transform.convertToNodeSpaceAR(worldSpacePos)); + } } } diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index c3c5d71b48..8f87d3888d 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -32,6 +32,7 @@ import { Vec2, Enum } from '../../../core/value-types'; import { MeshBuffer } from '../mesh-buffer'; import { UIRenderComponent } from './ui-render-component'; import { Node } from '../../../scene-graph/node'; +import { UI } from '../../../renderer/ui/ui'; const EventType = Node.EventType; /** @@ -399,11 +400,11 @@ export class SpriteComponent extends UIRenderComponent { // this.node.on(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this); } - public updateAssembler (buffer: MeshBuffer) { + public updateAssembler (render: UI) { if (!this._spriteFrame || !this.material) { return; } - super.updateAssembler(buffer); + super.updateAssembler(render); } public onDestroy () { diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/3d/ui/components/toggle-component.ts index 464d4a2c97..d6a5ead1ed 100644 --- a/cocos/3d/ui/components/toggle-component.ts +++ b/cocos/3d/ui/components/toggle-component.ts @@ -26,10 +26,8 @@ import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import ButtonComponent from './button-component'; -// import * as js from '../../core/utils/js'; -import RenderComponent from './render-component'; -import SpriteComponent from './sprite-component'; -import ToggleGroupComponent from './toggle-group-component'; +import { SpriteComponent} from './sprite-component'; +import { ToggleGroupComponent} from './toggle-group-component'; /** * !#en The toggle component is a CheckBox, when it used together with a ToggleGroup, it @@ -42,7 +40,7 @@ import ToggleGroupComponent from './toggle-group-component'; @executionOrder(100) @menu('UI/Toggle') @executeInEditMode -export default class ToggleComponent extends ButtonComponent { +export class ToggleComponent extends ButtonComponent { @property public _isChecked: boolean = true; @property diff --git a/cocos/3d/ui/components/toggle-container-component.ts b/cocos/3d/ui/components/toggle-container-component.ts index 2a0f400d8e..0df82c396e 100644 --- a/cocos/3d/ui/components/toggle-container-component.ts +++ b/cocos/3d/ui/components/toggle-container-component.ts @@ -39,7 +39,7 @@ import { Component } from '../../../components/component'; import { ccclass, executeInEditMode, menu, property } from '../../../core/data/class-decorator'; @ccclass('cc.ToggleContainerComponent') -export default class ToggleContainerComponent extends Component { +export class ToggleContainerComponent extends Component { @property protected _allowSwitchOff = false; @property diff --git a/cocos/3d/ui/components/toggle-group-component.ts b/cocos/3d/ui/components/toggle-group-component.ts index abea49b12c..e27de57a10 100644 --- a/cocos/3d/ui/components/toggle-group-component.ts +++ b/cocos/3d/ui/components/toggle-group-component.ts @@ -25,7 +25,7 @@ ****************************************************************************/ import { Component} from '../../../components/component'; import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; -import ToggleComponent from './toggle-component'; +import { ToggleComponent} from './toggle-component'; /** * !#en ToggleGroup is not a visiable UI component but a way to modify the behavior of a set of Toggles. @@ -40,7 +40,7 @@ import ToggleComponent from './toggle-component'; @executionOrder(100) @menu('UI/ToggleGroup') @executeInEditMode -export default class ToggleGroupComponent extends Component { +export class ToggleGroupComponent extends Component { @property _allowSwitchOff: boolean = false; _toggleItems: ToggleComponent[] = []; diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index 17d6fc53db..ddbb45116d 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -268,8 +268,6 @@ export class UIRenderComponent extends RenderableComponent { this._assembler.updateRenderData(this); } this._assembler.fillBuffers(this, render); - - return this._assembler.getRenderBuffers(); } public postUpdateAssembler () { diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index 193e1c686b..aa94af48ca 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -1,10 +1,10 @@ import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import Event from '../../../core/platform/event-manager/CCEvent.js'; import Size from '../../../core/value-types/size'; import Vec2 from '../../../core/value-types/vec2'; import * as math from '../../../core/vmath/index'; -import { Enum } from '../../../core/value-types'; +import { Enum, Mat4 } from '../../../core/value-types'; +import Event from '../../../core/event/event'; const _vec2a = cc.v2(); const _vec2b = cc.v2(); @@ -145,10 +145,11 @@ export class UITransformComponent extends Component { * node.setContentSize(cc.size(100, 100)); * node.setContentSize(100, 100); */ - public setContentSize (size: Size, height: number) { + public setContentSize (size: Size|number, height?: number) { const locContentSize = this._contentSize; // var clone; if (height === undefined) { + size = size as Size; if ((size.width === locContentSize.width) && (size.height === locContentSize.height)) { return; } @@ -197,9 +198,10 @@ export class UITransformComponent extends Component { * node.setAnchorPoint(cc.v2(1, 1)); * node.setAnchorPoint(1, 1); */ - public setAnchorPoint (point: Vec2, y: number) { + public setAnchorPoint (point: Vec2 | number, y?: number) { const locAnchorPoint = this._anchorPoint; if (y === undefined) { + point = point as Vec2; if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y)) { return; } @@ -218,7 +220,7 @@ export class UITransformComponent extends Component { // } } - public isHit (point: Vec2, listener: Event) { + public isHit (point: Vec2, listener: Event|null = null) { const w = this._contentSize.width; const h = this._contentSize.height; const cameraPt = _vec2a; @@ -271,7 +273,7 @@ export class UITransformComponent extends Component { // find mask parent, should hit test it if (parent === mask.node) { const comp = parent.getComponent(cc.Mask); - return (comp && comp.enabledInHierarchy) ? comp._hitTest(cameraPt) : true; + return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true; } else { listener.mask = null; return true; @@ -283,4 +285,40 @@ export class UITransformComponent extends Component { return false; } } + + /** + * !#en + * Converts a Point to node (local) space coordinates in which the anchor point is the origin position. + * !#zh + * 将一个点转换到节点 (局部) 空间坐标系,这个坐标系以锚点为原点。 + * @method convertToNodeSpaceAR + * @param {Vec2} worldPoint + * @return {Vec2} + * @example + * var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); + */ + convertToNodeSpaceAR(worldPoint) { + let matrix = new Mat4(); + this.node.getWorldMatrix(matrix); + math.mat4.invert(_mat4_temp, matrix); + let out = new cc.Vec2(); + return math.vec2.transformMat4(out, worldPoint, _mat4_temp); + } + + /** + * !#en + * Converts a Point in node coordinates to world space coordinates. + * !#zh + * 将节点坐标系下的一个点转换到世界空间坐标系。 + * @method convertToWorldSpaceAR + * @param {Vec2} nodePoint + * @return {Vec2} + * @example + * var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); + */ + convertToWorldSpaceAR(nodePoint) { + this.node.getWorldMatrix(_worldMatrix); + let out = new cc.Vec2(); + return math.vec2.transformMat4(out, nodePoint, _worldMatrix); + } } diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts index 4dd2fa3be0..db84548763 100644 --- a/cocos/3d/ui/mesh-buffer.ts +++ b/cocos/3d/ui/mesh-buffer.ts @@ -80,6 +80,13 @@ export class MeshBuffer { this._vertexBytes = this.calculateBytes(this._vertexFormat); this._initVDataCount = data.vertexCount * this._vertexBytes; this._initIDataCount = data.indiceCount; + this.primitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; + this.byteOffset = 0; + this.byteStart = 0; + this.indiceStart = 0; + this.indiceOffset = 0; + this.vertexStart = 0; + this.vertexOffset = 0; this._reallocBuffer(); } @@ -143,35 +150,45 @@ export class MeshBuffer { } public _reallocVData (copyOldData) { - let oldVData; - if (this.vData) { - oldVData = new Uint8Array(this.vData.buffer); + // let oldVData; + // if (this.vData) { + // if (this._initVDataCount * 4 > this.vData.byteLength){ + // oldVData = new Uint8Array(this.vData.buffer); + // } + // } + + if (this.vData && this.vData.byteLength === this._initVDataCount){ + return; } this.vData = new Float32Array(this._initVDataCount); // this.uintVData = new Uint32Array(this.vData.buffer); - const newData = new Uint8Array(this.vData.buffer); + // const newData = new Uint8Array(this.vData.buffer); - if (oldVData && copyOldData) { - for (let i = 0, l = oldVData.length; i < l; i++) { - newData[i] = oldVData[i]; - } - } + // if (oldVData && copyOldData) { + // for (let i = 0, l = oldVData.length; i < l; i++) { + // newData[i] = oldVData[i]; + // } + // } // this._vb._bytes = this.vData.byteLength; } public _reallocIData (copyOldData) { - const oldIData = this.iData; + // const oldIData = this.iData; + + if (this.iData && this.iData.byteLength === this._initIDataCount) { + return; + } this.iData = new Uint16Array(this._initIDataCount); - if (oldIData && copyOldData) { - const iData = this.iData; - for (let i = 0, l = oldIData.length; i < l; i++) { - iData[i] = oldIData[i]; - } - } + // if (oldIData && copyOldData) { + // const iData = this.iData; + // for (let i = 0, l = oldIData.length; i < l; i++) { + // iData[i] = oldIData[i]; + // } + // } // this._ib._bytes = this.iData.byteLength; } diff --git a/cocos/assets/CCSpriteFrame.ts b/cocos/assets/CCSpriteFrame.ts index f0a2764060..92f43670e0 100644 --- a/cocos/assets/CCSpriteFrame.ts +++ b/cocos/assets/CCSpriteFrame.ts @@ -234,8 +234,8 @@ export class SpriteFrame extends Texture2D { this._capInsets[INSET_BOTTOM] = 0; this._capInsets[INSET_LEFT] = 0; - this._capInsets[INSET_RIGHT] = 1; - this._capInsets[INSET_TOP] = 1; + this._capInsets[INSET_RIGHT] = 0; + this._capInsets[INSET_TOP] = 0; if (CC_EDITOR) { // Atlas asset uuid diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index ac6c50032c..c2e80a3e0d 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -59,7 +59,7 @@ export class UI { }, 128); private _screens: CanvasComponent[] = []; - private _bufferPool: RecyclePool = new RecyclePool(() => { + private _bufferPool: RecyclePool = new RecyclePool(() => { return new MeshBuffer(); }, 128); private _device: GFXDevice; From 6be45e5bfb5a69b61a60ef090366b41cece83528 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 21 Jan 2019 18:48:32 +0800 Subject: [PATCH 197/267] bug reproduce --- cocos/3d/framework/model-component.js | 3 ++- cocos/pipeline/render-pipeline.ts | 2 +- playground/gizmo.html | 12 ++++++------ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index e5209b81d9..2b2114a467 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -168,12 +168,13 @@ export class ModelComponent extends RenderableComponent { } onEnable() { - this._updateModels(); + this._updateModels(true); this._updateCastShadow(); this._updateReceiveShadow(); } onDisable() { + this._getRenderScene().destroyModel(this._model); } onDestroy() { diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 38236e63f7..b8f734147c 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -352,7 +352,7 @@ export abstract class RenderPipeline { // filter model by view visibility if (view.visibility > 0 && model.viewID !== view.visibility || !model.isEnable() || - !model.node.active) { + !model.node.activeInHierarchy) { continue; } diff --git a/playground/gizmo.html b/playground/gizmo.html index 300b5094f4..35cd8a4dca 100644 --- a/playground/gizmo.html +++ b/playground/gizmo.html @@ -117,11 +117,11 @@ const moveTool = new cc.Node('moveTool'); moveTool.parent = scene; createArrow(cc.Color.RED, quat.fromEuler(cc.quat(), 90, 0, 0)).parent = moveTool; - createArrow(cc.Color.GREEN, quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; - createArrow(cc.Color.BLUE, quat.fromEuler(cc.quat(), 0, 0, -90)).parent = moveTool; - createBorderPlane(cc.Color.RED, cc.v3(0.5, 0.5, 0), quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; - createBorderPlane(cc.Color.GREEN, cc.v3(0.5, 0, 0.5), quat.fromEuler(cc.quat(), -90, -90, 0)).parent = moveTool; - createBorderPlane(cc.Color.BLUE, cc.v3(0, 0.5, 0.5), quat.fromEuler(cc.quat(), 90, 0, 90)).parent = moveTool; + // createArrow(cc.Color.GREEN, quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; + // createArrow(cc.Color.BLUE, quat.fromEuler(cc.quat(), 0, 0, -90)).parent = moveTool; + // createBorderPlane(cc.Color.RED, cc.v3(0.5, 0.5, 0), quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; + // createBorderPlane(cc.Color.GREEN, cc.v3(0.5, 0, 0.5), quat.fromEuler(cc.quat(), -90, -90, 0)).parent = moveTool; + // createBorderPlane(cc.Color.BLUE, cc.v3(0, 0.5, 0.5), quat.fromEuler(cc.quat(), 90, 0, 90)).parent = moveTool; let vel = cc.v3(), speed = 0.1; canv.addEventListener('keydown', (e) => { @@ -139,11 +139,11 @@ else if (e.key === 'l') vel.x = 0; else if (e.key === 'o') vel.y = 0; else if (e.key === 'u') vel.y = 0; + else if (e.key === 'r') moveTool.active = !moveTool.active; }); cc.director.on(cc.Director.EVENT_AFTER_UPDATE, () => { moveTool.setPosition(vec3.add(moveTool._lpos, moveTool._lpos, vel)); }); - setInterval(()=> moveTool.active = !moveTool.active, 1000); cc.director.runSceneImmediate(scene); } From 30eaccc20fa2fa72ade49a7ec7571bb0c77dde1d Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 18:51:08 +0800 Subject: [PATCH 198/267] commit files --- cocos/pipeline/render-pipeline.ts | 18 ++++++++---------- cocos/renderer/scene/camera.ts | 5 ++++- cocos/scene-graph/base-node.ts | 9 ++++----- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 38236e63f7..89dd1e1055 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -290,8 +290,6 @@ export abstract class RenderPipeline { } protected updateUBOs (view: RenderView) { - const camera = view.camera as Camera; - camera.update(); // update UBOGlobal _vec4Array[0] = this._root.frameTime; @@ -312,27 +310,27 @@ export abstract class RenderPipeline { _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SCALE_OFFSET); - mat4.array(_mat4Array, camera.matView); + mat4.array(_mat4Array, view.camera.matView); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_OFFSET); - mat4.invert(_outMat, camera.matView); + mat4.invert(_outMat, view.camera.matView); mat4.array(_mat4Array, _outMat); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_INV_OFFSET); - mat4.array(_mat4Array, camera.matProj); + mat4.array(_mat4Array, view.camera.matProj); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_OFFSET); - mat4.invert(_outMat, camera.matProj); + mat4.invert(_outMat, view.camera.matProj); mat4.array(_mat4Array, _outMat); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_INV_OFFSET); - mat4.array(_mat4Array, camera.matViewProj); + mat4.array(_mat4Array, view.camera.matViewProj); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_OFFSET); - mat4.array(_mat4Array, camera.matViewProjInv); + mat4.array(_mat4Array, view.camera.matViewProjInv); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); - vec3.array(_vec4Array, camera.node && camera.node.getPosition()); + vec3.array(_vec4Array, view.camera.node && view.camera.node.getPosition()); _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); @@ -352,7 +350,7 @@ export abstract class RenderPipeline { // filter model by view visibility if (view.visibility > 0 && model.viewID !== view.visibility || !model.isEnable() || - !model.node.active) { + !model.node.activeInHierarchy) { continue; } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index b1b725491a..b156a383ba 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -99,7 +99,10 @@ export class Camera { } public update () { - if (!this._node) { return; } + if (!this._node) { + return; + } + // view matrix this.node.getWorldRT(this._matView); mat4.invert(this._matView, this._matView); diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index f3e4d2e613..f6d5fa4aca 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -184,15 +184,14 @@ export class BaseNode extends CCObject { get active () { return this._active; } - set active (value) { - value = !!value; - if (this._active !== value) { - this._active = value; + set active (isActive: boolean) { + if (this._active !== isActive) { + this._active = isActive; const parent = this._parent; if (parent) { const couldActiveInScene = parent._activeInHierarchy; if (couldActiveInScene) { - cc.director._nodeActivator.activateNode(this, value); + cc.director._nodeActivator.activateNode(this, isActive); } } } From 0d60055707a32afa37ac09caf8f2614eaf5cddd4 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 19:59:07 +0800 Subject: [PATCH 199/267] fix bug --- cocos/pipeline/render-queue.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index 6a6b1078f9..eb9c5178cf 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -64,24 +64,25 @@ export class RenderQueue { for (let i = 0; i < model.subModelNum; ++i) { const subModel = model.getSubModel(i); - for (const pso of subModel.psos) { + for (let p = 0; p < subModel.psos.length; ++p) { + const pso = subModel.psos[p]; const isTransparent = pso.blendState.targets[0].blend; // TODO: model priority if (!isTransparent) { - const hash = (0 << 30) | i; + const hash = (0 << 30) | p; this.opaques.push({ hash, depth, shaderId: pso.shader.id, - subModel, cmdBuff: subModel.commandBuffers[i]}); + subModel, cmdBuff: subModel.commandBuffers[p]}); } else { - const hash = (1 << 30) | i; + const hash = (1 << 30) | p; this.transparents.push({ hash, depth, shaderId: pso.shader.id, - subModel, cmdBuff: subModel.commandBuffers[i]}); + subModel, cmdBuff: subModel.commandBuffers[p]}); } } } From 87df5e9be730840ede37e9005e62e430fc9b31d9 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 21:26:40 +0800 Subject: [PATCH 200/267] fix command pool bug --- cocos/3d/framework/model-component.js | 1 - cocos/core/memop/cached-array.ts | 2 +- cocos/gfx/webgl/webgl-command-allocator.ts | 58 +++++++++++++--------- cocos/renderer/ui/ui.ts | 13 +++++ 4 files changed, 48 insertions(+), 26 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 2b2114a467..b3be42b7eb 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -174,7 +174,6 @@ export class ModelComponent extends RenderableComponent { } onDisable() { - this._getRenderScene().destroyModel(this._model); } onDestroy() { diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index de18948305..2388d0bba8 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -35,7 +35,7 @@ export class CachedArray { for (let i = 0; i < this._capacity; ++i) { this.array[i] = temp[i]; } - this._capacity = length; + this._capacity = this.length; } this.array[this.length++] = item; diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 7138306483..ce05a34e62 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -11,41 +11,51 @@ import { export class WebGLGFXCommandPool { - private _frees: Array; - private _freeIdx: number = 0; + private _count = 0; + private _data: T[]; + private _objIdx: Map; constructor (clazz: new() => T, count: number) { - this._frees = new Array(count); + this._data = new Array(count); + this._objIdx = new Map(); + for (let i = 0; i < count; ++i) { - this._frees[i] = new clazz(); + this._data[i] = new clazz(); + this._objIdx.set(this._data[i], i); } - - this._freeIdx = count - 1; } - public alloc (clazz: new() => T): T | null { - - if (this._freeIdx < 0) { - const size = this._frees.length * 2; - const temp = this._frees; - this._frees = new Array(size); - - const increase = size - temp.length; - for (let i = 0; i < increase; ++i) { - this._frees[i] = new clazz(); + public alloc (clazz: new() => T): T { + if (this._count >= this._data.length) { + if (this._data.length * 2 > this._data.length) { + for (let i = this._data.length; i < this._data.length * 2; ++i) { + this._data[i] = new clazz(); + } } - - this._freeIdx += increase; } - const item = this._frees[this._freeIdx]; - this._frees[this._freeIdx--] = null; - - return item; + return this._data[this._count++]; } - public free (cmd: T) { - this._frees[++this._freeIdx] = cmd; + public freeAt (idx: number) { + if (idx >= this._count) { + return; + } + + const last = this._count - 1; + 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 free (obj: T) { + const idx = this._objIdx.get(obj); + if (idx !== undefined) { + this.freeAt(idx); + } } } diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index c2e80a3e0d..19c9e0b108 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -264,6 +264,19 @@ export class UI { } private render () { + /* + const framebuffer = this._root.curWindow!.framebuffer; + const cmdBuff = this._cmdBuff!; + + cmdBuff.begin(); + cmdBuff.beginRenderPass(framebuffer, this._renderArea, + [{r: 1, g: 1, b: 1, a: 1}], 1.0, 0); + + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + */ + if (this._items.length) { const framebuffer = this._root.curWindow!.framebuffer; const cmdBuff = this._cmdBuff!; From d605c486ddb37cbba4e47389a65aa8401efc90b4 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 21:48:36 +0800 Subject: [PATCH 201/267] fix command pool --- cocos/gfx/webgl/webgl-command-allocator.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index ce05a34e62..4f2e4008c5 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -27,10 +27,9 @@ export class WebGLGFXCommandPool { public alloc (clazz: new() => T): T { if (this._count >= this._data.length) { - if (this._data.length * 2 > this._data.length) { - for (let i = this._data.length; i < this._data.length * 2; ++i) { - this._data[i] = new clazz(); - } + const size = this._data.length * 2; + for (let i = this._data.length; i < size; ++i) { + this._data[i] = new clazz(); } } From 74fe021641eb681acb1c89531653e95c7a236593 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 21 Jan 2019 21:26:51 +0800 Subject: [PATCH 202/267] misc fix --- cocos/3d/assets/mesh.ts | 10 ++--- cocos/3d/framework/animation-component.js | 10 +++-- .../framework/physics/collider-component.ts | 40 ++++++++++--------- .../framework/physics/rigid-body-component.ts | 34 ++++++++-------- cocos/3d/framework/renderable-component.ts | 5 ++- cocos/assets/CCScripts.js | 2 +- cocos/components/component.js | 3 +- cocos/core/platform/CCSys.js | 11 +++-- cocos/load-pipeline/audio-downloader.js | 4 +- playground/gizmo.html | 8 ++-- 10 files changed, 70 insertions(+), 57 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 553632a416..a6135dc2d5 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -374,7 +374,10 @@ export class Mesh extends Asset { } @property - private _struct: IMeshStruct; + private _struct: IMeshStruct = { + vertexBundles: [], + primitives: [], + }; private _data: Uint8Array | null = null; @@ -384,11 +387,6 @@ export class Mesh extends Asset { constructor () { super(); - - this._struct = { - vertexBundles: [], - primitives: [], - }; } /** diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js index 84ab6a847b..e14eefd7e3 100644 --- a/cocos/3d/framework/animation-component.js +++ b/cocos/3d/framework/animation-component.js @@ -308,7 +308,7 @@ export default class AnimationComponent extends Component { /** * @type {AnimationClip[]} */ - @property + @property({ type: [AnimationClip] }) _clips = []; /** @@ -318,7 +318,7 @@ export default class AnimationComponent extends Component { * @property currentClip * @type {AnimationClip} */ - @property({type:AnimationClip}) + @property({ type:AnimationClip }) currentClip = null; /** @@ -333,7 +333,7 @@ export default class AnimationComponent extends Component { _preview = false; - @property({type: Boolean}) + @property({ type: Boolean }) get preview() { return this._preview; } @@ -383,7 +383,9 @@ export default class AnimationComponent extends Component { * @property clips * @type {AnimationClip[]} */ - @property([AnimationClip]) + @property({ + type: [AnimationClip], + }) get clips() { return this._clips; } diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts index 132ecd0508..25762d8f0e 100644 --- a/cocos/3d/framework/physics/collider-component.ts +++ b/cocos/3d/framework/physics/collider-component.ts @@ -4,7 +4,7 @@ import { executeInEditMode, executionOrder, menu, - property + property, } from '../../../core/data/class-decorator'; import Vec3 from '../../../core/value-types/vec3'; import { PhysicsBoxShape, PhysicsShape, PhysicsSphereShape } from './body'; @@ -17,37 +17,39 @@ export class ColliderComponentBase extends PhysicsBasedComponent { @property private _center: Vec3 = new cc.Vec3(0, 0, 0); - constructor(shape: PhysicsShape) { + constructor (shape: PhysicsShape) { super(); this._center = new Vec3(0, 0, 0); this._shape = shape; } - public get body() { + public get body () { return this._body; } - public onLoad() { + public onLoad () { super.onLoad(); this.center = this._center; } - public onEnable() { + public onEnable () { super.onEnable(); this._body!.addShape(this._shape); } - public onDisable() { + public onDisable () { super.onDisable(); this._body!.removeShape(this._shape); } - @property(Vec3) - get center() { + @property({ + type: Vec3, + }) + get center () { return this._center; } - set center(value: Vec3) { + set center (value: Vec3) { this._center = new Vec3(value.x, value.y, value.z); this._shape.center = value; } @@ -61,24 +63,26 @@ export class BoxColliderComponent extends ColliderComponentBase { @property private _size: Vec3 = new Vec3(0, 0, 0); - constructor() { + constructor () { super(new PhysicsBoxShape(new Vec3(0, 0, 0))); } - public onLoad() { + public onLoad () { super.onLoad(); this.size = this._size; } - @property(Vec3) - get size() { + @property({ + type: Vec3, + }) + get size () { return this._size; } /** * Note, shall not specify size with component 0 */ - set size(value) { + set size (value) { this._size = value; (this._shape as PhysicsBoxShape).size = this._size; if (this._body) { @@ -95,21 +99,21 @@ export class SphereColliderComponent extends ColliderComponentBase { @property private _radius: number = 0; - constructor() { + constructor () { super(new PhysicsSphereShape(0)); } - public onLoad() { + public onLoad () { super.onLoad(); this.radius = this._radius; } @property - get radius() { + get radius () { return this._radius; } - set radius(value) { + set radius (value) { this._radius = value; (this._shape as PhysicsSphereShape).radius = value; if (this._body) { diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 37309ba6aa..5ca06ed783 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -4,7 +4,7 @@ import { executeInEditMode, executionOrder, menu, - property + property, } from '../../../core/data/class-decorator'; import { PhysicsMaterial } from '../../assets/physics/material'; import { PhysicsBasedComponent } from './detail/physics-based-component'; @@ -26,38 +26,40 @@ export class RigidBodyComponent extends PhysicsBasedComponent { @property private _angularDamping: number = NonRigidBodyProperties.angularDamping; - constructor() { + constructor () { super(); } - public get body() { + public get body () { return this._body; } - public onLoad() { + public onLoad () { super.onLoad(); } - public onEnable() { + public onEnable () { super.onEnable(); this.mass = this._mass; this.linearDamping = this._linearDamping; this.angularDamping = this._angularDamping; } - public onDisable() { + public onDisable () { super.onDisable(); this.mass = NonRigidBodyProperties.mass; this.linearDamping = NonRigidBodyProperties.linearDamping; this.angularDamping = NonRigidBodyProperties.angularDamping; } - @property(PhysicsMaterial) - get material() { + @property({ + type: PhysicsMaterial, + }) + get material () { return this._material; } - set material(value) { + set material (value) { this._material = value; if (this._body) { this._body.material = this._material; @@ -65,11 +67,11 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } @property - get mass() { + get mass () { return this._mass; } - set mass(value) { + set mass (value) { this._mass = value; if (this._body) { this._body.mass = value; @@ -77,11 +79,11 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } @property - get linearDamping() { + get linearDamping () { return this._linearDamping; } - set linearDamping(value) { + set linearDamping (value) { this._linearDamping = value; if (this._body) { this._body.linearDamping = value; @@ -89,18 +91,18 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } @property - get angularDamping() { + get angularDamping () { return this._angularDamping; } - set angularDamping(value) { + set angularDamping (value) { this._angularDamping = value; if (this._body) { this._body.angularDamping = value; } } - public pullTransform() { + public pullTransform () { if (this._body) { this._body.pullTransform(); } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 3a66658077..1190682be9 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -6,7 +6,9 @@ const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') export class RenderableComponent extends Component { - @property([Material]) + @property({ + type: [Material], + }) private _materials: Array = []; constructor () { @@ -16,6 +18,7 @@ export class RenderableComponent extends Component { @property({ type: [Material], displayName: 'Materials', + default: [], }) get sharedMaterials () { return this._materials; diff --git a/cocos/assets/CCScripts.js b/cocos/assets/CCScripts.js index 2595134a2b..9a1bf850db 100644 --- a/cocos/assets/CCScripts.js +++ b/cocos/assets/CCScripts.js @@ -36,7 +36,7 @@ import {ccclass} from '../core/data/class-decorator'; * @private */ @ccclass('cc.Script') -class Script extends Asset { +export class Script extends Asset { } cc._Script = Script; diff --git a/cocos/components/component.js b/cocos/components/component.js index a4cbd179ee..027555d5b1 100644 --- a/cocos/components/component.js +++ b/cocos/components/component.js @@ -28,6 +28,7 @@ import { CCObject } from '../core/data/object'; import {getClassName, value} from '../core/utils/js'; import IDGenerator from '../core/utils/id-generator'; import {ccclass, property} from '../core/data/class-decorator'; +import {Script} from '../assets'; let idGenerator = new IDGenerator('Comp'); const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; @@ -102,7 +103,7 @@ class Component extends CCObject { @property({ displayName: 'Script', - type: cc._Script, + type: Script, tooltip: CC_DEV && 'i18n:INSPECTOR.component.script' }) get __scriptAsset () { return null; } diff --git a/cocos/core/platform/CCSys.js b/cocos/core/platform/CCSys.js index 6fa19dfa61..93e9339a54 100644 --- a/cocos/core/platform/CCSys.js +++ b/cocos/core/platform/CCSys.js @@ -1022,10 +1022,13 @@ else { try { if (__audioSupport.WEB_AUDIO) { - __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); - if(__audioSupport.DELAY_CREATE_CTX) { - setTimeout(function(){ __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0); - } + __audioSupport._context = null; + Object.defineProperty(__audioSupport, 'context', { + get () { + if (this._context) return this._context; + return this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); + } + }); } } catch(error) { __audioSupport.WEB_AUDIO = false; diff --git a/cocos/load-pipeline/audio-downloader.js b/cocos/load-pipeline/audio-downloader.js index 2852de7e41..a34643c3b2 100644 --- a/cocos/load-pipeline/audio-downloader.js +++ b/cocos/load-pipeline/audio-downloader.js @@ -29,7 +29,6 @@ import debug from '../core/platform/CCDebug'; var __audioSupport = sys.__audioSupport; var formatSupport = __audioSupport.format; -var context = __audioSupport.context; function loadDomAudio (item, callback) { var dom = document.createElement('audio'); @@ -70,6 +69,7 @@ function loadDomAudio (item, callback) { } function loadWebAudio (item, callback) { + const context = __audioSupport.context; if (!context) callback(new Error(debug.getError(4926))); @@ -115,4 +115,4 @@ export default function downloadAudio (item, callback) { } } loader(item, callback); -} \ No newline at end of file +} diff --git a/playground/gizmo.html b/playground/gizmo.html index 35cd8a4dca..399c4d44be 100644 --- a/playground/gizmo.html +++ b/playground/gizmo.html @@ -82,7 +82,7 @@ bodyModel.material.setProperty('color', color); bodyModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST }); return arrow; - } + }; const createBorderPlane = (color, position, rotation) => { const borderPlane = new cc.Node('borderPlane'); borderPlane.setPosition(position); @@ -112,7 +112,7 @@ borderModel.material.setProperty('color', color); borderModel.material.overridePipelineStates({ primitive: cc.GFXPrimitiveMode.LINE_LIST }); return borderPlane; - } + }; const moveTool = new cc.Node('moveTool'); moveTool.parent = scene; @@ -125,7 +125,7 @@ let vel = cc.v3(), speed = 0.1; canv.addEventListener('keydown', (e) => { - if (e.key === 'i') vel.z = speed; + if (e.key === 'i') vel.z = speed; else if (e.key === 'k') vel.z = -speed; else if (e.key === 'j') vel.x = speed; else if (e.key === 'l') vel.x = -speed; @@ -133,7 +133,7 @@ else if (e.key === 'u') vel.y = -speed; }); canv.addEventListener('keyup', (e) => { - if (e.key === 'i') vel.z = 0; + if (e.key === 'i') vel.z = 0; else if (e.key === 'k') vel.z = 0; else if (e.key === 'j') vel.x = 0; else if (e.key === 'l') vel.x = 0; From 5874b5cc6cb1625679b92399509f7595e36f8438 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Mon, 21 Jan 2019 22:14:42 +0800 Subject: [PATCH 203/267] disable command pool --- cocos/3d/framework/model-component.js | 3 ++- cocos/gfx/webgl/webgl-command-allocator.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index b3be42b7eb..44329e4de6 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -168,12 +168,13 @@ export class ModelComponent extends RenderableComponent { } onEnable() { - this._updateModels(true); + this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); } onDisable() { + //this._getRenderScene().destroyModel(this._model); } onDestroy() { diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 4f2e4008c5..4f106beb8c 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -25,6 +25,11 @@ export class WebGLGFXCommandPool { } } + public alloc (clazz: new() => T): T { + return new clazz(); + } + + /* public alloc (clazz: new() => T): T { if (this._count >= this._data.length) { const size = this._data.length * 2; @@ -35,6 +40,7 @@ export class WebGLGFXCommandPool { return this._data[this._count++]; } + */ public freeAt (idx: number) { if (idx >= this._count) { @@ -50,12 +56,17 @@ export class WebGLGFXCommandPool { this._count -= 1; } + public free (obj: T) { + } + + /* public free (obj: T) { const idx = this._objIdx.get(obj); if (idx !== undefined) { this.freeAt(idx); } } + */ } export class WebGLGFXCommandAllocator extends GFXCommandAllocator { From fda2473401bc449d0d04ede9d08ab2376ef1623b Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 22 Jan 2019 11:26:18 +0800 Subject: [PATCH 204/267] pass priority --- cocos/3d/assets/effect-asset.ts | 1 + cocos/3d/framework/model-component.js | 4 ++++ cocos/gfx/define.ts | 6 ++++++ cocos/gfx/webgl/webgl-command-allocator.ts | 18 ++++++++--------- cocos/renderer/core/pass.ts | 23 ++++++++++++---------- cocos/renderer/scene/submodel.ts | 12 ++++++++++- 6 files changed, 44 insertions(+), 20 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index bb98d62d1f..0545c4d194 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -12,6 +12,7 @@ export interface IPropertyInfo { export interface IPassInfo { program: string; // effect-writer part + priority?: number; primitive?: GFXPrimitiveMode; stage?: RenderPassStage; rasterizerState?: GFXRasterizerState; diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 44329e4de6..76a4bb9edc 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -163,6 +163,10 @@ export class ModelComponent extends RenderableComponent { this._model = null; } + get model () { + return this._model; + } + onLoad() { } diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 03a8dd02d0..8f3aa8b544 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -791,3 +791,9 @@ export function GFXGetTypeSize (type: GFXType): number { } } } + +export enum GFXPassPriority { + MIN = 0, + MAX = 0xff, + DEFAULT = 0x80, +} diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 4f106beb8c..25aeffdbd2 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -25,23 +25,28 @@ export class WebGLGFXCommandPool { } } + /* */ public alloc (clazz: new() => T): T { return new clazz(); } - - /* + /* * public alloc (clazz: new() => T): T { if (this._count >= this._data.length) { const size = this._data.length * 2; for (let i = this._data.length; i < size; ++i) { this._data[i] = new clazz(); + this._objIdx.set(this._data[i], i); } } return this._data[this._count++]; } - */ + /* */ + /* */ + public free (obj: T) { + } + /* * public freeAt (idx: number) { if (idx >= this._count) { return; @@ -55,18 +60,13 @@ export class WebGLGFXCommandPool { this._objIdx.set(this._data[last], last); this._count -= 1; } - - public free (obj: T) { - } - - /* public free (obj: T) { const idx = this._objIdx.get(obj); if (idx !== undefined) { this.freeAt(idx); } } - */ + /* */ } export class WebGLGFXCommandAllocator extends GFXCommandAllocator { diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 2a4e29a1ce..8d1299d784 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -5,7 +5,7 @@ import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; import { GFXBindingLayout, IGFXBinding } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState, - GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define'; + GFXMemoryUsageBit, GFXPassPriority, GFXPrimitiveMode, GFXType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, @@ -107,6 +107,7 @@ export class Pass { protected _resources: IPassResources[] = []; // internal data protected _programName: string = ''; + protected _priority: GFXPassPriority = GFXPassPriority.DEFAULT; protected _primitive: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST; protected _stage: RenderPassStage = RenderPassStage.DEFAULT; protected _bindings: IGFXBinding[] = []; @@ -312,6 +313,7 @@ export class Pass { } protected _fillinPipelineInfo (info: PassOverrides) { + if (info.priority !== undefined) { this._priority = info.priority; } if (info.primitive !== undefined) { this._primitive = info.primitive; } if (info.stage !== undefined) { this._stage = info.stage; } if (info.dynamics !== undefined) { this._dynamicStates = info.dynamics; } @@ -331,15 +333,16 @@ export class Pass { } get programName () { return this._programName; } - 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 shader (): GFXShader | null { return this._shader; } - get renderPass (): GFXRenderPass | null { return this._renderPass; } - get dynamics (): IPassDynamics { return this._dynamics; } + get priority () { return this._priority; } + get primitive () { return this._primitive; } + get stage () { return this._stage; } + get bindings () { return this._bindings; } + get blendState () { return this._bs; } + get depthStencilState () { return this._dss; } + get rasterizerState () { return this._rs; } + get shader () { return this._shader; } + get renderPass () { return this._renderPass; } + get dynamics () { return this._dynamics; } } function serializeBlendState (bs: GFXBlendState) { diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index 0006f0e737..77bd86eee6 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -1,7 +1,7 @@ import { Material } from '../../3d/assets/material'; import { IRenderingSubmesh } from '../../3d/assets/mesh'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXCommandBufferType, GFXPassPriority } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; @@ -14,6 +14,7 @@ export class SubModel { private _cmdBuffers: GFXCommandBuffer[]; private _psos: GFXPipelineState[] | null; private _castShadow: boolean; + private _priority: GFXPassPriority; constructor () { this._subMeshObject = null; @@ -22,6 +23,7 @@ export class SubModel { this._psos = null; this._castShadow = false; this._inputAssembler = null; + this._priority = GFXPassPriority.DEFAULT; } public initialize (subMesh: IRenderingSubmesh, mat: Material, psos: GFXPipelineState[]) { @@ -43,6 +45,14 @@ export class SubModel { } } + set priority (val: GFXPassPriority) { + this._priority = val; + } + + get priority () { + return this._priority; + } + set subMeshData (sm: IRenderingSubmesh) { if (this._inputAssembler) { this._inputAssembler.destroy(); From 777103a221999bebd3facd8b525006742d70d1a5 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 22 Jan 2019 11:32:43 +0800 Subject: [PATCH 205/267] commit files --- cocos/gfx/webgl/webgl-command-allocator.ts | 122 ++++++++++++++------- cocos/gfx/webgl/webgl-command-buffer.ts | 24 ++-- cocos/gfx/webgl/webgl-commands.ts | 61 ++++++++--- cocos/gfx/webgl/webgl-device.ts | 1 + 4 files changed, 139 insertions(+), 69 deletions(-) diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 4f106beb8c..ab06d9dad1 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -1,3 +1,4 @@ +import { CachedArray } from '../../core/memop/cached-array'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; import { GFXStatus } from '../define'; import { GFXDevice } from '../device'; @@ -6,67 +7,71 @@ import { WebGLCmdBindStates, WebGLCmdCopyBufferToTexture, WebGLCmdDraw, + WebGLCmdObject, + WebGLCmdPackage, WebGLCmdUpdateBuffer, } from './webgl-commands'; -export class WebGLGFXCommandPool { +export class WebGLGFXCommandPool { - private _count = 0; - private _data: T[]; - private _objIdx: Map; + private _frees: Array; + private _freeIdx: number = 0; + private _freeCmds: CachedArray; constructor (clazz: new() => T, count: number) { - this._data = new Array(count); - this._objIdx = new Map(); - + this._frees = new Array(count); + this._freeCmds = new CachedArray(count); for (let i = 0; i < count; ++i) { - this._data[i] = new clazz(); - this._objIdx.set(this._data[i], i); + this._frees[i] = new clazz(); } + this._freeIdx = count - 1; } + /* public alloc (clazz: new() => T): T { return new clazz(); } + */ - /* public alloc (clazz: new() => T): T { - if (this._count >= this._data.length) { - const size = this._data.length * 2; - for (let i = this._data.length; i < size; ++i) { - this._data[i] = new clazz(); + if (this._freeIdx < 0) { + const size = this._frees.length * 2; + const temp = this._frees; + this._frees = new Array(size); + + const increase = size - temp.length; + for (let i = 0; i < increase; ++i) { + this._frees[i] = new clazz(); } + + for (let i = increase, j = 0; i < size; ++i, ++j) { + this._frees[i] = temp[j]; + } + + this._freeIdx += increase; } - return this._data[this._count++]; + const cmd = this._frees[this._freeIdx]; + this._frees[this._freeIdx--] = null; + return cmd!; } - */ - public freeAt (idx: number) { - if (idx >= this._count) { - return; + public free (cmd: T) { + this._freeCmds.push(cmd); + } + + public freeCmds (cmds: CachedArray) { + this._freeCmds.concat(cmds); + } + + public release () { + for (let i = 0; i < this._freeCmds.length; ++i) { + const cmd = this._freeCmds.array[i]; + cmd.clear(); + this._frees[++this._freeIdx] = cmd; } - - const last = this._count - 1; - 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; + this._freeCmds.clear(); } - - public free (obj: T) { - } - - /* - public free (obj: T) { - const idx = this._objIdx.get(obj); - if (idx !== undefined) { - this.freeAt(idx); - } - } - */ } export class WebGLGFXCommandAllocator extends GFXCommandAllocator { @@ -87,7 +92,6 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { } public initialize (info: IGFXCommandAllocatorInfo): boolean { - this._status = GFXStatus.SUCCESS; return true; } @@ -95,4 +99,42 @@ export class WebGLGFXCommandAllocator extends GFXCommandAllocator { public destroy () { this._status = GFXStatus.UNREADY; } + + public clearCmds (cmdPackage: WebGLCmdPackage) { + + if (cmdPackage.beginRenderPassCmds.length) { + this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds); + cmdPackage.beginRenderPassCmds.clear(); + } + + if (cmdPackage.bindStatesCmds.length) { + this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds); + cmdPackage.bindStatesCmds.clear(); + } + + if (cmdPackage.drawCmds.length) { + this.drawCmdPool.freeCmds(cmdPackage.drawCmds); + cmdPackage.drawCmds.clear(); + } + + if (cmdPackage.updateBufferCmds.length) { + this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds); + cmdPackage.updateBufferCmds.clear(); + } + + if (cmdPackage.copyBufferToTextureCmds.length) { + this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds); + cmdPackage.copyBufferToTextureCmds.clear(); + } + + cmdPackage.cmds.clear(); + } + + public releaseCmds () { + this.beginRenderPassCmdPool.release(); + this.bindStatesCmdPool.release(); + this.drawCmdPool.release(); + this.updateBufferCmdPool.release(); + this.copyBufferToTextureCmdPool.release(); + } } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 245e7b2fbc..2d3e6848ad 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -61,6 +61,7 @@ export interface IGFXStencilCompareMask { export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public cmdPackage: WebGLCmdPackage = new WebGLCmdPackage(); + private _webGLAllocator: WebGLGFXCommandAllocator | null = null; private _isInRenderPass: boolean = false; private _curGPUPipelineState: WebGLGPUPipelineState | null = null; private _curGPUBindingLayout: WebGLGPUBindingLayout | null = null; @@ -86,6 +87,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } this._allocator = info.allocator; + this._webGLAllocator = this._allocator as WebGLGFXCommandAllocator; this._type = info.type; this._status = GFXStatus.SUCCESS; @@ -93,16 +95,16 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } public destroy () { - if (this._allocator) { - this.cmdPackage.clearCmds( this._allocator as WebGLGFXCommandAllocator); + if (this._webGLAllocator) { + this._webGLAllocator!.clearCmds(this.cmdPackage); + this._allocator = null; + this._webGLAllocator = null; } this._status = GFXStatus.UNREADY; } public begin () { - if (this._allocator) { - this.cmdPackage.clearCmds( this._allocator as WebGLGFXCommandAllocator); - } + this._webGLAllocator!.clearCmds(this.cmdPackage); } public end () { @@ -119,8 +121,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { clearColors: IGFXColor[], clearDepth: number, clearStencil: number) { - const cmd = ( this._allocator as WebGLGFXCommandAllocator). - beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); + const cmd = this._webGLAllocator!.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); if (cmd) { cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; cmd.renderArea = renderArea; @@ -347,8 +348,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { this._type === GFXCommandBufferType.SECONDARY) { const gpuBuffer = (buffer as WebGLGFXBuffer).gpuBuffer; if (gpuBuffer) { - const cmd = (this._allocator as WebGLGFXCommandAllocator). - updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); + const cmd = this._webGLAllocator!.updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer); if (cmd) { let buffSize; @@ -387,8 +387,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { const gpuBuffer = ( srcBuff as WebGLGFXBuffer).gpuBuffer; const gpuTexture = ( dstTex as WebGLGFXTexture).gpuTexture; if (gpuBuffer && gpuTexture) { - const cmd = (this._allocator as WebGLGFXCommandAllocator). - copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); + const cmd = this._webGLAllocator!.copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture); if (cmd) { cmd.gpuBuffer = gpuBuffer; cmd.gpuTexture = gpuTexture; @@ -424,8 +423,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { } private bindStates () { - const bindStatesCmd = ( this._allocator as WebGLGFXCommandAllocator). - bindStatesCmdPool.alloc(WebGLCmdBindStates); + const bindStatesCmd = this._webGLAllocator!.bindStatesCmdPool.alloc(WebGLCmdBindStates); if (bindStatesCmd) { bindStatesCmd.gpuPipelineState = this._curGPUPipelineState; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 045d3a6d8a..3272a9361e 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -353,12 +353,14 @@ export enum WebGLCmd { COUNT, } -export class WebGLCmdObject { +export abstract class WebGLCmdObject { public cmdType: WebGLCmd; constructor (type: WebGLCmd) { this.cmdType = type; } + + public abstract clear (); } export class WebGLCmdBeginRenderPass extends WebGLCmdObject { @@ -372,6 +374,13 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject { constructor () { super(WebGLCmd.BEGIN_RENDER_PASS); } + + public clear () { + this.gpuFramebuffer = null; + this.clearColors = []; + this.clearDepth = 1.0; + this.clearStencil = 0; + } } export class WebGLCmdBindStates extends WebGLCmdObject { @@ -387,9 +396,24 @@ export class WebGLCmdBindStates extends WebGLCmdObject { public depthBounds: IGFXDepthBounds | null = null; public stencilWriteMask: IGFXStencilWriteMask | null = null; public stencilCompareMask: IGFXStencilCompareMask | null = null; + constructor () { super(WebGLCmd.BIND_STATES); } + + public clear () { + this.gpuPipelineState = null; + this.gpuBindingLayout = null; + this.gpuInputAssembler = null; + this.viewport = null; + this.scissor = null; + this.lineWidth = null; + this.depthBias = null; + this.blendConstants = null; + this.depthBounds = null; + this.stencilWriteMask = null; + this.stencilCompareMask = null; + } } export class WebGLCmdDraw extends WebGLCmdObject { @@ -407,6 +431,9 @@ export class WebGLCmdDraw extends WebGLCmdObject { constructor () { super(WebGLCmd.DRAW); } + + public clear () { + } } export class WebGLCmdUpdateBuffer extends WebGLCmdObject { @@ -419,6 +446,11 @@ export class WebGLCmdUpdateBuffer extends WebGLCmdObject { constructor () { super(WebGLCmd.UPDATE_BUFFER); } + + public clear () { + this.gpuBuffer = null; + this.buffer = null; + } } export class WebGLGFXTextureSubres { @@ -447,6 +479,13 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject { constructor () { super(WebGLCmd.COPY_BUFFER_TO_TEXTURE); } + + public clear () { + this.gpuBuffer = null; + this.gpuTexture = null; + this.dstLayout = null; + this.regions = []; + } } export class WebGLCmdPackage { @@ -460,37 +499,27 @@ export class WebGLCmdPackage { public clearCmds (allocator: WebGLGFXCommandAllocator) { if (this.beginRenderPassCmds.length) { - for (let i = 0; i < this.beginRenderPassCmds.length; ++i) { - allocator.beginRenderPassCmdPool.free(this.beginRenderPassCmds.array[i]); - } + allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds); this.beginRenderPassCmds.clear(); } if (this.bindStatesCmds.length) { - for (let i = 0; i < this.bindStatesCmds.length; ++i) { - allocator.bindStatesCmdPool.free(this.bindStatesCmds.array[i]); - } + allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds); this.bindStatesCmds.clear(); } if (this.drawCmds.length) { - for (let i = 0; i < this.drawCmds.length; ++i) { - allocator.drawCmdPool.free(this.drawCmds.array[i]); - } + allocator.drawCmdPool.freeCmds(this.drawCmds); this.drawCmds.clear(); } if (this.updateBufferCmds.length) { - for (let i = 0; i < this.updateBufferCmds.length; ++i) { - allocator.updateBufferCmdPool.free(this.updateBufferCmds.array[i]); - } + allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds); this.updateBufferCmds.clear(); } if (this.copyBufferToTextureCmds.length) { - for (let i = 0; i < this.copyBufferToTextureCmds.length; ++i) { - allocator.copyBufferToTextureCmdPool.free(this.copyBufferToTextureCmds.array[i]); - } + allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds); this.copyBufferToTextureCmds.clear(); } diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 3ee0573aba..a585011c53 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -491,6 +491,7 @@ export class WebGLGFXDevice extends GFXDevice { } public present () { + (this._cmdAllocator as WebGLGFXCommandAllocator).releaseCmds(); } public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { From 83ceb0dd80b843e3b164f0416777886654e01183 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 22 Jan 2019 11:33:09 +0800 Subject: [PATCH 206/267] commit files --- cocos/gfx/webgl/webgl-command-allocator.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index ab06d9dad1..351db0a49c 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -27,12 +27,11 @@ export class WebGLGFXCommandPool { this._freeIdx = count - 1; } - /* public alloc (clazz: new() => T): T { return new clazz(); } - */ + /* public alloc (clazz: new() => T): T { if (this._freeIdx < 0) { const size = this._frees.length * 2; @@ -55,13 +54,14 @@ export class WebGLGFXCommandPool { this._frees[this._freeIdx--] = null; return cmd!; } + */ public free (cmd: T) { this._freeCmds.push(cmd); } public freeCmds (cmds: CachedArray) { - this._freeCmds.concat(cmds); + // this._freeCmds.concat(cmds); } public release () { From 9b759ccc6438c7fda9964cc06fee99dcb9ebb366 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 22 Jan 2019 13:09:08 +0800 Subject: [PATCH 207/267] fix command allocator bugs, and optimize cached array --- cocos/core/memop/cached-array.ts | 43 ++---------------- cocos/gfx/webgl/webgl-command-allocator.ts | 21 ++++++--- cocos/gfx/webgl/webgl-command-buffer.ts | 51 ++++++++++++++++------ cocos/gfx/webgl/webgl-commands.ts | 3 +- cocos/pipeline/render-queue.ts | 3 -- 5 files changed, 55 insertions(+), 66 deletions(-) diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index 2388d0bba8..5f7b7b4727 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -2,12 +2,12 @@ export class CachedArray { public array: T[]; public length: number = 0; + private cache: Array; private _compareFn; - private _capacity: number = 0; constructor (length: number, compareFn?: (a: T, b: T) => number) { this.array = new Array(length); - this._capacity = length; + this.cache = this.array; this.length = 0; if (compareFn !== undefined) { @@ -17,27 +17,7 @@ export class CachedArray { } } - public reserve (length: number) { - if (length > this._capacity) { - const temp = this.array; - this.array = new Array(length); - for (let i = 0; i < this._capacity; ++i) { - this.array[i] = temp[i]; - } - this._capacity = length; - } - } - public push (item: T) { - if (this.length > this._capacity) { - const temp = this.array; - this.array = new Array(this.length); - for (let i = 0; i < this._capacity; ++i) { - this.array[i] = temp[i]; - } - this._capacity = this.length; - } - this.array[this.length++] = item; } @@ -50,6 +30,7 @@ export class CachedArray { } public clear () { + this.cache.fill(null); this.length = 0; } @@ -59,30 +40,12 @@ export class CachedArray { } public concat (array: CachedArray) { - if (array.length + this.length > this._capacity) { - const temp = this.array; - this.array = new Array(array.length + this.length); - for (let i = 0; i < this._capacity; ++i) { - this.array[i] = temp[i]; - } - this._capacity = this.array.length; - } - for (let i = 0; i < array.length; ++i) { this.array[this.length++] = array.array[i]; } } public append (array: T[]) { - if (array.length + this.length > this._capacity) { - const temp = this.array; - this.array = new Array(array.length + this.length); - for (let i = 0; i < this._capacity; ++i) { - this.array[i] = temp[i]; - } - this._capacity = this.array.length; - } - for (const item of array) { this.array[this.length++] = item; } diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index 819f45ce97..fa5790db8d 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -27,11 +27,12 @@ export class WebGLGFXCommandPool { this._freeIdx = count - 1; } - /* */ + /* public alloc (clazz: new() => T): T { return new clazz(); } - /* * + */ + public alloc (clazz: new() => T): T { if (this._freeIdx < 0) { const size = this._frees.length * 2; @@ -50,18 +51,24 @@ export class WebGLGFXCommandPool { this._freeIdx += increase; } - const cmd = this._frees[this._freeIdx]; + const cmd = this._frees[this._freeIdx]!; this._frees[this._freeIdx--] = null; - return cmd!; + ++cmd.refCount; + return cmd; } - /* */ public free (cmd: T) { - this._freeCmds.push(cmd); + if (--cmd.refCount === 0) { + this._freeCmds.push(cmd); + } } public freeCmds (cmds: CachedArray) { - // this._freeCmds.concat(cmds); + for (let i = 0; i < cmds.length; ++i) { + if (--cmds.array[i].refCount === 0) { + this._freeCmds.push(cmds.array[i]); + } + } } public release () { diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 2d3e6848ad..3f6d77f9e4 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -122,16 +122,14 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { clearDepth: number, clearStencil: number) { const cmd = this._webGLAllocator!.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass); - if (cmd) { - cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; - cmd.renderArea = renderArea; - cmd.clearColors = clearColors.slice(); - cmd.clearDepth = clearDepth; - cmd.clearStencil = clearStencil; - this.cmdPackage.beginRenderPassCmds.push(cmd); + cmd.gpuFramebuffer = ( framebuffer as WebGLGFXFramebuffer).gpuFramebuffer; + cmd.renderArea = renderArea; + cmd.clearColors = clearColors.slice(); + cmd.clearDepth = clearDepth; + cmd.clearStencil = clearStencil; + this.cmdPackage.beginRenderPassCmds.push(cmd); - this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS); - } + this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS); this._isInRenderPass = true; } @@ -409,11 +407,36 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { for (let i = 0; i < count; ++i) { const webGLCmdBuff = cmdBuffs[i] as WebGLGFXCommandBuffer; - this.cmdPackage.beginRenderPassCmds.concat(webGLCmdBuff.cmdPackage.beginRenderPassCmds); - this.cmdPackage.bindStatesCmds.concat(webGLCmdBuff.cmdPackage.bindStatesCmds); - this.cmdPackage.drawCmds.concat(webGLCmdBuff.cmdPackage.drawCmds); - this.cmdPackage.updateBufferCmds.concat(webGLCmdBuff.cmdPackage.updateBufferCmds); - this.cmdPackage.copyBufferToTextureCmds.concat(webGLCmdBuff.cmdPackage.copyBufferToTextureCmds); + for (let c = 0; c < webGLCmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.beginRenderPassCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.beginRenderPassCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.bindStatesCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.bindStatesCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.bindStatesCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.drawCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.drawCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.drawCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.updateBufferCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.updateBufferCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.updateBufferCmds.push(cmd); + } + + for (let c = 0; c < webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++c) { + const cmd = webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.array[c]; + ++cmd.refCount; + this.cmdPackage.copyBufferToTextureCmds.push(cmd); + } + this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds); } } diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 3272a9361e..6d967bb34f 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -355,6 +355,7 @@ export enum WebGLCmd { export abstract class WebGLCmdObject { public cmdType: WebGLCmd; + public refCount: number = 0; constructor (type: WebGLCmd) { this.cmdType = type; @@ -378,8 +379,6 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject { public clear () { this.gpuFramebuffer = null; this.clearColors = []; - this.clearDepth = 1.0; - this.clearStencil = 0; } } diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index cac06fa55b..7f81a66e5c 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -102,9 +102,6 @@ export class RenderQueue { const opaqueCount = this.opaques.length; const cmdBuffCount = opaqueCount + this.transparents.length; - - this.cmdBuffs.reserve(cmdBuffCount); - this.cmdBuffCount = cmdBuffCount; for (let i = 0; i < this.opaques.length; ++i) { From 457814d8485cb349d446e77210bb5d1f34607e4e Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Tue, 22 Jan 2019 14:22:28 +0800 Subject: [PATCH 208/267] add function addToQueue for mask --- cocos/3d/ui/assembler/mask-assembler.ts | 1 + cocos/3d/ui/assembler/sprite/bar-filled.ts | 31 ++++++++------ cocos/3d/ui/assembler/sprite/radial-filled.ts | 11 ++--- cocos/3d/ui/assembler/sprite/simple.ts | 13 +++--- cocos/3d/ui/assembler/sprite/sliced.ts | 15 +++---- cocos/3d/ui/assembler/sprite/tiled.ts | 40 +++++++++---------- cocos/renderer/ui/ui.ts | 30 +++++++++----- 7 files changed, 80 insertions(+), 61 deletions(-) diff --git a/cocos/3d/ui/assembler/mask-assembler.ts b/cocos/3d/ui/assembler/mask-assembler.ts index 412466ffd6..2b2f09747f 100644 --- a/cocos/3d/ui/assembler/mask-assembler.ts +++ b/cocos/3d/ui/assembler/mask-assembler.ts @@ -145,6 +145,7 @@ export const maskAssembler: IAssembler = { const maskRenderData = ui.createUIRenderData() as IUIRenderData; maskRenderData.meshBuffer = meshBuffer; maskRenderData.material = maskMaterial; + ui.addToQueue(maskRenderData); } }, }; diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/3d/ui/assembler/sprite/bar-filled.ts index b435716709..9a0e124cbc 100644 --- a/cocos/3d/ui/assembler/sprite/bar-filled.ts +++ b/cocos/3d/ui/assembler/sprite/bar-filled.ts @@ -27,20 +27,20 @@ import { SpriteComponent } from '../../components/sprite-component'; const FillType = SpriteComponent.FillType; // const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); -import { fillVerticesWithoutCalc3D } from '../utils'; -import { vec3 } from '../../../../core/vmath/index'; -import { RenderData, IRenderData } from '../../../../renderer/ui/renderData'; -import { Node } from '../../../../scene-graph/node'; -import { IAssembler } from '../assembler'; import { Mat4 } from '../../../../core/value-types'; -import { MeshBuffer } from '../../mesh-buffer'; +import { vec3 } from '../../../../core/vmath/index'; +import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; +import { Node } from '../../../../scene-graph/node'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; +import { fillVerticesWithoutCalc3D } from '../utils'; const matrix = new Mat4(); export const barFilled: IAssembler = { useModel: false, - updateRenderData(sprite: SpriteComponent) { + updateRenderData (sprite: SpriteComponent) { const frame = sprite.spriteFrame; // TODO: Material API design and export from editor could affect the material activation process @@ -95,7 +95,7 @@ export const barFilled: IAssembler = { } }, - updateUVs(sprite: SpriteComponent, fillStart: number, fillEnd: number) { + updateUVs (sprite: SpriteComponent, fillStart: number, fillEnd: number) { const spriteFrame = sprite.spriteFrame; const renderData = sprite.renderData; const datas = renderData!.datas; @@ -186,7 +186,7 @@ export const barFilled: IAssembler = { renderData!.uvDirty = false; }, - updateVerts(sprite: SpriteComponent, fillStart: number, fillEnd: number) { + updateVerts (sprite: SpriteComponent, fillStart: number, fillEnd: number) { const renderData: RenderData|null = sprite.renderData; const datas: IRenderData[] = renderData!.datas; const node: Node = sprite.node; @@ -234,7 +234,7 @@ export const barFilled: IAssembler = { renderData!.vertDirty = false; }, - createData(sprite: SpriteComponent) { + createData (sprite: SpriteComponent) { const renderData: RenderData|null = sprite.requestRenderData(); // 0-4 for world verts // 5-8 for local verts @@ -250,7 +250,7 @@ export const barFilled: IAssembler = { return renderData as RenderData; }, - updateWorldVerts(sprite: SpriteComponent) { + updateWorldVerts (sprite: SpriteComponent) { const node = sprite.node; const datas = sprite.renderData!.datas; @@ -263,10 +263,10 @@ export const barFilled: IAssembler = { } }, - fillBuffers(sprite: SpriteComponent, renderer: UI) { + fillBuffers (sprite: SpriteComponent, renderer: UI) { const buffer: MeshBuffer = renderer.createBuffer( sprite.renderData!.vertexCount, - sprite.renderData!.indiceCount + sprite.renderData!.indiceCount, ); const commitBuffer: IUIRenderData = renderer.createUIRenderData(); // if (renderer.worldMatDirty) { @@ -288,5 +288,10 @@ export const barFilled: IAssembler = { ibuf![indiceOffset++] = vertexId + 1; ibuf![indiceOffset++] = vertexId + 3; ibuf![indiceOffset++] = vertexId + 2; + + commitBuffer.meshBuffer = buffer; + commitBuffer.material = sprite.material!; + commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + renderer.addToQueue(commitBuffer); }, }; diff --git a/cocos/3d/ui/assembler/sprite/radial-filled.ts b/cocos/3d/ui/assembler/sprite/radial-filled.ts index 626b6a0099..805d232a23 100644 --- a/cocos/3d/ui/assembler/sprite/radial-filled.ts +++ b/cocos/3d/ui/assembler/sprite/radial-filled.ts @@ -24,13 +24,13 @@ ****************************************************************************/ // const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); -import { fillVertices3D } from '../utils'; -import { Vec2, Color } from '../../../../core/value-types'; +import { Color, Vec2 } from '../../../../core/value-types'; import { RenderData } from '../../../../renderer/ui/renderData'; -import { IAssembler } from '../assembler'; +import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; import { SpriteComponent } from '../../components/sprite-component'; import { MeshBuffer } from '../../mesh-buffer'; -import { UI, IUIRenderData } from '../../../../renderer/ui/ui'; +import { IAssembler } from '../assembler'; +import { fillVertices3D } from '../utils'; const PI_2 = Math.PI * 2; @@ -360,7 +360,7 @@ export const radialFilled: IAssembler = { fillBuffers (comp: SpriteComponent, renderer: UI) { const buffer: MeshBuffer = renderer.createBuffer( comp.renderData!.vertexCount, - comp.renderData!.indiceCount + comp.renderData!.indiceCount, ); const commitBuffer: IUIRenderData = renderer.createUIRenderData(); @@ -381,5 +381,6 @@ export const radialFilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = comp.material!; commitBuffer.camera = renderer.getScreen(comp.viewID)!.camera!; + renderer.addToQueue(commitBuffer); }, }; diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts index 802c92cb04..fb172af088 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -23,14 +23,14 @@ THE SOFTWARE. ****************************************************************************/ +import { Color, Vec3 } from '../../../../core/value-types'; import { vec3 } from '../../../../core/vmath/index'; -import { SpriteComponent } from '../../components/sprite-component'; -import { Vec3, Color } from '../../../../core/value-types'; -import { Node } from '../../../../scene-graph/node'; import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; -import { IAssembler } from '../assembler'; +import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; +import { Node } from '../../../../scene-graph/node'; +import { SpriteComponent } from '../../components/sprite-component'; import { MeshBuffer } from '../../mesh-buffer'; -import { UI, IUIRenderData } from '../../../../renderer/ui/ui'; +import { IAssembler } from '../assembler'; // const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager'); const matrix = cc.mat4(); const vec3_temps: Vec3[] = []; @@ -79,7 +79,7 @@ export const simple: IAssembler = { const buffer: MeshBuffer = renderer.createBuffer( sprite.renderData!.vertexCount, - sprite.renderData!.indiceCount + sprite.renderData!.indiceCount, ); const commitBuffer: IUIRenderData = renderer.createUIRenderData(); const datas: IRenderData[] = sprite!.renderData!.datas; @@ -141,6 +141,7 @@ export const simple: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + renderer.addToQueue(commitBuffer); }, updateVerts (sprite: SpriteComponent) { diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/3d/ui/assembler/sprite/sliced.ts index 969f6f1829..f6a2cd6420 100644 --- a/cocos/3d/ui/assembler/sprite/sliced.ts +++ b/cocos/3d/ui/assembler/sprite/sliced.ts @@ -24,15 +24,15 @@ ****************************************************************************/ // const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); -import { vec3, mat4 } from '../../../../core/vmath/index'; -import { RenderData, IRenderData } from '../../../../renderer/ui/renderData'; -import { Node } from '../../../../scene-graph/node'; -import { Color, Mat4 } from '../../../../core/value-types'; import { IUV, SpriteFrame } from '../../../../assets/CCSpriteFrame'; -import { IAssembler } from '../assembler'; +import { Color, Mat4 } from '../../../../core/value-types'; +import { vec3 } from '../../../../core/vmath/index'; +import { IRenderData, RenderData } from '../../../../renderer/ui/renderData'; +import { IUIRenderData } from '../../../../renderer/ui/ui'; +import { Node } from '../../../../scene-graph/node'; import { SpriteComponent } from '../../components/sprite-component'; import { MeshBuffer } from '../../mesh-buffer'; -import { IUIRenderData } from '../../../../renderer/ui/ui'; +import { IAssembler } from '../assembler'; const vec3_temp = vec3.create(); const matrix = new Mat4(); @@ -118,7 +118,7 @@ export const sliced: IAssembler = { const buffer: MeshBuffer = renderer.createBuffer( sprite.renderData!.vertexCount, - sprite.renderData!.indiceCount + sprite.renderData!.indiceCount, ); const commitBuffer: IUIRenderData = renderer.createUIRenderData(); const renderData: RenderData|null = sprite.renderData; @@ -172,6 +172,7 @@ export const sliced: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + renderer.addToQueue(commitBuffer); }, updateWorldVerts (sprite: SpriteComponent) { diff --git a/cocos/3d/ui/assembler/sprite/tiled.ts b/cocos/3d/ui/assembler/sprite/tiled.ts index 4e5a5ee77c..2cc31b7948 100644 --- a/cocos/3d/ui/assembler/sprite/tiled.ts +++ b/cocos/3d/ui/assembler/sprite/tiled.ts @@ -24,18 +24,18 @@ ****************************************************************************/ // const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); -import { vec3 } from '../../../../core/vmath/index'; import { Mat4, Vec3 } from '../../../../core/value-types'; -import { IAssembler } from '../assembler'; -import { UIRenderComponent } from '../../components/ui-render-component'; +import { vec3 } from '../../../../core/vmath/index'; import { RenderData } from '../../../../renderer/ui/renderData'; -import { MeshBuffer } from '../../mesh-buffer'; import { IUIRenderData, UI } from '../../../../renderer/ui/ui'; import { SpriteComponent } from '../../components/sprite-component'; +import { UIRenderComponent } from '../../components/ui-render-component'; +import { MeshBuffer } from '../../mesh-buffer'; +import { IAssembler } from '../assembler'; const matrix = new Mat4(); -let vec3_temps: Vec3[] = []; +const vec3_temps: Vec3[] = []; for (let i = 0; i < 4; i++) { vec3_temps.push(new Vec3()); } @@ -47,11 +47,11 @@ const _tempColorOffset = 5; export const tilled: IAssembler = { useModel: false, - createData(sprite: UIRenderComponent) { + createData (sprite: UIRenderComponent) { return sprite.requestRenderData() as RenderData; }, - updateRenderData(sprite: SpriteComponent) { + updateRenderData (sprite: SpriteComponent) { const frame = sprite.spriteFrame; // TODO: Material API design and export from editor could affect the material activation process @@ -105,10 +105,10 @@ export const tilled: IAssembler = { renderData.vertDirty = false; }, - fillBuffers(sprite: SpriteComponent, renderer: UI) { + fillBuffers (sprite: SpriteComponent, renderer: UI) { const buffer: MeshBuffer = renderer.createBuffer( sprite.renderData!.vertexCount, - sprite.renderData!.indiceCount + sprite.renderData!.indiceCount, ); const commitBuffer: IUIRenderData = renderer.createUIRenderData(); @@ -160,12 +160,12 @@ export const tilled: IAssembler = { vec3.set(vec3_temps[3], x1, y1, 0); for (let i = 0; i < 4; i++) { - let vec3_temp = vec3_temps[i]; + const vec3_temp = vec3_temps[i]; vec3.transformMat4(vec3_temp, vec3_temp, matrix); - let offset = i * 6; - vbuf![vertexOffset + offset] = vec3_temp.x; - vbuf![vertexOffset + offset + 1] = vec3_temp.y; - vbuf![vertexOffset + offset + 2] = vec3_temp.z; + const move = i * 6; + vbuf![vertexOffset + move] = vec3_temp.x; + vbuf![vertexOffset + move + 1] = vec3_temp.y; + vbuf![vertexOffset + move + 2] = vec3_temp.z; } vertexOffset += 24; @@ -186,8 +186,8 @@ export const tilled: IAssembler = { for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) { coefu = Math.min(1, hRepeat - xindex); - let vertexOffsetU = vertexOffset + uvOffset; - let vertexOffsetV = vertexOffsetU + 1; + const vertexOffsetU = vertexOffset + uvOffset; + const vertexOffsetV = vertexOffsetU + 1; // UV if (rotated) { // lb @@ -202,8 +202,7 @@ export const tilled: IAssembler = { // rt vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset2]; vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset1]; - } - else { + } else { // lb vbuf![vertexOffsetU] = uv[0]; vbuf![vertexOffsetV] = uv[1]; @@ -228,7 +227,7 @@ export const tilled: IAssembler = { } // update indices - let length = renderData!.indiceCount; + const length = renderData!.indiceCount; for (let i = 0; i < length; i += 6) { ibuf![indiceOffset++] = vertexId; ibuf![indiceOffset++] = vertexId + 1; @@ -242,9 +241,10 @@ export const tilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + renderer.addToQueue(commitBuffer); }, - updateVerts(sprite: SpriteComponent) { + updateVerts (sprite: SpriteComponent) { // const renderData = sprite.renderData; // const datas = renderData!.datas; // const vbuf; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 19c9e0b108..6a8ea70132 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -2,6 +2,7 @@ import { Material } from '../../3d/assets/material'; import RecyclePool from '../../3d/memop/recycle-pool'; import { CanvasComponent } from '../../3d/ui/components/canvas-component'; +import { UIRenderComponent } from '../../3d/ui/components/ui-render-component'; import { IMeshBufferInitData, MeshBuffer } from '../../3d/ui/mesh-buffer'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; @@ -20,11 +21,10 @@ import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { vfmt } from '../../gfx/vertex-format-sample'; +import { BaseNode } from '../../scene-graph/base-node'; import { Pass } from '../core/pass'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; -import { UIRenderComponent } from '../../3d/ui/components/ui-render-component'; -import { BaseNode } from '../../scene-graph/base-node'; export interface IUIBufferBatch { vb: GFXBuffer; @@ -71,6 +71,7 @@ export class UI { private _uiMaterials: IUIMaterial[] = []; private _items: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; + private _commitUIRenderDatas: IUIRenderData[] = []; constructor (private _root: Root) { this._device = _root.device; @@ -89,9 +90,9 @@ export class UI { public initialize () { this._attributes = [ - { name: 'a_texCoord', format: GFXFormat.RGB32F }, - { name: 'a_position', format: GFXFormat.RG32F }, - { name: 'a_color', format: GFXFormat.RGBA8, isNormalized: true }, + { name: 'a_color', format: GFXFormat.RGBA32F, binding: 0, }, + { name: 'a_position', format: GFXFormat.RGB32F, binding: 1, }, + { name: 'a_texCoord', format: GFXFormat.RG32F, binding: 2, }, ]; this.createBufferBatch(); @@ -189,7 +190,7 @@ export class UI { } } - public createBuffer(vertexCount: number, indiceCount: number){ + public createBuffer (vertexCount: number, indiceCount: number) { const buffer = this._bufferPool.add(); this._bufferInitData!.vertexCount = vertexCount; this._bufferInitData!.indiceCount = indiceCount; @@ -201,13 +202,22 @@ export class UI { return this._commitUIRenderDataPool.add(); } + public addToQueue(uiRenderData: IUIRenderData){ + this._commitUIRenderDatas.push(uiRenderData); + } + + public flush(){ + this.render(); + } + public update (dt: number) { this._items.clear(); // TODO: Merge batch here. this._renderScreens(); - this.render(); + // this.render(); + this.flush(); } private _walk (node, fn1, fn2, level = 0) { @@ -244,15 +254,15 @@ export class UI { } } - private _reset(){ + private _reset () { this._bufferPool.reset(); this._commitUIRenderDataPool.reset(); + this._commitUIRenderDatas.length = 0; } private _commitComp (comp: UIRenderComponent) { comp.updateAssembler(this); - const canvasComp: CanvasComponent | null = this.getScreen(comp.viewID); - + // const canvasComp: CanvasComponent | null = this.getScreen(comp.viewID); // const renderDataFormat: IUIRenderData = this._commitUIRenderDataPool.add(); // renderDataFormat.meshBuffer = buffer; // renderDataFormat.material = comp.material as Material; From d2e2c14b2f947add6a27468a76f3a0aec39ae0ad Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 22 Jan 2019 14:16:27 +0800 Subject: [PATCH 209/267] render priority --- cocos/3d/framework/animation-component.js | 4 +--- cocos/3d/framework/renderable-component.ts | 5 +---- cocos/core/data/class.js | 4 ++-- cocos/core/vmath/quat.ts | 14 ++++++++++++++ cocos/pipeline/define.ts | 6 ++++++ cocos/pipeline/render-queue.ts | 8 +------- cocos/renderer/core/pass.ts | 3 +-- cocos/renderer/scene/submodel.ts | 2 +- 8 files changed, 27 insertions(+), 19 deletions(-) diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js index e14eefd7e3..0e9d1c8e4b 100644 --- a/cocos/3d/framework/animation-component.js +++ b/cocos/3d/framework/animation-component.js @@ -383,9 +383,7 @@ export default class AnimationComponent extends Component { * @property clips * @type {AnimationClip[]} */ - @property({ - type: [AnimationClip], - }) + @property({ type: [AnimationClip] }) get clips() { return this._clips; } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 1190682be9..108e0ed33b 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -6,9 +6,7 @@ const { ccclass, property } = _decorator; @ccclass('cc.RenderableComponent') export class RenderableComponent extends Component { - @property({ - type: [Material], - }) + @property({ type: [Material] }) private _materials: Array = []; constructor () { @@ -18,7 +16,6 @@ export class RenderableComponent extends Component { @property({ type: [Material], displayName: 'Materials', - default: [], }) get sharedMaterials () { return this._materials; diff --git a/cocos/core/data/class.js b/cocos/core/data/class.js index 5981486b6c..93684394e1 100644 --- a/cocos/core/data/class.js +++ b/cocos/core/data/class.js @@ -144,7 +144,7 @@ function defineProp (cls, className, propName, val, es6) { appendProp(cls, propName); // apply attributes - var attrs = parseAttributes(cls, val, className, propName, false); + var attrs = parseAttributes(cls, val, className, propName, false); if (attrs) { var onAfterProp = tmpArray; for (var i = 0; i < attrs.length; i++) { @@ -1240,4 +1240,4 @@ CCClass.escapeForJS = escapeForJS; CCClass.IDENTIFIER_RE = IDENTIFIER_RE; CCClass.getNewValueTypeCode = CC_SUPPORT_JIT && getNewValueTypeCodeJit; -cc.Class = CCClass; \ No newline at end of file +cc.Class = CCClass; diff --git a/cocos/core/vmath/quat.ts b/cocos/core/vmath/quat.ts index 8dbb21edd6..3bf3dce712 100644 --- a/cocos/core/vmath/quat.ts +++ b/cocos/core/vmath/quat.ts @@ -68,6 +68,20 @@ export default class quat { return out; } + /** + * Sets a quaternion as identity quaternion. + * + * @param out - Quaternion to set. + * @return out. + */ + public static identity (out: Out) { + out.x = 0; + out.y = 0; + out.z = 0; + out.w = 1; + return out; + } + /** * Sets a quaternion to represent the shortest rotation from one * vector to another. diff --git a/cocos/pipeline/define.ts b/cocos/pipeline/define.ts index bd8119ba8b..ae5cbdb2fb 100644 --- a/cocos/pipeline/define.ts +++ b/cocos/pipeline/define.ts @@ -2,3 +2,9 @@ export enum RenderPassStage { DEFAULT = 100, } + +export enum RenderPriority { + MIN = 0, + MAX = 0xff, + DEFAULT = 0x80, +} diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index 7f81a66e5c..a02e0ac02b 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -5,12 +5,6 @@ import { Camera } from '../renderer/scene/camera'; import { Model } from '../renderer/scene/model'; import { SubModel } from '../renderer/scene/submodel'; -export enum RenderPriority { - MIN = 0, - MAX = 0xff, - DEFAULT = 0x80, -} - export interface IRenderItem { hash: number; depth: number; @@ -66,7 +60,7 @@ export class RenderQueue { public add (model: Model, camera: Camera) { - const depth = vec3.distance(camera.node.getPosition(), model.node!.getPosition()); + const depth = vec3.squaredDistance(camera.node.getPosition(), model.node!.getPosition()); for (let i = 0; i < model.subModelNum; ++i) { const subModel = model.getSubModel(i); diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 64ea91fdc8..54b321faa7 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -14,9 +14,8 @@ import { GFXRenderPass } from '../../gfx/render-pass'; import { GFXSampler } from '../../gfx/sampler'; import { GFXShader } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; -import { RenderPassStage } from '../../pipeline/define'; +import { RenderPassStage, RenderPriority } from '../../pipeline/define'; import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; -import { RenderPriority } from '../../pipeline/render-queue'; export interface IPassInfoFull extends IPassInfo { // generated part diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index 79d0b403c6..70f8cb2019 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -5,7 +5,7 @@ import { GFXCommandBufferType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; -import { RenderPriority } from '../../pipeline/render-queue'; +import { RenderPriority } from '../../pipeline/define'; import { Pass } from '../core/pass'; export class SubModel { From 8a1f0f0d1c4e89938fa628e61dd3ddadc87ce0af Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 22 Jan 2019 15:12:58 +0800 Subject: [PATCH 210/267] depth sort for transparent model --- cocos/pipeline/render-pipeline.ts | 7 ++++--- cocos/pipeline/render-queue.ts | 8 ++++++-- cocos/renderer/scene/camera.ts | 20 +++++++++++++++++++- cocos/renderer/scene/render-scene.ts | 8 +++++--- 4 files changed, 34 insertions(+), 9 deletions(-) diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 89dd1e1055..ae5756a941 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,5 +1,6 @@ import { intersect } from '../3d/geom-utils'; import { Root } from '../core/root'; +import { Mat4, Vec3 } from '../core/value-types'; import { mat4, vec3 } from '../core/vmath'; import { GFXBuffer } from '../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXType } from '../gfx/define'; @@ -9,7 +10,6 @@ import { GFXRenderPass } from '../gfx/render-pass'; import { GFXUniformBlock } from '../gfx/shader'; import { GFXTexture } from '../gfx/texture'; import { GFXTextureView } from '../gfx/texture-view'; -import { Camera } from '../renderer/scene/camera'; import { IRenderFlowInfo, RenderFlow } from './render-flow'; import { RenderQueue } from './render-queue'; import { RenderView } from './render-view'; @@ -64,7 +64,8 @@ export class UBOLocal { const _vec4Array = new Float32Array(4); const _mat4Array = new Float32Array(16); -const _outMat = new mat4(); +const _outMat = new Mat4(); +const _outVec3 = new Vec3(); export abstract class RenderPipeline { @@ -330,7 +331,7 @@ export abstract class RenderPipeline { mat4.array(_mat4Array, view.camera.matViewProjInv); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); - vec3.array(_vec4Array, view.camera.node && view.camera.node.getPosition()); + vec3.array(_vec4Array, view.camera.node && view.camera.node.getWorldPosition(_outVec3)); _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index a02e0ac02b..4d56c3fc07 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -1,4 +1,5 @@ import { CachedArray } from '../core/memop/cached-array'; +import { Vec3 } from '../core/value-types'; import { vec3 } from '../core/vmath'; import { GFXCommandBuffer } from '../gfx/command-buffer'; import { Camera } from '../renderer/scene/camera'; @@ -13,6 +14,8 @@ export interface IRenderItem { cmdBuff: GFXCommandBuffer; } +const _v3tmp = new Vec3(); + export class RenderQueue { public opaques: CachedArray; public transparents: CachedArray; @@ -59,8 +62,9 @@ export class RenderQueue { } public add (model: Model, camera: Camera) { - - const depth = vec3.squaredDistance(camera.node.getPosition(), model.node!.getPosition()); + model.node.getWorldPosition(_v3tmp); + vec3.sub(_v3tmp, _v3tmp, camera.position); + const depth = vec3.dot(_v3tmp, camera.forward); for (let i = 0; i < model.subModelNum; ++i) { const subModel = model.getSubModel(i); diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index b156a383ba..6a8ed99b52 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -1,5 +1,5 @@ import { frustum, ray } from '../../3d/geom-utils'; -import { Color, Mat4, Rect } from '../../core/value-types'; +import { Color, Mat4, Rect, Vec3 } from '../../core/value-types'; import { color4, lerp, mat4, toRadian, vec3 } from '../../core/vmath'; import { GFXClearFlag, IGFXColor } from '../../gfx/define'; import { RenderView, RenderViewPriority } from '../../pipeline/render-view'; @@ -53,6 +53,8 @@ export class Camera { private _matViewProj: Mat4 = new Mat4(); private _matViewProjInv: Mat4 = new Mat4(); private _frustum: frustum = new frustum(); + private _forward: Vec3 = new Vec3(); + private _position: Vec3 = new Vec3(); private _node: Node | null = null; private _view: RenderView; private _visibility: number = 0; @@ -120,6 +122,14 @@ export class Camera { mat4.mul(this._matViewProj, this._matProj, this._matView); mat4.invert(this._matViewProjInv, this._matViewProj); + vec3.set( + this._forward, + -this._matView.m02, + -this._matView.m06, + -this._matView.m10, + ); + this._node.getWorldPosition(this._position); + this._frustum.update(this._matViewProj, this._matViewProjInv); } @@ -259,6 +269,14 @@ export class Camera { return this._frustum; } + get forward () { + return this._forward; + } + + get position () { + return this._position; + } + set visibility (vis) { this._visibility = vis; } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 5da41535f7..72040b51e3 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -168,12 +168,14 @@ export class RenderScene { if (distance <= 0) { continue; } for (let i = 0; i < m.subModelNum; ++i) { const subModel = m.getSubModel(i).subMeshData; - if (!subModel || !subModel.geometricInfo) { continue; } - const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; - narrowphase(vb, ib, subModel.primitiveMode, sides); + if (subModel && subModel.geometricInfo) { + const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; + narrowphase(vb, ib, subModel.primitiveMode, sides); + } if (distance < Infinity) { const r = pool.add(); r.node = node; + // @ts-ignore r.distance = distance * vec3.magnitude(vec3.mul(v3, modelRay.d, node._scale)); results[pool.length - 1] = r; } From 8afef01d42e4acea43c35be82a04196dfbe20d33 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Tue, 22 Jan 2019 15:31:30 +0800 Subject: [PATCH 211/267] fix model error --- cocos/3d/framework/model-component.js | 20 +++++++++++++------- cocos/3d/memop/recycle-pool.ts | 1 + cocos/renderer/scene/model.ts | 24 ++++++++++++++++++++---- cocos/renderer/scene/submodel.ts | 1 + 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 76a4bb9edc..d9472711ae 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -163,7 +163,7 @@ export class ModelComponent extends RenderableComponent { this._model = null; } - get model () { + get model() { return this._model; } @@ -175,10 +175,13 @@ export class ModelComponent extends RenderableComponent { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); + this._model.enable = true; } onDisable() { - //this._getRenderScene().destroyModel(this._model); + if (this._model) { + this._model.enable = false; + } } onDestroy() { @@ -191,12 +194,12 @@ export class ModelComponent extends RenderableComponent { } if (this._model) { - this._getRenderScene().destroyModel(this._model); + this._model.destroy(); + } else { + this._model = this._createModel(); } - let model = this._createModel(); - model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); - this._model = model; + this._model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._updateModelParams(); } @@ -211,7 +214,7 @@ export class ModelComponent extends RenderableComponent { for (let i = 0; i < meshCount; ++i) { let material = this.getSharedMaterial(i); let subMeshData = this._mesh.renderingMesh.getSubmesh(i); - this._model.setSubModel(i, subMeshData, material); + this._model.initSubModel(i, subMeshData, material); } } @@ -223,6 +226,9 @@ export class ModelComponent extends RenderableComponent { } _clearMaterials() { + if (this._model == null) { + return; + } for (let i = 0; i < this._model.subModelNum; ++i) { this._onMaterialModified(i, null); } diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/3d/memop/recycle-pool.ts index fb48e86b17..1fac7f0aba 100644 --- a/cocos/3d/memop/recycle-pool.ts +++ b/cocos/3d/memop/recycle-pool.ts @@ -33,6 +33,7 @@ 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); } } } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index b601af39d1..29df1a3929 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -19,7 +19,7 @@ const _temp_mat4 = mat4.create(); const _subMeshPool = new RecyclePool(() => { return new SubModel(); -}, 100); +}, 32); /** * A representation of a model @@ -41,7 +41,7 @@ export class Model { private _matPSORecord: Map; private _matRefCount: Map; private _uboLocal: UBOLocal; - private _localUBO: GFXBuffer; + private _localUBO: GFXBuffer | null; /** * Setup a default empty model @@ -69,6 +69,13 @@ export class Model { subModel.destroy(); _subMeshPool.remove(subModel); } + if (this._localUBO) { + this._localUBO.destroy(); + this._localUBO = null; + } + this._worldBounds = null; + this._modelBounds = null; + this._subModels.splice(0); this._matPSORecord.clear(); this._matRefCount.clear(); } @@ -174,7 +181,7 @@ export class Model { return this._viewID; } - public setSubModel (idx: number, subMeshData: IRenderingSubmesh, mat: Material) { + public initSubModel (idx: number, subMeshData: IRenderingSubmesh, mat: Material) { if (this._subModels[idx] == null) { this._subModels[idx] = _subMeshPool.add(); } else { @@ -213,10 +220,19 @@ export class Model { } protected createPipelineState (mat: Material): GFXPipelineState[] { + if (this._localUBO) { + this._localUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: UBOLocal.SIZE, + stride: UBOLocal.SIZE, + }); + this._localUBO.update(this._uboLocal.view); + } const ret = new Array(mat.passes.length); for (let i = 0; i < ret.length; i++) { ret[i] = mat.passes[i].createPipelineState()!; - ret[i].pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this.localUBO); + ret[i].pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this.localUBO!); } return ret; } diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index 79d0b403c6..345c800121 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -44,6 +44,7 @@ export class SubModel { for (const cmdBuffer of this._cmdBuffers) { cmdBuffer.destroy(); } + this._cmdBuffers.splice(0); } set priority (val: RenderPriority) { From 3b220076a58d2f0fbf43da068f28d2edb5511800 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Tue, 22 Jan 2019 15:38:01 +0800 Subject: [PATCH 212/267] fix localUBO error --- cocos/renderer/scene/model.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 29df1a3929..999cf72549 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -55,13 +55,7 @@ export class Model { this._matPSORecord = new Map(); this._matRefCount = new Map(); this._uboLocal = new UBOLocal(); - this._localUBO = this._device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST, - size: UBOLocal.SIZE, - stride: UBOLocal.SIZE, - }); - this._localUBO.update(this._uboLocal.view); + this._localUBO = null; } public destroy () { @@ -123,7 +117,9 @@ export class Model { mat4.array(_temp_floatx16, _temp_mat4); this._uboLocal.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_IT_OFFSET); - this._localUBO.update(this._uboLocal.view); + if (this._localUBO) { + this._localUBO.update(this._uboLocal.view); + } for (const mat of this._matPSORecord.keys()) { for (const pass of mat.passes) { @@ -220,7 +216,7 @@ export class Model { } protected createPipelineState (mat: Material): GFXPipelineState[] { - if (this._localUBO) { + if (this._localUBO == null) { this._localUBO = this._device.createBuffer({ usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST, From 905b5f70813be505191e29901a48b59d0f8ffcf2 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Tue, 22 Jan 2019 16:42:54 +0800 Subject: [PATCH 213/267] fix default material --- cocos/3d/builtin/init.js | 1 + cocos/3d/framework/model-component.js | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js index 62843f198f..6ace146fb3 100644 --- a/cocos/3d/builtin/init.js +++ b/cocos/3d/builtin/init.js @@ -107,6 +107,7 @@ let builtinResMgr = { // [defaultTextureCube._uuid]: defaultTextureCub [blackTexture._uuid]: blackTexture, [whiteTexture._uuid]: whiteTexture, + [defaultMtl._uuid]: defaultMtl, [spriteMtl._uuid]: spriteMtl, [spriteFrame._uuid]:spriteFrame }; diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index d9472711ae..5195ebde8c 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -189,7 +189,7 @@ export class ModelComponent extends RenderableComponent { } _updateModels(forceUpdate) { - if (!this.enabled || !this.node._scene || (this._model && !forceUpdate)) { + if (!this.enabled || !this.node._scene || !this._mesh || (this._model && !forceUpdate)) { return; } @@ -214,7 +214,7 @@ export class ModelComponent extends RenderableComponent { for (let i = 0; i < meshCount; ++i) { let material = this.getSharedMaterial(i); let subMeshData = this._mesh.renderingMesh.getSubmesh(i); - this._model.initSubModel(i, subMeshData, material); + this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial()); } } From a074b2c217d8ff266e72b234d9eb7681f685c599 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Tue, 22 Jan 2019 18:55:11 +0800 Subject: [PATCH 214/267] add floating texture to GFXFeature --- cocos/3d/ui/mesh-buffer.ts | 3 +- cocos/core/platform/CCView.js | 8 +- cocos/gfx/command-allocator.ts | 1 + cocos/gfx/device.ts | 8 + cocos/gfx/webgl/webgl-command-allocator.ts | 5 +- cocos/gfx/webgl/webgl-device.ts | 11 +- cocos/renderer/ui/ui-material.ts | 51 +++++ cocos/renderer/ui/ui.ts | 206 +++++++++------------ 8 files changed, 171 insertions(+), 122 deletions(-) create mode 100644 cocos/renderer/ui/ui-material.ts diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts index db84548763..35e439bfc0 100644 --- a/cocos/3d/ui/mesh-buffer.ts +++ b/cocos/3d/ui/mesh-buffer.ts @@ -35,7 +35,6 @@ export class MeshBuffer { private _initIDataCount: number = 0; private _dirty: boolean = false; - constructor (/*device: GFXDevice*/) { // const device = cc.game._renderContext; @@ -157,7 +156,7 @@ export class MeshBuffer { // } // } - if (this.vData && this.vData.byteLength === this._initVDataCount){ + if (this.vData && this.vData.byteLength === this._initVDataCount) { return; } diff --git a/cocos/core/platform/CCView.js b/cocos/core/platform/CCView.js index b3a42a57f6..b63807bef8 100644 --- a/cocos/core/platform/CCView.js +++ b/cocos/core/platform/CCView.js @@ -552,8 +552,12 @@ class View extends EventTarget { var canvas = game.canvas; var container = game.container; - canvas.width = width * this._devicePixelRatio; - canvas.height = height * this._devicePixelRatio; + //canvas.width = width * this._devicePixelRatio; + //canvas.height = height * this._devicePixelRatio; + + const w = width * this._devicePixelRatio; + const h = height * this._devicePixelRatio; + cc.director.root.resize(w, h); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; diff --git a/cocos/gfx/command-allocator.ts b/cocos/gfx/command-allocator.ts index 56a96506d3..6bcc133239 100644 --- a/cocos/gfx/command-allocator.ts +++ b/cocos/gfx/command-allocator.ts @@ -1,6 +1,7 @@ import { GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; +// tslint:disable-next-line:no-empty-interface export interface IGFXCommandAllocatorInfo { } diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index fcab2760b7..e9d17c6ba7 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -16,6 +16,9 @@ import { GFXTextureView, IGFXTextureViewInfo } from './texture-view'; import { GFXWindow, IGFXWindowInfo } from './window'; export enum GFXFeature { + TEXTURE_FLOAT, + TEXTURE_HALF_FLOAT, + COUNT, } export interface IGFXDeviceInfo { @@ -105,6 +108,7 @@ export abstract class GFXDevice { protected _renderer: string = ''; protected _vendor: string = ''; protected _version: string = ''; + protected _features: boolean[] = new Array(GFXFeature.COUNT); protected _queue: GFXQueue | null = null; protected _width: number = 0; protected _height: number = 0; @@ -145,6 +149,10 @@ export abstract class GFXDevice { public abstract copyImageSourceToTexture (source: CanvasImageSource, texture: GFXTexture, regions: GFXBufferTextureCopy[]); public abstract copyFramebufferToBuffer (srcFramebuffer: GFXFramebuffer, dstBuffer: ArrayBuffer, regions: GFXBufferTextureCopy[]); + public hasFeature (feature: GFXFeature): boolean { + return this._features[feature]; + } + public genShaderId (): number { return this._shaderIdGen++; } diff --git a/cocos/gfx/webgl/webgl-command-allocator.ts b/cocos/gfx/webgl/webgl-command-allocator.ts index fa5790db8d..12bdee0502 100644 --- a/cocos/gfx/webgl/webgl-command-allocator.ts +++ b/cocos/gfx/webgl/webgl-command-allocator.ts @@ -27,12 +27,11 @@ export class WebGLGFXCommandPool { this._freeIdx = count - 1; } - /* public alloc (clazz: new() => T): T { return new clazz(); } - */ + /* public alloc (clazz: new() => T): T { if (this._freeIdx < 0) { const size = this._frees.length * 2; @@ -56,6 +55,7 @@ export class WebGLGFXCommandPool { ++cmd.refCount; return cmd; } + */ public free (cmd: T) { if (--cmd.refCount === 0) { @@ -64,6 +64,7 @@ export class WebGLGFXCommandPool { } public freeCmds (cmds: CachedArray) { + return ; for (let i = 0; i < cmds.length; ++i) { if (--cmds.array[i].refCount === 0) { this._freeCmds.push(cmds.array[i]); diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index a585011c53..fc56e5b707 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -15,7 +15,7 @@ import { GFXTextureType, GFXTextureViewType, } from '../define'; -import { GFXDevice, IGFXDeviceInfo } from '../device'; +import { GFXDevice, GFXFeature, IGFXDeviceInfo } from '../device'; import { GFXFramebuffer, IGFXFramebufferInfo } from '../framebuffer'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../input-assembler'; import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../pipeline-layout'; @@ -351,6 +351,15 @@ export class WebGLGFXDevice extends GFXDevice { this._OES_element_index_uint = gl.getExtension('OES_element_index_uint'); this._ANGLE_instanced_arrays = gl.getExtension('ANGLE_instanced_arrays'); + this._features.fill(false); + if (this._OES_texture_float) { + this._features[GFXFeature.TEXTURE_FLOAT] = true; + } + + if (this._OES_texture_half_float) { + this._features[GFXFeature.TEXTURE_HALF_FLOAT] = true; + } + // init states this.initStates(gl); diff --git a/cocos/renderer/ui/ui-material.ts b/cocos/renderer/ui/ui-material.ts new file mode 100644 index 0000000000..1dee43b2da --- /dev/null +++ b/cocos/renderer/ui/ui-material.ts @@ -0,0 +1,51 @@ +import { Material } from '../../3d/assets/material'; +import { GFXBindingLayout } from '../../gfx/binding-layout'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { Pass } from '../core/pass'; + +export interface IUIMaterialInfo { + material: Material; +} + +export class UIMaterial { + + public get material (): Material { + return this._material!; + } + + public get pass (): Pass { + return this._pass!; + } + + public get pipelineState (): GFXPipelineState { + return this._pipelineState!; + } + + public get bindingLayout (): GFXBindingLayout { + return this._bindingLayout!; + } + + protected _material: Material | null = null; + protected _pass: Pass | null = null; + protected _pipelineState: GFXPipelineState | null = null; + protected _bindingLayout: GFXBindingLayout | null = null; + + constructor () { + } + + public initialize (info: IUIMaterialInfo): boolean { + this._material = info.material; + + this._pass = this._material.passes[0]; + this._pipelineState = this._pass.createPipelineState(); + this._bindingLayout = this._pipelineState!.pipelineLayout.layouts[0]; + + return true; + } + + public destroy () { + this._bindingLayout = null; + this._pipelineState = null; + this._material = null; + } +} diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 6a8ea70132..5e407f0606 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -25,26 +25,18 @@ import { BaseNode } from '../../scene-graph/base-node'; import { Pass } from '../core/pass'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; +import { IUIMaterialInfo, UIMaterial } from './ui-material'; export interface IUIBufferBatch { vb: GFXBuffer; ib: GFXBuffer; -} - -export interface IUIMaterial { - material: Material; - bindingLayout: GFXBindingLayout; - pipelineLayout: GFXPipelineLayout; - pipelineState: GFXPipelineState; + ia: GFXInputAssembler; } export interface IUIRenderItem { camera: Camera; - pass: Pass; - bindingLayout: GFXBindingLayout; - pipelineLayout: GFXPipelineLayout; - pipelineState: GFXPipelineState; - inputAssembler: GFXInputAssembler; + bufferBatch: IUIBufferBatch; + uiMaterial: UIMaterial; } export interface IUIRenderData { @@ -68,8 +60,9 @@ export class UI { private _scene: RenderScene; private _attributes: IGFXInputAttribute[] = []; private _bufferBatches: IUIBufferBatch[] = []; - private _uiMaterials: IUIMaterial[] = []; - private _items: CachedArray; + private _uiMaterial: UIMaterial | null = null; + private _uiMaterials: UIMaterial[] = []; + private _items: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; @@ -90,9 +83,9 @@ export class UI { public initialize () { this._attributes = [ - { name: 'a_color', format: GFXFormat.RGBA32F, binding: 0, }, - { name: 'a_position', format: GFXFormat.RGB32F, binding: 1, }, - { name: 'a_texCoord', format: GFXFormat.RG32F, binding: 2, }, + { name: 'a_color', format: GFXFormat.RGBA32F, binding: 0 }, + { name: 'a_position', format: GFXFormat.RGB32F, binding: 1 }, + { name: 'a_texCoord', format: GFXFormat.RG32F, binding: 2 }, ]; this.createBufferBatch(); @@ -102,17 +95,22 @@ export class UI { type: GFXCommandBufferType.PRIMARY, }); + // create ui material + + /* + const material = new Material(); + material.effectName = 'sprite-material'; + // material.setProperty('mainTexture', texture); + material.update(); + + this._uiMaterial = this.createUIMaterial( { material }); + */ + return true; } public destroy () { - - for (const uiMaterial of this._uiMaterials) { - uiMaterial.bindingLayout.destroy(); - uiMaterial.pipelineLayout.destroy(); - uiMaterial.pipelineState.destroy(); - } - this._uiMaterials = []; + this.destroyUIMaterials(); for (const buffBatch of this._bufferBatches) { buffBatch.vb.destroy(); @@ -126,46 +124,32 @@ export class UI { } } - /* - public registerMaterial (material: Material): IUIMaterial { - const pass = material.passes[0]; - for (const mtrl of this._uiMaterials) { - if (mtrl.pass === pass) { - return mtrl; + public createUIMaterial (info: IUIMaterialInfo): UIMaterial | null { + const uiMtrl = new UIMaterial(); + if (uiMtrl.initialize(info)) { + this._uiMaterials.push(uiMtrl); + return uiMtrl; + } else { + return null; + } + } + + 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; } } - - const bindingLayout = this._device.createBindingLayout({ - bindings: pass.bindings, - }); - - const pipelineLayout = this._device.createPipelineLayout({ - layouts: [bindingLayout], - }); - - const pipelineState = this._device.createPipelineState({ - primitive: pass.primitive, - shader: pass.shader, - is: { attributes: this._attributes }, - rs: pass.rasterizerState, - dss: pass.depthStencilState, - bs: pass.blendState, - layout: pipelineLayout, - renderPass: pass.renderPass, - }); - - const uiMaterial = { - pass, - bindingLayout, - pipelineLayout, - pipelineState, - }; - - this._uiMaterials.push(uiMaterial); - - return uiMaterial; } - */ + + public destroyUIMaterials () { + for (const uiMaterial of this._uiMaterials) { + uiMaterial.destroy(); + } + this._uiMaterials = []; + } public addScreen (comp) { this._screens.push(comp); @@ -198,26 +182,62 @@ export class UI { return buffer; } - public createUIRenderData(){ + public createUIRenderData () { return this._commitUIRenderDataPool.add(); } - public addToQueue(uiRenderData: IUIRenderData){ + public addToQueue (uiRenderData: IUIRenderData) { this._commitUIRenderDatas.push(uiRenderData); } - public flush(){ - this.render(); - } - public update (dt: number) { this._items.clear(); - // TODO: Merge batch here. this._renderScreens(); - // this.render(); - this.flush(); + // TODO: Merge batch here. + let curCamera: Camera | null = null; + + for (const uiRenderData of this._commitUIRenderDatas) { + + if (curCamera !== uiRenderData.camera) { + curCamera = uiRenderData.camera; + } + + // uiRenderData.meshBuffer.iData.length; + } + } + + public render () { + + const material = this._uiMaterial!; + + if (this._items.length) { + const framebuffer = this._root.curWindow!.framebuffer; + const cmdBuff = this._cmdBuff!; + + cmdBuff.begin(); + + for (let i = 0; i < this._items.length; ++i) { + const item = this._items.array[i]; + const camera = item.camera; + + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; + + cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); + cmdBuff.bindPipelineState(material.pipelineState); + cmdBuff.bindBindingLayout(material.bindingLayout); + // cmdBuff.bindInputAssembler(item.meshBuffer.indiceOffset); + // cmdBuff.draw(item.inputAssembler); + + cmdBuff.endRenderPass(); + } + + cmdBuff.end(); + + this._device.queue.submit([cmdBuff]); + } } private _walk (node, fn1, fn2, level = 0) { @@ -273,50 +293,6 @@ export class UI { comp.postUpdateAssembler(); } - private render () { - /* - const framebuffer = this._root.curWindow!.framebuffer; - const cmdBuff = this._cmdBuff!; - - cmdBuff.begin(); - cmdBuff.beginRenderPass(framebuffer, this._renderArea, - [{r: 1, g: 1, b: 1, a: 1}], 1.0, 0); - - cmdBuff.end(); - - this._device.queue.submit([cmdBuff]); - */ - - if (this._items.length) { - const framebuffer = this._root.curWindow!.framebuffer; - const cmdBuff = this._cmdBuff!; - - cmdBuff.begin(); - - for (let i = 0; i < this._items.length; ++i) { - const item = this._items.array[i]; - const camera = item.camera; - - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; - - cmdBuff.beginRenderPass(framebuffer, this._renderArea, - [camera.clearColor], camera.clearDepth, camera.clearStencil); - - cmdBuff.bindPipelineState(item.pipelineState); - cmdBuff.bindBindingLayout(item.bindingLayout); - cmdBuff.bindInputAssembler(item.inputAssembler); - cmdBuff.draw(item.inputAssembler); - - cmdBuff.endRenderPass(); - } - - cmdBuff.end(); - - this._device.queue.submit([cmdBuff]); - } - } - private createBufferBatch (): IUIBufferBatch { const vbStride = Float32Array.BYTES_PER_ELEMENT * 6; @@ -343,7 +319,7 @@ export class UI { indexBuffer: ib, }); - const batch: IUIBufferBatch = { vb, ib }; + const batch: IUIBufferBatch = { vb, ib, ia }; this._bufferBatches.push(batch); return batch; } From a62bfdb7684024fbab22b8577d254832d1a5c8d0 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Tue, 22 Jan 2019 17:21:55 +0800 Subject: [PATCH 215/267] fix some bug --- cocos/3d/framework/model-component.js | 6 +++--- cocos/scene-graph/base-node.ts | 20 +++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 5195ebde8c..1b0d59561b 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -175,7 +175,6 @@ export class ModelComponent extends RenderableComponent { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); - this._model.enable = true; } onDisable() { @@ -198,6 +197,7 @@ export class ModelComponent extends RenderableComponent { } else { this._model = this._createModel(); } + this._model.enable = this.enabled; this._model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); @@ -235,7 +235,7 @@ export class ModelComponent extends RenderableComponent { } _updateCastShadow() { - if (!this.enabled) + if (!this.enabled || !this._model) return; if (this._shadowCastingMode === ModelShadowCastingMode.Off) { for (let i = 0; i < this._model.subModelNum; ++i) { @@ -253,7 +253,7 @@ export class ModelComponent extends RenderableComponent { } _updateReceiveShadow() { - if (!this.enabled) + if (!this.enabled || !this._model) return; for (let i = 0; i < this._model.subModelNum; ++i) { let subModel = this._model.getSubModel(i); diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index f6d5fa4aca..57df433741 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -286,7 +286,7 @@ export class BaseNode extends CCObject { private static _findChildComponents (children: BaseNode[], constructor, components) { for (const node of children) { - BaseNode._findComponents (node, constructor, components); + BaseNode._findComponents(node, constructor, components); if (node._children.length > 0) { BaseNode._findChildComponents(node._children, constructor, components); } @@ -1058,13 +1058,15 @@ export class BaseNode extends CCObject { return; } - public emit? (type: string, ...args: any[]): void; + public emit?(type: string, ...args: any[]): void; protected _onSetParent (oldParent: this | null) { - if ((oldParent == null || oldParent._scene !== this._parent!._scene) && this._parent!._scene != null) { - this.walk((node) => { - BaseNode._setScene(node); - }); + if (this._parent) { + if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) { + this.walk((node) => { + BaseNode._setScene(node); + }); + } } } @@ -1252,11 +1254,11 @@ export class BaseNode extends CCObject { } } - private _onSiblingIndexChanged? (siblingIndex: number): void; + private _onSiblingIndexChanged?(siblingIndex: number): void; - private _registerIfAttached? (attached: boolean): void; + private _registerIfAttached?(attached: boolean): void; - private _checkMultipleComp? (constructor: Function): boolean; + private _checkMultipleComp?(constructor: Function): boolean; private _onPreDestroyBase () { return this._onPreDestroy(); From 34429bdda0032ba3ee6da1e7e5549b66ec49d5e6 Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Tue, 22 Jan 2019 18:26:40 +0800 Subject: [PATCH 216/267] add texture to IUIRenderData --- cocos/3d/ui/assembler/sprite/simple.ts | 1 + cocos/renderer/ui/ui.ts | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts index fb172af088..b842fa6f9f 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -140,6 +140,7 @@ export const simple: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; + commitBuffer.texture = sprite.spriteFrame!; commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 5e407f0606..2e51e75b05 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -25,7 +25,11 @@ import { BaseNode } from '../../scene-graph/base-node'; import { Pass } from '../core/pass'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; +<<<<<<< HEAD import { IUIMaterialInfo, UIMaterial } from './ui-material'; +======= +import { SpriteFrame } from '../../assets/CCSpriteFrame'; +>>>>>>> 86462dac... add texture to IUIRenderData export interface IUIBufferBatch { vb: GFXBuffer; @@ -42,6 +46,7 @@ export interface IUIRenderItem { export interface IUIRenderData { meshBuffer: MeshBuffer; material: Material; + texture: SpriteFrame, camera: Camera; } @@ -277,12 +282,12 @@ export class UI { private _reset () { this._bufferPool.reset(); this._commitUIRenderDataPool.reset(); - this._commitUIRenderDatas.length = 0; } private _commitComp (comp: UIRenderComponent) { comp.updateAssembler(this); // const canvasComp: CanvasComponent | null = this.getScreen(comp.viewID); + // const renderDataFormat: IUIRenderData = this._commitUIRenderDataPool.add(); // renderDataFormat.meshBuffer = buffer; // renderDataFormat.material = comp.material as Material; From 26334ad0b5827bee95081438105d2310c34e8230 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 23 Jan 2019 10:23:16 +0800 Subject: [PATCH 217/267] add skinning ubo --- cocos/renderer/core/program-lib.ts | 4 +++ cocos/renderer/models/model-uniforms.ts | 18 ++++++++++++ cocos/renderer/models/skinning-model.js | 38 +++++++++++++++++-------- cocos/renderer/scene/model.ts | 6 +++- 4 files changed, 53 insertions(+), 13 deletions(-) create mode 100644 cocos/renderer/models/model-uniforms.ts diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 0d3852923f..269196da27 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -6,6 +6,7 @@ import { GFXDevice } from '../../gfx/device'; import { GFXShader, GFXUniform, GFXUniformBlock } from '../../gfx/shader'; import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; import { IDefineMap } from './effect'; +import { SkinningUBO } from '../models/model-uniforms'; function _generateDefines ( device: GFXDevice, @@ -83,6 +84,9 @@ export class ProgramLib { } else { // boolean def._map = ((value: any) => (value ? (1 << def._offset) : 0)); } + if (def.name === 'CC_USE_SKINNING') { + tmpl.blocks = tmpl.blocks.concat(convertToBlockInfo(SkinningUBO.BLOCK)); + } offset += cnt; def._offset = offset; } diff --git a/cocos/renderer/models/model-uniforms.ts b/cocos/renderer/models/model-uniforms.ts new file mode 100644 index 0000000000..b28f62485a --- /dev/null +++ b/cocos/renderer/models/model-uniforms.ts @@ -0,0 +1,18 @@ +import { GFXType } from '../../gfx/define'; +import { GFXUniformBlock } from '../../gfx/shader'; + +export class SkinningUBO { + public static MAT_JOINT_OFFSET: number = 0; + public static JOINTS_TEXTURE_SIZE_OFFSET: number = SkinningUBO.MAT_JOINT_OFFSET + 128 * 4; + public static COUNT: number = SkinningUBO.MAT_JOINT_OFFSET + 4; + public static SIZE: number = SkinningUBO.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 29, name: 'CCSkinning', members: [ + { name: 'cc_matJoint', type: GFXType.MAT4, count: 128 }, + { name: 'cc_jointsTextureSize', type: GFXType.FLOAT4, count: 1 }, + ], + }; + + // public view: Float32Array = new Float32Array(SkinningUBO.COUNT); +} diff --git a/cocos/renderer/models/skinning-model.js b/cocos/renderer/models/skinning-model.js index 7239ecf85e..53a8af9c92 100644 --- a/cocos/renderer/models/skinning-model.js +++ b/cocos/renderer/models/skinning-model.js @@ -1,21 +1,35 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { Model } from '../scene/model'; +import { SkinningUBO } from './model-uniforms'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; export default class SkinningModel extends Model { - constructor() { - super(); + constructor() { + super(); - this._type = 'skinning'; - this._jointsTexture = null; - this._jointsMatrixArray = null; - } + this._type = 'skinning'; + this._jointsTexture = null; + this._jointsMatrixArray = null; + } - setJointsTexture(texture) { - this._jointsTexture = texture; - } + setJointsTexture(texture) { + this._jointsTexture = texture; + } - setJointsMatrixArray(a) { - this._jointsMatrixArray = a; - } + setJointsMatrixArray(a) { + this._jointsMatrixArray = a; + this._skinningUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: SkinningUBO.SIZE, + stride: SkinningUBO.SIZE, + }); + this._skinningUBO.update(this._jointsMatrixArray); + } + + _onCreatePSO(pso) { + super._onCreatePSO(pso); + pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); + } } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 999cf72549..e0a9a781e7 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -228,7 +228,7 @@ export class Model { const ret = new Array(mat.passes.length); for (let i = 0; i < ret.length; i++) { ret[i] = mat.passes[i].createPipelineState()!; - ret[i].pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this.localUBO!); + this._onCreatePSO(ret[i]); } return ret; } @@ -257,6 +257,10 @@ export class Model { } } + protected _onCreatePSO (pso: GFXPipelineState) { + pso.pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this.localUBO!); + } + /** * Set the user key * @param {number} key From b2c0b365b9d3246b6c75d6fb959a447da26c1730 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 22 Jan 2019 16:28:09 +0800 Subject: [PATCH 218/267] material tech index --- cocos/3d/assets/effect-asset.ts | 4 ++-- cocos/3d/assets/material.ts | 1 + cocos/core/game.js | 2 -- cocos/pipeline/render-pipeline.ts | 16 ++++++++-------- cocos/renderer/core/effect.ts | 6 ++++-- cocos/renderer/core/pass.ts | 3 ++- cocos/renderer/core/program-lib.ts | 20 ++++++++++++-------- cocos/renderer/scene/camera.ts | 2 +- cocos/renderer/scene/render-scene.ts | 2 +- 9 files changed, 31 insertions(+), 25 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 0545c4d194..51bcdf4d04 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -3,6 +3,7 @@ import { ccclass, property } from '../../core/data/class-decorator'; import { GFXDynamicState, GFXPrimitiveMode } from '../../gfx/define'; import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; import { RenderPassStage } from '../../pipeline/define'; +import { programLib } from '../../renderer/core/program-lib'; export interface IPropertyInfo { type: number; // auto-extracted if not specified @@ -97,8 +98,7 @@ export class EffectAsset extends Asset { public shaders: IShaderInfo[] = []; public onLoaded () { - const lib = cc.game._programLib; - this.shaders.forEach((s) => lib.define(s)); + this.shaders.forEach((s) => programLib.define(s)); EffectAsset.register(this); } } diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 1b9b95941d..f4156a77f4 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -143,6 +143,7 @@ export class Material extends Asset { } public copy (mat: Material) { + this._techIdx = mat._techIdx; this._props.length = mat._props.length; this._props.fill({}); for (let i = 0; i < mat._props.length; i++) { diff --git a/cocos/core/game.js b/cocos/core/game.js index ac46a63bec..0f4b1f7233 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -32,7 +32,6 @@ import { addon } from './utils/js'; import * as renderer from '../renderer'; import gfx from '../renderer/gfx'; import builtinResMgr from '../3d/builtin/init'; -import { ProgramLib } from '../renderer/core/program-lib'; /** * @module cc @@ -818,7 +817,6 @@ var game = { }, _initBuiltins: function() { - this._programLib = new ProgramLib(this._gfxDevice); builtinResMgr.initBuiltinRes(this._gfxDevice); // this._renderer.setBuiltins({ // defaultTexture: builtins['default-texture']._texture, diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index ae5756a941..3198a85137 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -65,7 +65,6 @@ export class UBOLocal { const _vec4Array = new Float32Array(4); const _mat4Array = new Float32Array(16); const _outMat = new Mat4(); -const _outVec3 = new Vec3(); export abstract class RenderPipeline { @@ -311,27 +310,28 @@ export abstract class RenderPipeline { _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.SCREEN_SCALE_OFFSET); - mat4.array(_mat4Array, view.camera.matView); + const camera = view.camera; + mat4.array(_mat4Array, camera.matView); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_OFFSET); - mat4.invert(_outMat, view.camera.matView); + mat4.invert(_outMat, camera.matView); mat4.array(_mat4Array, _outMat); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_INV_OFFSET); - mat4.array(_mat4Array, view.camera.matProj); + mat4.array(_mat4Array, camera.matProj); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_OFFSET); - mat4.invert(_outMat, view.camera.matProj); + mat4.invert(_outMat, camera.matProj); mat4.array(_mat4Array, _outMat); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_PROJ_INV_OFFSET); - mat4.array(_mat4Array, view.camera.matViewProj); + mat4.array(_mat4Array, camera.matViewProj); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_OFFSET); - mat4.array(_mat4Array, view.camera.matViewProjInv); + mat4.array(_mat4Array, camera.matViewProjInv); this._uboGlobal.view.set(_mat4Array, UBOGlobal.MAT_VIEW_PROJ_INV_OFFSET); - vec3.array(_vec4Array, view.camera.node && view.camera.node.getWorldPosition(_outVec3)); + vec3.array(_vec4Array, camera.position); _vec4Array[3] = 1.0; this._uboGlobal.view.set(_vec4Array, UBOGlobal.CAMERA_POS_OFFSET); diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 82f375b1de..461477c87a 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -3,6 +3,7 @@ import { EffectAsset } from '../../3d/assets/effect-asset'; import { RenderPassStage } from '../../pipeline/define'; import { IPassInfoFull, Pass } from './pass'; +import { programLib } from './program-lib'; export interface IDefineMap { [name: string]: number | boolean; } export interface IEffectInfo { @@ -23,8 +24,9 @@ export class Effect { const passes: Pass[] = new Array(passNum); for (let k = 0; k < passNum; ++k) { const passInfo = tech.passes[k] as IPassInfoFull; - const prog = cc.game._programLib.getTemplate(passInfo.program); - passInfo.shader = cc.game._programLib.getGFXShader(passInfo.program, defines && defines[k] || {}); + const prog = programLib.getTemplate(passInfo.program); + passInfo.shader = programLib.getGFXShader(cc.game._gfxDevice, + passInfo.program, defines && defines[k] || {})!; passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); passInfo.globals = cc.director.root.pipeline.globalUBO; passInfo.blocks = prog!.blocks; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 54b321faa7..fa5f12b445 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -305,7 +305,8 @@ export class Pass { } public serializePipelineStates () { - let res = `${this._shader && this._shader.name},${this._stage},${this._primitive}`; + const shaderName = this._shader && this._shader.name; + let res = `${shaderName},${this._stage},${this._primitive}`; res += serializeBlendState(this._bs); res += serializeDepthStencilState(this._dss); res += serializeRasterizerState(this._rs); diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 269196da27..bb4f7964d3 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -37,14 +37,13 @@ interface IProgramInfo extends IShaderInfo { id: number; defines: IDefineRecord[]; } -export class ProgramLib { - protected _device: GFXDevice; + +class ProgramLib { protected _precision: string; protected _templates: Record; protected _cache: Record; - constructor (device: GFXDevice) { - this._device = device; + constructor () { this._precision = `precision highp float;\n`; this._templates = {}; this._cache = {}; @@ -61,7 +60,9 @@ export class ProgramLib { * { name: 'shadow', type: 'boolean' }, * { name: 'lightCount', type: 'number', range: [1, 4] } * ], - * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }], + * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [ + * { name: 'color', type: 'vec4' }], defines: [] } + * ], * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, * }; * programLib.define(program); @@ -118,7 +119,7 @@ export class ProgramLib { return key << 8 | (tmpl.id & 0xff); } - public getGFXShader (name: string, defines: IDefineMap = {}) { + public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap = {}) { const key = this.getKey(name, defines); let program = this._cache[key]; if (program !== undefined) { @@ -127,12 +128,12 @@ export class ProgramLib { // get template const tmpl = this._templates[name]; - const customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n'; + const customDef = _generateDefines(device, defines, tmpl.defines, tmpl.dependencies) + '\n'; const vert = customDef + tmpl.vert; const frag = customDef + tmpl.frag; const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name); - program = this._device.createShader({ + program = device.createShader({ name: instanceName, blocks: tmpl.blocks, samplers: tmpl.samplers, @@ -173,3 +174,6 @@ function convertToBlockInfo (block: GFXUniformBlock): IBlockInfo { size, }; } + +const programLib = cc.programLib = new ProgramLib(); +export { programLib }; diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index 6a8ed99b52..a67daf96a5 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -367,7 +367,7 @@ export class Camera { const cw = this._viewport.width * this._width; const ch = this._viewport.height * this._height; - vec3.transformMat4(out, worldPos, this.matViewProjInv); + vec3.transformMat4(out, worldPos, this.matViewProj); out.x = cx + (out.x + 1) * 0.5 * cw; out.y = cy + (out.y + 1) * 0.5 * ch; out.z = out.z * 0.5 + 0.5; diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 72040b51e3..f6e842d5d2 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -158,7 +158,7 @@ export class RenderScene { pool.reset(); for (const m of this._models) { const node = m.node; - if (!cc.Layers.check(node.layer, mask) || !m.modelBounds) { continue; } + if (!node.activeInHierarchy || !cc.Layers.check(node.layer, mask) || !m.modelBounds) { continue; } // transform ray back to model space mat4.invert(m4, node.getWorldMatrix(m4)); vec3.transformMat4(modelRay.o, worldRay.o, m4); From 3e8eb350726ca3973146d8255da14cdbd2434691 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 10:12:33 +0800 Subject: [PATCH 219/267] misc bugfix and restructure --- cocos/3d/assets/bitmap-font.js | 2 +- cocos/3d/assets/effect-asset.ts | 6 +- cocos/3d/assets/material.ts | 3 +- cocos/3d/assets/opentype-font.js | 9 +- cocos/3d/assets/texture-cube.ts | 6 +- cocos/3d/assets/texture-sprite.js | 5 +- cocos/3d/builtin/index.js | 0 cocos/3d/builtin/index.ts | 3 + cocos/3d/builtin/init.js | 132 -- cocos/3d/builtin/init.ts | 131 ++ cocos/3d/framework/camera-component.ts | 2 +- cocos/3d/framework/light-component.js | 3 - cocos/3d/framework/model-component.js | 21 +- .../framework/physics/rigid-body-component.ts | 12 +- cocos/3d/framework/render-system.js | 21 - cocos/3d/framework/renderSystemActor.js | 41 - cocos/3d/framework/skybox-component.js | 120 -- cocos/3d/framework/skybox-component.ts | 106 ++ cocos/3d/misc/utils.ts | 2 +- cocos/3d/primitive/{index.js => index.ts} | 0 cocos/3d/ui/components/label-component.ts | 6 +- cocos/3d/ui/components/mask-component.ts | 4 +- cocos/3d/ui/components/sprite-component.ts | 4 +- cocos/assets/CCSpriteFrame.ts | 2 +- cocos/assets/image-asset.ts | 2 +- cocos/assets/index.js | 6 +- cocos/assets/render-texture.ts | 6 +- cocos/assets/texture-2d.ts | 6 +- cocos/assets/texture-base.ts | 4 +- cocos/assets/texture-util.js | 4 +- cocos/components/WXSubContextView.js | 2 +- cocos/components/component.d.ts | 20 +- cocos/core/director.js | 1 - cocos/core/game.js | 16 +- cocos/gfx/webgl/webgl-commands.ts | 8 +- cocos/gfx/webgl/webgl-state-cache.ts | 10 + cocos/load-pipeline/loader.js | 4 +- cocos/load-pipeline/unpackers.js | 2 +- cocos/pipeline/render-pipeline.ts | 2 +- cocos/renderer/core/base-renderer.js | 825 ----------- cocos/renderer/core/input-assembler.js | 31 - cocos/renderer/core/pass.ts | 16 +- cocos/renderer/core/view.js | 79 - cocos/renderer/enums.js | 47 - cocos/renderer/gfx/device.js | 1287 ----------------- cocos/renderer/gfx/enums.js | 336 ----- cocos/renderer/gfx/frame-buffer.js | 41 - cocos/renderer/gfx/index-buffer.js | 134 -- cocos/renderer/gfx/index.js | 40 - cocos/renderer/gfx/misc.js | 3 - cocos/renderer/gfx/program.js | 176 --- cocos/renderer/gfx/render-buffer.js | 42 - cocos/renderer/gfx/state.js | 133 -- cocos/renderer/gfx/texture-2d.js | 333 ----- cocos/renderer/gfx/texture-cube.js | 346 ----- cocos/renderer/gfx/texture.js | 52 - cocos/renderer/gfx/vertex-buffer.js | 154 -- cocos/renderer/gfx/vertex-format.js | 56 - cocos/renderer/{index.js => index.ts} | 7 - cocos/renderer/models/particle-batch-model.ts | 20 +- cocos/renderer/renderers/forward-renderer.js | 387 ----- cocos/renderer/renderers/gaussian-blur.js | 96 -- cocos/renderer/scene/model.ts | 4 +- cocos/renderer/scene/render-scene.ts | 5 +- cocos/renderer/scene/scene.js | 202 --- cocos/renderer/ui/ui.ts | 4 - playground/gizmo.html | 10 +- 67 files changed, 359 insertions(+), 5241 deletions(-) delete mode 100644 cocos/3d/builtin/index.js create mode 100644 cocos/3d/builtin/index.ts delete mode 100644 cocos/3d/builtin/init.js create mode 100644 cocos/3d/builtin/init.ts delete mode 100644 cocos/3d/framework/render-system.js delete mode 100644 cocos/3d/framework/renderSystemActor.js delete mode 100644 cocos/3d/framework/skybox-component.js create mode 100644 cocos/3d/framework/skybox-component.ts rename cocos/3d/primitive/{index.js => index.ts} (100%) delete mode 100644 cocos/renderer/core/base-renderer.js delete mode 100644 cocos/renderer/core/input-assembler.js delete mode 100644 cocos/renderer/core/view.js delete mode 100644 cocos/renderer/enums.js delete mode 100644 cocos/renderer/gfx/device.js delete mode 100644 cocos/renderer/gfx/enums.js delete mode 100644 cocos/renderer/gfx/frame-buffer.js delete mode 100644 cocos/renderer/gfx/index-buffer.js delete mode 100644 cocos/renderer/gfx/index.js delete mode 100644 cocos/renderer/gfx/misc.js delete mode 100644 cocos/renderer/gfx/program.js delete mode 100644 cocos/renderer/gfx/render-buffer.js delete mode 100644 cocos/renderer/gfx/state.js delete mode 100644 cocos/renderer/gfx/texture-2d.js delete mode 100644 cocos/renderer/gfx/texture-cube.js delete mode 100644 cocos/renderer/gfx/texture.js delete mode 100644 cocos/renderer/gfx/vertex-buffer.js delete mode 100644 cocos/renderer/gfx/vertex-format.js rename cocos/renderer/{index.js => index.ts} (71%) delete mode 100644 cocos/renderer/renderers/forward-renderer.js delete mode 100644 cocos/renderer/renderers/gaussian-blur.js delete mode 100644 cocos/renderer/scene/scene.js diff --git a/cocos/3d/assets/bitmap-font.js b/cocos/3d/assets/bitmap-font.js index 343aa2381c..668669542d 100644 --- a/cocos/3d/assets/bitmap-font.js +++ b/cocos/3d/assets/bitmap-font.js @@ -27,7 +27,7 @@ import { _decorator } from "../../core/data/index"; const { ccclass, property } = _decorator; import Font from "./font"; import vec2 from "../../core/vmath/vec2"; -import Texture2D from "../../assets/texture-2d"; +import { Texture2D } from "../../assets/texture-2d"; @ccclass('cc.BitmapFont') export class BitmapFont extends Font { diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 51bcdf4d04..3aef395d52 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -1,6 +1,6 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; -import { GFXDynamicState, GFXPrimitiveMode } from '../../gfx/define'; +import { GFXDynamicState, GFXPrimitiveMode, GFXType } from '../../gfx/define'; import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; import { RenderPassStage } from '../../pipeline/define'; import { programLib } from '../../renderer/core/program-lib'; @@ -31,7 +31,7 @@ export interface ITechniqueInfo { export interface IBlockMember { name: string; - type: number; + type: GFXType; count: number; size: number; } @@ -46,7 +46,7 @@ export interface ISamplerInfo { name: string; binding: number; defines: string[]; - type: number; + type: GFXType; count: number; } export interface IDefineInfo { diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index f4156a77f4..a740fad854 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -33,7 +33,7 @@ import { EffectAsset } from './effect-asset'; export interface IMaterialInfo { technique?: number; - defines?: IDefineMap[]; + defines?: IDefineMap | IDefineMap[]; effectName?: string; } @@ -229,6 +229,7 @@ export class Material extends Asset { if (this._owner) { const comp = this._owner; const index = comp.sharedMaterials.findIndex((m) => m === this); + // @ts-ignore if (index >= 0) { comp._onMaterialModified(index, this); } } } diff --git a/cocos/3d/assets/opentype-font.js b/cocos/3d/assets/opentype-font.js index bcf867b98b..12ac748ac5 100644 --- a/cocos/3d/assets/opentype-font.js +++ b/cocos/3d/assets/opentype-font.js @@ -23,13 +23,12 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import { _decorator } from "../../core/data/index"; -const {ccclass} = _decorator; +import { ccclass } from "../../core/data/class-decorator"; import Font from "./font"; -import vec2 from "../../core/vmath/vec2"; +import { vec2 } from "../../core/vmath"; import ShelfPack from "./utils/shelf-pack"; -import ImageAsset from "../../assets/image-asset"; -import Texture2D from "../../assets/texture-2d"; +import { ImageAsset } from "../../assets/image-asset"; +import { Texture2D } from "../../assets/texture-2d"; @ccclass('cc.OpentypeFont') export default class OpentypeFont extends Font { diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index 9b508c941e..d3a60944bd 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -24,8 +24,8 @@ ****************************************************************************/ // @ts-check import { Texture2D } from '../../assets'; -import ImageAsset from '../../assets/image-asset'; -import TextureBase from '../../assets/texture-base'; +import { ImageAsset } from '../../assets/image-asset'; +import { TextureBase } from '../../assets/texture-base'; import { ccclass, property } from '../../core/data/class-decorator'; import { GFXTextureFlagBit, GFXTextureViewType } from '../../gfx/define'; @@ -39,7 +39,7 @@ interface ITextureCubeMipmap { } @ccclass('cc.TextureCube') -export default class TextureCube extends TextureBase { +export class TextureCube extends TextureBase { /** * Gets the mipmap images. * Note that the result do not contains the auto generated mipmaps. diff --git a/cocos/3d/assets/texture-sprite.js b/cocos/3d/assets/texture-sprite.js index 1bc29e5e1b..50fc175f66 100644 --- a/cocos/3d/assets/texture-sprite.js +++ b/cocos/3d/assets/texture-sprite.js @@ -23,9 +23,8 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import Texture2D from '../../assets/texture-2d'; +import { ccclass, property } from "../../core/data/class-decorator"; +import { Texture2D } from '../../assets/texture-2d'; import Sprite from "./sprite"; @ccclass('cc.TextureSprite') diff --git a/cocos/3d/builtin/index.js b/cocos/3d/builtin/index.js deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cocos/3d/builtin/index.ts b/cocos/3d/builtin/index.ts new file mode 100644 index 0000000000..e0ce4607f2 --- /dev/null +++ b/cocos/3d/builtin/index.ts @@ -0,0 +1,3 @@ + +export * from './init'; +export { default as effects } from './effects'; diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js deleted file mode 100644 index 6ace146fb3..0000000000 --- a/cocos/3d/builtin/init.js +++ /dev/null @@ -1,132 +0,0 @@ -import Texture2D from '../../assets/texture-2d'; -import TextureCube from '../assets/texture-cube'; -import ImageAsset from '../../assets/image-asset'; -import { Material } from '../assets/material'; -import { EffectAsset } from '../assets/effect-asset'; -import effects from './effects'; -import { SpriteFrame} from '../../assets/CCSpriteFrame'; - -let builtinResMgr = { - // this should be called after renderer initialized - initBuiltinRes: function (device) { - builtinResMgr.device = device; - let canvas = document.createElement('canvas'); - let context = canvas.getContext('2d'); - - // ============================ - // builtin textures - // ============================ - - // default texture canvas fill - canvas.width = canvas.height = 128; - context.fillStyle = '#ddd'; - context.fillRect(0, 0, 128, 128); - context.fillStyle = '#555'; - context.fillRect(0, 0, 64, 64); - context.fillStyle = '#555'; - context.fillRect(64, 64, 64, 64); - - const canvasImage = new ImageAsset(canvas); - - // default-texture - let defaultTexture = new Texture2D(); - defaultTexture.setMipFilter(Texture2D.Filter.LINEAR); - defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR); - defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - defaultTexture._uuid = 'default-texture'; - defaultTexture.image = canvasImage; - - // default-texture-cube - // let defaultTextureCube = new TextureCube(); - // defaultTextureCube._uuid = 'default-texture-cube'; - // defaultTextureCube.image = { - // front: canvasImage, - // back: canvasImage, - // left: canvasImage, - // right: canvasImage, - // top: canvasImage, - // bottom: canvasImage, - // }; - - // black texture canvas fill - canvas.width = canvas.height = 2; - context.fillStyle = '#000'; - context.fillRect(0, 0, 2, 2); - - // black-texture - let blackTexture = new Texture2D(); - blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - blackTexture._uuid = 'black-texture'; - defaultTexture.image = canvasImage; - - // white texture canvas fill - canvas.width = canvas.height = 2; - context.fillStyle = '#fff'; - context.fillRect(0, 0, 2, 2); - - // white-texture - let whiteTexture = new Texture2D(); - blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - whiteTexture._uuid = 'white-texture'; - defaultTexture.image = canvasImage; - - let spriteFrame = new SpriteFrame(); - spriteFrame.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - spriteFrame.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); - spriteFrame._uuid = 'default-spriteframe'; - spriteFrame.setOriginalSize(cc.size(canvasImage.width, canvasImage.height)); - spriteFrame.setRect(0, 0, canvasImage.width, canvasImage.height); - spriteFrame.image = canvasImage; - if (spriteFrame.onLoaded) { - spriteFrame.onLoaded(); - } - - // essential builtin effects - let efxs = effects.map(e => { - let effect = Object.assign(new EffectAsset(), e); - effect.onLoaded(); return effect; - }); - - // default material - let defaultMtl = new Material(); - defaultMtl._uuid = 'default-material'; - defaultMtl.setDefines({ USE_COLOR: true }); - defaultMtl.effectName = 'builtin-effect-unlit'; - defaultMtl.setProperty('color', cc.color('#FF00FF')); - - // sprite material - let spriteMtl = new Material(); - spriteMtl._uuid = 'sprite-material'; - spriteMtl.effectName = 'builtin-effect-sprite'; - defaultMtl.setProperty('mainTexture', defaultTexture); - - let builtins = { - [defaultTexture._uuid]: defaultTexture, - // [defaultTextureCube._uuid]: defaultTextureCub - [blackTexture._uuid]: blackTexture, - [whiteTexture._uuid]: whiteTexture, - [defaultMtl._uuid]: defaultMtl, - [spriteMtl._uuid]: spriteMtl, - [spriteFrame._uuid]:spriteFrame - }; - return Object.assign(builtinResMgr, builtins); - }, - initEffects(effectUUIDs, OnComplete) { - // ============================ - // async builtin effects - // ============================ - let remainingJobs = effectUUIDs.length; - for (let i = 0; i < effectUUIDs.length; ++i) { - let uuid = effectUUIDs[i]; - cc.AssetLibrary.loadAsset(uuid, err => { - if (err) console.error(err); - if (!--remainingJobs) OnComplete(); - }); - } - } -}; - -cc.BuiltinResMgr = builtinResMgr; -export default builtinResMgr; diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts new file mode 100644 index 0000000000..d13175649e --- /dev/null +++ b/cocos/3d/builtin/init.ts @@ -0,0 +1,131 @@ +import { Asset } from '../../assets/asset'; +import { SpriteFrame} from '../../assets/CCSpriteFrame'; +import { ImageAsset } from '../../assets/image-asset'; +import { Texture2D } from '../../assets/texture-2d'; +import { Rect } from '../../core/value-types'; +import { GFXDevice } from '../../gfx/device'; +import { TextureCube } from '../assets/texture-cube'; + +class BuiltinResMgr { + protected _device: GFXDevice | null = null; + protected _resources: Record = {}; + + // this should be called after renderer initialized + public initBuiltinRes (device: GFXDevice) { + this._device = device; + const resources = this._resources; + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d')!; + const imgAsset = new ImageAsset(canvas); + canvas.width = canvas.height = 2; + + // ============================ + // builtin textures + // ============================ + + // black texture + context.fillStyle = '#000'; + context.fillRect(0, 0, 2, 2); + const blackTexture = new Texture2D(); + blackTexture._uuid = 'black-texture'; + blackTexture.image = imgAsset; + resources[blackTexture._uuid] = blackTexture; + + // grey texture + context.fillStyle = '#777'; + context.fillRect(0, 0, 2, 2); + const greyTexture = new Texture2D(); + greyTexture._uuid = 'grey-texture'; + greyTexture.image = imgAsset; + resources[greyTexture._uuid] = greyTexture; + + // grey cube texture + // const greyCubeTexture = new TextureCube(); + // greyCubeTexture._uuid = 'grey-cube-texture'; + // greyCubeTexture.image = { + // front: new ImageAsset(canvas), + // back: new ImageAsset(canvas), + // left: new ImageAsset(canvas), + // right: new ImageAsset(canvas), + // top: new ImageAsset(canvas), + // bottom: new ImageAsset(canvas), + // }; + // resources[greyCubeTexture._uuid] = greyCubeTexture; + + // white texture + context.fillStyle = '#fff'; + context.fillRect(0, 0, 2, 2); + const whiteTexture = new Texture2D(); + whiteTexture._uuid = 'white-texture'; + whiteTexture.image = imgAsset; + resources[whiteTexture._uuid] = whiteTexture; + + // normal texture + context.fillStyle = '#7f7fff'; + context.fillRect(0, 0, 2, 2); + const normalTexture = new Texture2D(); + normalTexture._uuid = 'normal-texture'; + normalTexture.image = imgAsset; + resources[normalTexture._uuid] = normalTexture; + + // default texture + context.fillStyle = '#ddd'; + context.fillRect(0, 0, 2, 2); + context.fillStyle = '#555'; + context.fillRect(0, 0, 1, 1); + context.fillStyle = '#555'; + context.fillRect(1, 1, 1, 1); + const defaultTexture = new Texture2D(); + defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + defaultTexture._uuid = 'default-texture'; + defaultTexture.image = imgAsset; + resources[defaultTexture._uuid] = defaultTexture; + + // default cube texture + // const defaultCubeTexture = new TextureCube(); + // defaultCubeTexture._uuid = 'default-cube-texture'; + // defaultCubeTexture.image = { + // front: new ImageAsset(canvas), + // back: new ImageAsset(canvas), + // left: new ImageAsset(canvas), + // right: new ImageAsset(canvas), + // top: new ImageAsset(canvas), + // bottom: new ImageAsset(canvas), + // }; + // resources.push(defaultCubeTexture); + + const spriteFrame = new SpriteFrame(); + spriteFrame.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + spriteFrame.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); + spriteFrame._uuid = 'default-spriteframe'; + spriteFrame.setOriginalSize(cc.size(imgAsset.width, imgAsset.height)); + spriteFrame.setRect(new Rect(0, 0, imgAsset.width, imgAsset.height)); + spriteFrame.image = imgAsset; + if (spriteFrame.onLoaded) { + spriteFrame.onLoaded(); + } + resources[spriteFrame._uuid] = spriteFrame; + + // default material + const defaultMtl = new cc.Material(); + defaultMtl._uuid = 'default-material'; + defaultMtl.setDefines({ USE_COLOR: true }); + defaultMtl.effectName = 'builtin-effect-unlit'; + defaultMtl.setProperty('color', cc.color('#FF00FF')); + resources[defaultMtl._uuid] = defaultMtl; + + // sprite material + const spriteMtl = new cc.Material(); + spriteMtl._uuid = 'sprite-material'; + spriteMtl.effectName = 'builtin-effect-sprite'; + spriteMtl.setProperty('mainTexture', defaultTexture); + resources[spriteMtl._uuid] = spriteMtl; + } + + public get (uuid: string): T { + return this._resources[uuid]; + } +} + +const builtinResMgr = cc.builtinResMgr = new BuiltinResMgr(); +export { builtinResMgr }; diff --git a/cocos/3d/framework/camera-component.ts b/cocos/3d/framework/camera-component.ts index e202ce06bb..f3fc42378d 100644 --- a/cocos/3d/framework/camera-component.ts +++ b/cocos/3d/framework/camera-component.ts @@ -28,7 +28,7 @@ import { ccclass, executeInEditMode, menu, property } from '../../core/data/clas import { Enum, Rect, Vec3 } from '../../core/value-types'; import { color4, toRadian } from '../../core/vmath'; import { GFXClearFlag } from '../../gfx/define'; -import { Camera } from '../../renderer/scene/camera'; +import { Camera } from '../../renderer'; /** * !#en The light source type diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js index ee33ffef9e..1822c7e15a 100644 --- a/cocos/3d/framework/light-component.js +++ b/cocos/3d/framework/light-component.js @@ -22,9 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -// @ts-check -import RenderSystemActor from './renderSystemActor'; -import * as renderer from '../../renderer/index'; import { Color, Enum } from '../../core/value-types'; import { toRadian } from '../../core/vmath'; import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index 1b0d59561b..f12afc3011 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -27,6 +27,7 @@ import { ccclass, property, menu, executionOrder, executeInEditMode } from '../. import { Mesh } from '../assets/mesh'; import Enum from '../../core/value-types/enum'; import { RenderableComponent } from './renderable-component'; +import { builtinResMgr } from '../builtin'; /** * !#en Shadow projection mode @@ -90,10 +91,10 @@ export class ModelComponent extends RenderableComponent { /** * @type {Mesh} */ - @property + @property({ type: Mesh }) _mesh = null; - @property + @property({ type: ModelShadowCastingMode }) _shadowCastingMode = ModelShadowCastingMode.Off; @property @@ -107,13 +108,10 @@ export class ModelComponent extends RenderableComponent { * !#ch 模型网格 * @type {Mesh} */ - @property({ - type: Mesh - }) + @property({ type: Mesh }) get mesh() { return this._mesh; } - set mesh(val) { this._mesh = val; this._updateModels(true); @@ -125,13 +123,10 @@ export class ModelComponent extends RenderableComponent { * !#ch 投射阴影方式 * @type {Number} */ - @property({ - type: ModelShadowCastingMode - }) + @property({ type: ModelShadowCastingMode }) get shadowCastingMode() { return this._shadowCastingMode; } - set shadowCastingMode(val) { this._shadowCastingMode = val; this._updateCastShadow(); @@ -178,9 +173,7 @@ export class ModelComponent extends RenderableComponent { } onDisable() { - if (this._model) { - this._model.enable = false; - } + if (this._model) { this._model.enabled = this.enabled; } } onDestroy() { @@ -265,6 +258,6 @@ export class ModelComponent extends RenderableComponent { _getBuiltinMaterial() { // classic ugly pink indicating missing material - return cc.BuiltinResMgr['default-material']; + return builtinResMgr.get('default-material'); } } diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 5ca06ed783..3d4b7cc157 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -9,6 +9,12 @@ import { import { PhysicsMaterial } from '../../assets/physics/material'; import { PhysicsBasedComponent } from './detail/physics-based-component'; +const NonRigidBodyProperties = { + mass: 0, + linearDamping: 0, + angularDamping: 0, +}; + @ccclass('cc.RigidBodyComponent') @executionOrder(100) @menu('Components/RigidBodyComponent') @@ -108,9 +114,3 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } } } - -const NonRigidBodyProperties = { - mass: 0, - linearDamping: 0, - angularDamping: 0, -}; diff --git a/cocos/3d/framework/render-system.js b/cocos/3d/framework/render-system.js deleted file mode 100644 index 424e3f5006..0000000000 --- a/cocos/3d/framework/render-system.js +++ /dev/null @@ -1,21 +0,0 @@ -import * as renderer from '../../renderer'; -export default class RenderSystem { - constructor () { - this._scene = new renderer.Scene(); - } - - init () { - - } - - update (dt) { - this._scene.tick(); - cc.game._renderer.render(this._scene); - this._scene.reset(); - if (cc.director._scene) cc.director._scene.resetHasChanged(); - } - - get scene () { - return this._scene; - } -} diff --git a/cocos/3d/framework/renderSystemActor.js b/cocos/3d/framework/renderSystemActor.js deleted file mode 100644 index a570b57e9b..0000000000 --- a/cocos/3d/framework/renderSystemActor.js +++ /dev/null @@ -1,41 +0,0 @@ -import { Component } from '../../components/component'; - -class RenderSystemActorListener { - constructor() { - this._renderSystem = null; - } - - onRenderableComponentCreated(comp) { - if(this._renderSystem === null) { - this._renderSystem = cc.director._renderSystem; - } - comp._system = this._renderSystem; - if (this._renderSystem) { - comp._scene = this._renderSystem.scene; - } - } -} - -let listener = new RenderSystemActorListener(); - -/** - * @class RenderSystemActor - * @extends Component - * RenderSystemActor is used to access Rendersystem - */ -export default class RenderSystemActor extends Component { - constructor() { - super(); - this._system = null; - this._scene = null; - listener.onRenderableComponentCreated(this); - } - - get renderSystem() { - return this._system; - } - - get scene() { - return this._scene; - } -} diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js deleted file mode 100644 index 13cf122025..0000000000 --- a/cocos/3d/framework/skybox-component.js +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import * as renderer from '../../renderer/index'; -import { box } from '../primitive/index'; -import { Material } from '../assets/material'; -import { ccclass, property, menu, executeInEditMode } from '../../core/data/class-decorator'; -import TextureCube from '../assets/texture-cube'; -import { Component } from '../../components/component'; - -/** - * !#en The Skybox Component - * - * !#ch 天空盒组件 - * @class SkyboxComponent - * @extends Component - */ -@ccclass('cc.SkyboxComponent') -@menu('Components/SkyboxComponent') -@executeInEditMode -export default class SkyboxComponent extends Component { - - @property - _cubemap = null; - @property - _rgbeTexture = false; - - @property({ - type: TextureCube, - displayName: 'Cubemap' - }) - get cubemap() { - return this._cubemap; - } - - set cubemap(val) { - this._cubemap = val; - this._updateMaterialParams(); - } - - @property({ - type: Boolean, - displayName: 'RGBE Texture' - }) - set rgbeTexture(v) { - this._rgbeTexture = v; - this._updateMaterialParams(); - } - get rgbeTexture() { - return this._rgbeTexture; - } - - constructor() { - super(); - - this._model = new renderer.Model(); - this._attachedCamera = null; - } - - onLoad() { - this._model.setNode(this.node); - - let ia = renderer.createIA(cc.game._gfxDevice, box(2, 2, 2)); - this._model.setInputAssembler(ia); - - if (!this._material) { - this._material = new Material(); - let skyboxEffect = cc.EffectAsset.get('builtin-effect-skybox'); - if (skyboxEffect) this._material.effectAsset = skyboxEffect; - } - - this._updateMaterialParams(); - this._model.setEffect(this._material.effect); - } - - onEnable() { - if (this.node) { - let cameraComponent = this.getComponent(cc.CameraComponent); - if (cameraComponent && (cameraComponent._clearFlags & renderer.CLEAR_SKYBOX)) { - this._attachedCamera = cameraComponent._camera; - this._attachedCamera._clearModel = this._model; - } - } - } - - onDisable() { - if (this._attachedCamera) { - this._attachedCamera._clearModel = null; - this._attachedCamera = null; - } - } - - _updateMaterialParams() { - if (!this._material) return; - if (this._cubemap) this._material.setProperty('cubeMap', this._cubemap); - this._material.define('USE_RGBE_CUBEMAP', this._rgbeTexture); - } -} diff --git a/cocos/3d/framework/skybox-component.ts b/cocos/3d/framework/skybox-component.ts new file mode 100644 index 0000000000..45b316293a --- /dev/null +++ b/cocos/3d/framework/skybox-component.ts @@ -0,0 +1,106 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { Camera, Model } from '../../renderer'; +import { Material } from '../assets/material'; +import { Mesh } from '../assets/mesh'; +import { TextureCube } from '../assets/texture-cube'; +import { createMesh } from '../misc/utils'; +import { box } from '../primitive'; + +/** + * !#en The Skybox Component + * + * !#ch 天空盒组件 + * @class SkyboxComponent + * @extends Component + */ +@ccclass('cc.SkyboxComponent') +@menu('Components/SkyboxComponent') +@executeInEditMode +export default class SkyboxComponent extends Component { + + @property + protected _cubemap = null; + @property + protected _rgbeTexture = false; + + @property({ + type: TextureCube, + displayName: 'Cubemap', + }) + get cubemap () { + return this._cubemap; + } + + set cubemap (val) { + this._cubemap = val; + if (this._material) { this._material.setProperty('cubeMap', this._cubemap); } + } + + @property({ + type: Boolean, + displayName: 'RGBE Texture', + }) + set rgbeTexture (v) { + this._rgbeTexture = v; + if (this._material) { this._material.setDefines({ USE_RGBE_CUBEMAP: v }); } + } + get rgbeTexture () { + return this._rgbeTexture; + } + + protected _attachedCamera: Camera | null = null; + protected _model: Model | null = null; + protected _mesh: Mesh | null = null; + protected _material: Material | null = null; + + public onLoad () { + this._model = this._getRenderScene().createModel(Model, this.node); + this._mesh = createMesh(box({ width: 2, height: 2, length: 2 })); + this._material = new Material({ + effectName: 'builtin-effect-skybox', + defines: { USE_RGBE_CUBEMAP: this._rgbeTexture }, + }); + if (this._cubemap) { this._material.setProperty('cubeMap', this._cubemap); } + + const subMeshData = this._mesh.renderingMesh!.getSubmesh(0); + this._model.initSubModel(0, subMeshData!, this._material); + } + + public onEnable () { + if (this._model) { this._model.enabled = true; } + } + + public onDisable () { + if (this._model) { this._model.enabled = false; } + } + + public onDestroy () { + if (this._model) { this._model.destroy(); this._model = null; } + } +} diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 7fe8e3ca31..dc34b4371c 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -1,6 +1,6 @@ import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define'; export { default as find } from '../../scene-graph/find'; -import Texture2D from '../../assets/texture-2d'; +import { Texture2D } from '../../assets/texture-2d'; import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; import { Vec3 } from '../../core/value-types'; import { AttributeBaseType, AttributeType, diff --git a/cocos/3d/primitive/index.js b/cocos/3d/primitive/index.ts similarity index 100% rename from cocos/3d/primitive/index.js rename to cocos/3d/primitive/index.ts diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index b432f0e3c8..d5f44ba06f 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -26,7 +26,7 @@ // @ts-check import macro from '../../../core/platform/CCMacro'; import { UIRenderComponent } from './ui-render-component'; -import ImageAsset from '../../../assets/image-asset'; +import { ImageAsset } from '../../../assets/image-asset'; // import { vec2, vec3, mat4, color4 } from '../../../core/vmath/index'; import { ccclass, @@ -36,7 +36,7 @@ import { executeInEditMode, } from '../../../core/data/class-decorator'; import Font from '../../../assets/CCFont'; -import Texture2D from '../../../assets/texture-2d'; +import { Texture2D } from '../../../assets/texture-2d'; import { MeshBuffer } from '../mesh-buffer'; import { Enum } from '../../../core/value-types'; // import { value } from '../../../core/utils/js'; @@ -605,7 +605,7 @@ export class LabelComponent extends UIRenderComponent { if (!material) { // material = new SpriteMaterial(); - this.material = cc.BuiltinResMgr['sprite-material']; + this.material = cc.builtinResMgr.get('sprite-material'); material = this.material; } // Setup blend function for premultiplied ttf label texture diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts index 807aee1a46..dd8eee5516 100644 --- a/cocos/3d/ui/components/mask-component.ts +++ b/cocos/3d/ui/components/mask-component.ts @@ -254,12 +254,12 @@ export class MaskComponent extends UIRenderComponent { public _activateMaterial () { if (!this._maskMaterial) { - this._maskMaterial = Material.getInstantiatedMaterial(cc.BuiltinResMgr['sprite-material'], this); + this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this); setupMaskMaterial(this._maskMaterial); } if (!this._clearMaskMaterial) { - this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.BuiltinResMgr['sprite-material'], this); + this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this); setupClearMaskMaterial(this._clearMaskMaterial); } } diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 8f87d3888d..6e999caec0 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -393,7 +393,7 @@ export class SpriteComponent extends UIRenderComponent { this._activateMaterial(); if (!this._spriteFrame) { - this.spriteFrame = cc.BuiltinResMgr['default-spriteframe']; + this.spriteFrame = cc.builtinResMgr.get('default-spriteframe'); } // this.node.on(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this); @@ -448,7 +448,7 @@ export class SpriteComponent extends UIRenderComponent { // WebGL if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { if (!material) { - this.material = cc.BuiltinResMgr['sprite-material']; + this.material = cc.builtinResMgr.get('sprite-material'); material = this.material; if (spriteFrame && spriteFrame.textureLoaded()) { material!.setProperty('mainTexture', spriteFrame); diff --git a/cocos/assets/CCSpriteFrame.ts b/cocos/assets/CCSpriteFrame.ts index 92f43670e0..2000d6a05c 100644 --- a/cocos/assets/CCSpriteFrame.ts +++ b/cocos/assets/CCSpriteFrame.ts @@ -32,7 +32,7 @@ import Rect, { rect } from '../core/value-types/rect'; import Size, { size } from '../core/value-types/size'; import Vec2, { v2 } from '../core/value-types/vec2'; import { Asset } from './asset'; -import Texture2D from './texture-2d'; +import { Texture2D } from './texture-2d'; import textureUtil from './texture-util'; const INSET_LEFT = 0; diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts index b43319850c..5cb4c4f2aa 100644 --- a/cocos/assets/image-asset.ts +++ b/cocos/assets/image-asset.ts @@ -42,7 +42,7 @@ type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource; * Class ImageAsset. */ @ccclass('cc.ImageAsset') -export default class ImageAsset extends Asset { +export class ImageAsset extends Asset { @property({override: true}) get _nativeAsset () { diff --git a/cocos/assets/index.js b/cocos/assets/index.js index b4981657a6..fd95924b0c 100644 --- a/cocos/assets/index.js +++ b/cocos/assets/index.js @@ -36,6 +36,6 @@ export {default as JsonAsset} from './CCJsonAsset'; export {default as GLTFAsset} from './CCGLTFAsset'; export {default as BufferAsset} from './CCBufferAsset'; export {default as AssetLibrary} from './CCAssetLibrary'; -export {default as ImageAsset} from './image-asset'; -export {default as Texture2D} from './texture-2d'; -export {default as RenderTexture} from './render-texture'; +export { ImageAsset } from './image-asset'; +export { Texture2D } from './texture-2d'; +export { RenderTexture } from './render-texture'; diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts index a2e032753a..d535942467 100644 --- a/cocos/assets/render-texture.ts +++ b/cocos/assets/render-texture.ts @@ -5,8 +5,8 @@ import { GFXFramebuffer } from '../gfx/framebuffer'; import { GFXTexture } from '../gfx/texture'; import { GFXTextureView } from '../gfx/texture-view'; import { RenderPassStage } from '../pipeline/define'; -import ImageAsset from './image-asset'; -import Texture2D from './texture-2d'; +import { ImageAsset } from './image-asset'; +import { Texture2D } from './texture-2d'; type DSFormat = 'D24S8' | 'S8' | 'D16'; const _formatMap = { @@ -21,7 +21,7 @@ const _formatMap = { * @extends Texture2D */ @ccclass('cc.RenderTexture') -export default class RenderTexture extends Texture2D { +export class RenderTexture extends Texture2D { private _framebuffer: GFXFramebuffer | null = null; private _depthStencilTexture: GFXTexture | null = null; diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index 30c621caef..95c03611b9 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -25,14 +25,14 @@ ****************************************************************************/ // @ts-check import { ccclass, property } from '../core/data/class-decorator'; -import ImageAsset from './image-asset'; -import TextureBase from './texture-base'; +import { ImageAsset } from './image-asset'; +import { TextureBase } from './texture-base'; /** * Represents a 2-dimension texture. */ @ccclass('cc.Texture2D') -export default class Texture2D extends TextureBase { +export class Texture2D extends TextureBase { /** * Gets the mipmap images. * Note that the result do not contains the auto generated mipmaps. diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 33450e9cff..550eb22339 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -36,7 +36,7 @@ import { GFXSampler } from '../gfx/sampler'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; import { Asset } from './asset'; -import ImageAsset from './image-asset'; +import { ImageAsset } from './image-asset'; const CHAR_CODE_1 = 49; // '1' @@ -157,7 +157,7 @@ function toGfxFilterMode (filter: Filter) { } @ccclass('cc.TextureBase') -export default class TextureBase extends Asset { +export class TextureBase extends Asset { /** * !#en diff --git a/cocos/assets/texture-util.js b/cocos/assets/texture-util.js index 35d75a2fe3..0278ade825 100644 --- a/cocos/assets/texture-util.js +++ b/cocos/assets/texture-util.js @@ -24,8 +24,8 @@ THE SOFTWARE. ****************************************************************************/ -import ImageAsset from './image-asset'; -import Texture2D from './texture-2d'; +import { ImageAsset } from './image-asset'; +import { Texture2D } from './texture-2d'; /** * cc.textureUtil is a singleton object, it can load cc.Texture2D asynchronously diff --git a/cocos/components/WXSubContextView.js b/cocos/components/WXSubContextView.js index 48e9e393fa..cf1fc17dd2 100644 --- a/cocos/components/WXSubContextView.js +++ b/cocos/components/WXSubContextView.js @@ -24,7 +24,7 @@ ****************************************************************************/ import { Component } from './component'; -const ImageAsset = require('../assets/image-asset'); +const { ImageAsset } = require('../assets/image-asset'); let WXSubContextView; diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts index a08b6af267..c8cbc9b011 100644 --- a/cocos/components/component.d.ts +++ b/cocos/components/component.d.ts @@ -39,16 +39,16 @@ export class Component extends CCObject { public constructor(); - protected _getRenderScene(): RenderScene; - public addComponent(typeOrClassName: Function | string): Component; - public getComponent(typeOrClassName: Function | string): Component; - public getComponents(typeOrClassName: Function | string): Component[]; - public getComponentInChildren(typeOrClassName: Function | string): Component; - public getComponentsInChildren(typeOrClassName: Function | string): Component[]; - public schedule(callback: Function, interval: number, repeat: number, delay: number): void; - public scheduleOnce(callback: Function, delay: number): void; - public unschedule(callback: Function): void; - public unscheduleAllCallbacks(): void; + protected _getRenderScene (): RenderScene; + public addComponent (typeOrClassName: string | (new () => T)): T; + public getComponent (typeOrClassName: string | (new () => T)): T; + public getComponents (typeOrClassName: string | (new () => T)): T[]; + public getComponentInChildren (typeOrClassName: string | (new () => T)): T; + public getComponentsInChildren (typeOrClassName: string | (new () => T)): T[]; + public schedule (callback: Function, interval: number, repeat: number, delay: number): void; + public scheduleOnce (callback: Function, delay: number): void; + public unschedule (callback: Function): void; + public unscheduleAllCallbacks (): void; // friend to class BaseNode public _id: string; diff --git a/cocos/core/director.js b/cocos/core/director.js index 5350f0b60a..4f475aef48 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -35,7 +35,6 @@ import ComponentScheduler from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; // import AnimationSystem from '../3d/framework/animation-system'; // import SkinningModelSystem from '../3d/framework/skinning-model-system'; -import RenderSystem from '../3d/framework/render-system'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; import { Root } from './root'; diff --git a/cocos/core/game.js b/cocos/core/game.js index 0f4b1f7233..d593695b04 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -28,10 +28,8 @@ import EventTarget from './event/event-target'; import inputManager from './platform/event-manager/CCInputManager'; import debug from './platform/CCDebug'; import { addon } from './utils/js'; - -import * as renderer from '../renderer'; -import gfx from '../renderer/gfx'; -import builtinResMgr from '../3d/builtin/init'; +import { EffectAsset } from '../3d/assets/effect-asset'; +import { builtinResMgr, effects } from '../3d/builtin'; /** * @module cc @@ -459,6 +457,12 @@ var game = { return; } + // Load builtin effects + effects.map(e => { + let effect = Object.assign(new EffectAsset(), e); + effect.onLoaded(); return effect; + }); + // Load game scripts let jsList = this.config.jsList; if (jsList && jsList.length > 0) { @@ -818,10 +822,6 @@ var game = { _initBuiltins: function() { builtinResMgr.initBuiltinRes(this._gfxDevice); - // this._renderer.setBuiltins({ - // defaultTexture: builtins['default-texture']._texture, - // defaultTextureCube: builtins['default-texture-cube']._texture, - // }); }, _initEvents: function () { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 6d967bb34f..d917cdf370 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -703,7 +703,7 @@ export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: W let w = gpuTexture.width; let h = gpuTexture.height; for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.texImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); + gl.texImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null); w = Math.max(1, w >> 1); h = Math.max(1, h >> 1); } @@ -715,7 +715,7 @@ export function WebGLCmdFuncCreateTexture (device: WebGLGFXDevice, gpuTexture: W let w = gpuTexture.width; let h = gpuTexture.height; for (let i = 0; i < gpuTexture.mipLevel; ++i) { - gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, view); + gl.compressedTexImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture.glInternelFmt, w, h, 0, view); w = Math.max(1, w >> 1); h = Math.max(1, h >> 1); } @@ -2228,7 +2228,7 @@ export function WebGLCmdFuncCopyBufferToTexture ( const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); const data = bufferView.subarray(buffOffset, buffOffset + memSize); - gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, + gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, data); @@ -2250,7 +2250,7 @@ export function WebGLCmdFuncCopyBufferToTexture ( const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); const data = bufferView.subarray(buffOffset, buffOffset + memSize); - gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_NEGATIVE_X + f, m, + gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, data); diff --git a/cocos/gfx/webgl/webgl-state-cache.ts b/cocos/gfx/webgl/webgl-state-cache.ts index 61cbfd1aff..87a373bded 100644 --- a/cocos/gfx/webgl/webgl-state-cache.ts +++ b/cocos/gfx/webgl/webgl-state-cache.ts @@ -50,6 +50,16 @@ export class WebGLStateCache { baseLevel: 0, maxLevel: 1000, }; + this.glTexCubeUnits[i] = { + glTexture: 0, + minFilter: WebGLRenderingContext.NONE, + magFilter: WebGLRenderingContext.NONE, + wrapS: WebGLRenderingContext.NONE, + wrapT: WebGLRenderingContext.NONE, + wrapR: WebGLRenderingContext.NONE, + baseLevel: 0, + maxLevel: 1000, + }; } for (let i = 0; i < GFX_MAX_VERTEX_ATTRIBUTES; ++i) { diff --git a/cocos/load-pipeline/loader.js b/cocos/load-pipeline/loader.js index 32ef57c48b..20ebe40f51 100644 --- a/cocos/load-pipeline/loader.js +++ b/cocos/load-pipeline/loader.js @@ -25,7 +25,7 @@ ****************************************************************************/ import {mixin} from '../core/utils/js'; -import ImageAsset from '../assets/image-asset'; +import {ImageAsset} from '../assets/image-asset'; import plistParser from './plist-parser'; import Pipeline from './pipeline'; import {loadUuid} from './uuid-loader'; @@ -59,7 +59,7 @@ function loadImage (item) { var image = item.content; if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); - } + } // load cc.ImageAsset var rawUrl = item.rawUrl; diff --git a/cocos/load-pipeline/unpackers.js b/cocos/load-pipeline/unpackers.js index 043faa9feb..c772b83b16 100644 --- a/cocos/load-pipeline/unpackers.js +++ b/cocos/load-pipeline/unpackers.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -import Texture2D from '../assets/texture-2d'; +import {Texture2D} from '../assets/texture-2d'; import {_getClassId} from '../core/utils/js'; export class JsonUnpacker { diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 3198a85137..c85d96ae14 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -350,7 +350,7 @@ export abstract class RenderPipeline { // filter model by view visibility if (view.visibility > 0 && model.viewID !== view.visibility || - !model.isEnable() || + !model.enabled || !model.node.activeInHierarchy) { continue; } diff --git a/cocos/renderer/core/base-renderer.js b/cocos/renderer/core/base-renderer.js deleted file mode 100644 index 9f8fa041cf..0000000000 --- a/cocos/renderer/core/base-renderer.js +++ /dev/null @@ -1,825 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { RecyclePool } from '../../3d/memop'; -import { vec2, vec3, vec4, mat2, mat3, mat4, color3, color4 } from '../../core/vmath'; -import { intersect } from '../../3d/geom-utils'; - -import * as enums from '../enums'; -import View from './view'; -import { ProgramLib } from './program-lib'; -import { RenderQueue } from './constants'; - -let _m3_tmp = mat3.create(); -let _m4_tmp = mat4.create(); - -let _camPos = vec3.create(0, 0, 0); -let _camFwd = vec3.create(0, 0, 0); -let _v3_tmp1 = vec3.create(0, 0, 0); - -let _a16_view = new Float32Array(16); -let _a16_proj = new Float32Array(16); -let _a16_viewProj = new Float32Array(16); -let _a3_camPos = new Float32Array(3); - -let _stageInfos = new RecyclePool(() => { - return { - stage: null, - items: null, - }; -}, 8); - -let _float2_pool = new RecyclePool(() => { - return new Float32Array(2); -}, 8); - -let _float3_pool = new RecyclePool(() => { - return new Float32Array(3); -}, 8); - -let _float4_pool = new RecyclePool(() => { - return new Float32Array(4); -}, 8); - -let _float9_pool = new RecyclePool(() => { - return new Float32Array(9); -}, 8); - -let _float16_pool = new RecyclePool(() => { - return new Float32Array(16); -}, 8); - -let _float64_pool = new RecyclePool(() => { - return new Float32Array(64); -}, 8); - -let _int2_pool = new RecyclePool(() => { - return new Int32Array(2); -}, 8); - -let _int3_pool = new RecyclePool(() => { - return new Int32Array(3); -}, 8); - -let _int4_pool = new RecyclePool(() => { - return new Int32Array(4); -}, 8); - -let _int64_pool = new RecyclePool(() => { - return new Int32Array(64); -}, 8); - -let _type2uniformValue = { - [enums.PARAM_INT]: function (value) { - return value; - }, - - [enums.PARAM_INT2]: function (value) { - return vec2.array(_int2_pool.add(), value); - }, - - [enums.PARAM_INT3]: function (value) { - return vec3.array(_int3_pool.add(), value); - }, - - [enums.PARAM_INT4]: function (value) { - return vec4.array(_int4_pool.add(), value); - }, - - [enums.PARAM_FLOAT]: function (value) { - return value; - }, - - [enums.PARAM_FLOAT2]: function (value) { - return vec2.array(_float2_pool.add(), value); - }, - - [enums.PARAM_FLOAT3]: function (value) { - return vec3.array(_float3_pool.add(), value); - }, - - [enums.PARAM_FLOAT4]: function (value) { - return vec4.array(_float4_pool.add(), value); - }, - - [enums.PARAM_COLOR3]: function (value) { - return color3.array(_float3_pool.add(), value); - }, - - [enums.PARAM_COLOR4]: function (value) { - return color4.array(_float4_pool.add(), value); - }, - - [enums.PARAM_MAT2]: function (value) { - return mat2.array(_float4_pool.add(), value); - }, - - [enums.PARAM_MAT3]: function (value) { - return mat3.array(_float9_pool.add(), value); - }, - - [enums.PARAM_MAT4]: function (value) { - return mat4.array(_float16_pool.add(), value); - }, - - // [enums.PARAM_TEXTURE_2D]: function (value) { - // }, - - // [enums.PARAM_TEXTURE_CUBE]: function (value) { - // }, -}; - -let _type2uniformArrayValue = { - [enums.PARAM_INT]: { - func (values) { - let result = _int64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[i] = values[i]; - } - return result; - }, - size: 1, - }, - - [enums.PARAM_INT2]: { - func (values) { - let result = _int64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[2 * i] = values[i].x; - result[2 * i + 1] = values[i].y; - } - return result; - }, - size: 2, - }, - - [enums.PARAM_INT3]: { - func: undefined, - size: 3, - }, - - [enums.PARAM_INT4]: { - func (values) { - let result = _int64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[4 * i] = v.x; - result[4 * i + 1] = v.y; - result[4 * i + 2] = v.z; - result[4 * i + 3] = v.w; - } - return result; - }, - size: 4, - }, - - [enums.PARAM_FLOAT]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[i] = values[i]; - } - return result; - }, - size: 1 - }, - - [enums.PARAM_FLOAT2]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - result[2 * i] = values[i].x; - result[2 * i + 1] = values[i].y; - } - return result; - }, - size: 2, - }, - - [enums.PARAM_FLOAT3]: { - func: undefined, - size: 3, - }, - - [enums.PARAM_FLOAT4]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[4 * i] = v.x; - result[4 * i + 1] = v.y; - result[4 * i + 2] = v.z; - result[4 * i + 3] = v.w; - } - return result; - }, - size: 4, - }, - - [enums.PARAM_COLOR3]: { - func: undefined, - size: 3, - }, - - [enums.PARAM_COLOR4]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - let scale = v instanceof cc.Color ? 1 / 255 : 1; - result[4 * i] = v.r * scale; - result[4 * i + 1] = v.g * scale; - result[4 * i + 2] = v.b * scale; - result[4 * i + 3] = v.a * scale; - } - return result; - }, - size: 4, - }, - - [enums.PARAM_MAT2]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[4 * i] = v.m00; - result[4 * i + 1] = v.m01; - result[4 * i + 2] = v.m02; - result[4 * i + 3] = v.m03; - } - return result; - }, - size: 4 - }, - - [enums.PARAM_MAT3]: { - func: undefined, - size: 9 - }, - - - [enums.PARAM_MAT4]: { - func (values) { - let result = _float64_pool.add(); - for (let i = 0; i < values.length; ++i) { - let v = values[i]; - result[16 * i] = v.m00; - result[16 * i + 1] = v.m01; - result[16 * i + 2] = v.m02; - result[16 * i + 3] = v.m03; - result[16 * i + 4] = v.m04; - result[16 * i + 5] = v.m05; - result[16 * i + 6] = v.m06; - result[16 * i + 7] = v.m07; - result[16 * i + 8] = v.m08; - result[16 * i + 9] = v.m09; - result[16 * i + 10] = v.m10; - result[16 * i + 11] = v.m11; - result[16 * i + 12] = v.m12; - result[16 * i + 13] = v.m13; - result[16 * i + 14] = v.m14; - result[16 * i + 15] = v.m15; - } - return result; - }, - size: 16 - }, - - // [enums.PARAM_TEXTURE_2D]: function (value) { - // }, - - // [enums.PARAM_TEXTURE_CUBE]: function (value) { - // }, -}; - -export default class BaseRenderer { - /** - * @param {gfx.Device} device - */ - constructor(device) { - this._device = device; - this._programLib = new ProgramLib(device); - this._type2defaultValue = { - [enums.PARAM_INT]: 0, - [enums.PARAM_INT2]: vec2.create(0, 0), - [enums.PARAM_INT3]: vec3.create(0, 0, 0), - [enums.PARAM_INT4]: vec4.create(0, 0, 0, 0), - [enums.PARAM_FLOAT]: 0.0, - [enums.PARAM_FLOAT2]: vec2.create(0, 0), - [enums.PARAM_FLOAT3]: vec3.create(0, 0, 0), - [enums.PARAM_FLOAT4]: vec4.create(0, 0, 0, 0), - [enums.PARAM_COLOR3]: color3.create(0, 0, 0), - [enums.PARAM_COLOR4]: color4.create(0, 0, 0, 1), - [enums.PARAM_MAT2]: mat2.create(), - [enums.PARAM_MAT3]: mat3.create(), - [enums.PARAM_MAT4]: mat4.create(), - [enums.PARAM_TEXTURE_2D]: null, - [enums.PARAM_TEXTURE_CUBE]: null, - }; - this._renderQueueFn = {}; - this._stage2fn = {}; - this._modelType2fn = {}; - this._usedTextureUnits = 0; - this.frustum_test_func = intersect.aabb_frustum; - this._accurateFrustumCulling = false; - this._currentView = null; - - this._viewPools = new RecyclePool(() => { - return new View(); - }, 8); - - // store renderable based on material - this._drawItemsPools = new RecyclePool(() => { - return { - model: null, - node: null, - ia: null, - effect: null, - defines: null, - dependencies: null, - }; - }, 100); - - // store renderable based on pass - this._stageItemsPools = new RecyclePool(() => { - return new RecyclePool(() => { - return { - model: null, - node: null, - ia: null, - effect: null, - defines: null, - dependencies: null, - tech: null, - pass: null, - passIndex: 0, - sortKey: -1, - }; - }, 100); - }, 16); - - this._registerRenderQueue('TRANSPARENT', this._renderTransparent.bind(this)); - this._registerRenderQueue('OPAQUE', this._renderOpaque.bind(this)); - this._registerRenderQueue('OVERLAY', this._renderOverlay.bind(this)); - } - - /** - * @param {Object} opts - * @param {gfx.Texture2D} opts.defaultTexture - * @param {gfx.TextureCube} opts.defaultTextureCube - */ - setBuiltins(opts) { - this._opts = opts; - this._type2defaultValue[enums.PARAM_TEXTURE_2D] = opts.defaultTexture; - this._type2defaultValue[enums.PARAM_TEXTURE_CUBE] = opts.defaultTextureCube; - } - - _resetTextureUnit() { - this._usedTextureUnits = 0; - } - - _allocTextureUnit() { - const device = this._device; - - let unit = this._usedTextureUnits; - if (unit >= device._caps.maxTextureUnits) { - console.warn(`Trying to use ${unit} texture units while this GPU supports only ${device._caps.maxTextureUnits}`); - } - - this._usedTextureUnits += 1; - return unit; - } - - _registerRenderQueue(name, fn) { - this._renderQueueFn[name] = fn; - } - - _registerStage(name, fn) { - this._stage2fn[name] = fn; - } - - _registerModel(name, fn) { - this._modelType2fn[name] = fn; - } - - _reset() { - this._currentView = null; - this._viewPools.reset(); - this._stageItemsPools.reset(); - } - - _requestView() { - let view = this._viewPools.add(); - view._frustum.accurate = this._accurateFrustumCulling; - return view; - } - - set accurateFrustumCulling(accurate) { - this._accurateFrustumCulling = accurate; - if (!accurate) this.frustum_test_func = intersect.aabb_frustum; - else this.frustum_test_func = intersect.aabb_frustum_accurate; - } - - _render(view, scene) { - const device = this._device; - this._currentView = view; - - // setup framebuffer - device.setFrameBuffer(view._framebuffer); - - // setup viewport - device.setViewport( - view._rect.x, - view._rect.y, - view._rect.w, - view._rect.h - ); - - // setup clear - let clearOpts = {}; - if (view._clearFlags & enums.CLEAR_COLOR) { - clearOpts.color = [ - view._color.r, - view._color.g, - view._color.b, - view._color.a - ]; - } - if (view._clearFlags & enums.CLEAR_DEPTH) { - clearOpts.depth = view._depth; - } - if (view._clearFlags & enums.CLEAR_STENCIL) { - clearOpts.stencil = view._stencil; - } - device.clear(clearOpts); - - // get all draw items - this._drawItemsPools.reset(); - - if ((view._clearFlags & enums.CLEAR_SKYBOX) && view._clearModel != null) { - let drawItem = this._drawItemsPools.add(); - view._clearModel.extractDrawItem(drawItem); - } - - for (let i = 0; i < scene._models.length; ++i) { - let model = scene._models.data[i]; - - // TODO: HACK: filter model by view - if (view._cullingByID) { - if (model._viewID !== view._id) { - continue; - } - } else { - if (model._viewID !== -1) { - continue; - } - } - - // frustum culling - if (model._boundingShape !== null) { // if model does not have boundingBox, skip culling. - if (!this.frustum_test_func(model._boundingShape, view._frustum)) { - // console.log('model is not in view frustum.'); - continue; - } - } - - let drawItem = this._drawItemsPools.add(); - model.extractDrawItem(drawItem); - } - - // dispatch draw items to different stage - _stageInfos.reset(); - - // for (let i = 0; i < view._stages.length; ++i) { - // let stage = view._stages[i]; - let renderQueues = Object.keys(RenderQueue); - for (let qi = 0; qi < renderQueues.length; qi++) { - this._stageItemsPools.add().reset(); - } - - for (let j = 0; j < this._drawItemsPools.length; ++j) { - let drawItem = this._drawItemsPools.data[j]; - let tech = drawItem.effect.getActiveTechnique(); - - if (tech) { - for (let k = 0; k < tech.passes.length; k++) { - if (!(view._stages & tech._passes[k]._stage)) - continue; - - let stageItem = this._stageItemsPools.data[tech.renderQueue].add(); - stageItem.model = drawItem.model; - stageItem.node = drawItem.node; - stageItem.ia = drawItem.ia; - stageItem.effect = drawItem.effect; - stageItem.defines = drawItem.defines; - stageItem.dependencies = drawItem.dependencies; - stageItem.tech = tech; - stageItem.pass = tech._passes[k]; - stageItem.passIndex = k; - stageItem.sortKey = -1; - } - } - } - - // let stageInfo = _stageInfos.add(); - // stageInfo.stage = stage; - // stageInfo.items = stageItems; - // } - - // render stages - // for (let i = 0; i < _stageInfos.length; ++i) { - // let info = _stageInfos.data[i]; - // let stageFn = this._stage2fn[info.stage]; - - // stageFn(view, info.items); - // } - - for (let qi = 0; qi < renderQueues.length; qi++) { - this._renderQueueFn[renderQueues[qi]](view, this._stageItemsPools.data[qi]); - } - this._stageItemsPools.reset(); - } - - _drawModel(item) { - let model = item.model; - let drawFn = this._modelType2fn[model._type]; - - if (!drawFn) { - // console.warn(`Can not find draw function for modle type ${model.type}`); - return; - } - - drawFn(item); - } - - _draw(item) { - - - // for each pass - // for (let i = 0; i < technique._passes.length; ++i) { - // let pass = technique._passes[i]; - this._stage2fn[item.pass._stage](item); - // } - } - - _isPassSuitable(view, stage) { - return view._stages.includes(stage); - } - - _renderOpaque(view, stageItems) { - - const programLib = this._programLib; - view.getPosition(_camPos); - - // update uniforms - this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - this._device.setUniform('_eye', vec3.array(_a3_camPos, _camPos)); - - // calculate sorting key - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - item.sortKey = programLib.getKey( - item.pass._programName, - item.defines - ); - } - - // sort items - stageItems.sort((a, b) => { - // first,sort by queue - if (a.tech._priority !== b.tech._priority) { - return a.tech._priority - b.tech._priority; - } - // second,sort by shader - return a.sortKey - b.sortKey; - }); - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - - this._drawModel(item); - } - } - - _renderTransparent(view, stageItems) { - - view.getPosition(_camPos); - view.getForward(_camFwd); - - // update uniforms - this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - this._device.setUniform('_eye', vec3.array(_a3_camPos, _camPos)); - - // calculate zdist - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - - // TODO: we should use mesh center instead! - item.node.getWorldPosition(_v3_tmp1); - - vec3.sub(_v3_tmp1, _v3_tmp1, _camPos); - item.sortKey = -vec3.dot(_v3_tmp1, _camFwd); - } - - // sort items - stageItems.sort((a, b) => { - // first, sort by queue - if (a.tech._priority !== b.tech._priority) { - return a.tech._priority - b.tech._priority; - } - // second, sort by distance - return a.sortKey - b.sortKey; - }); - - // draw it - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - - this._drawModel(item); - } - - } - - _renderOverlay(view, stageItems) { - // update uniforms - this._device.setUniform('_view', mat4.array(_a16_view, view._matView)); - this._device.setUniform('_proj', mat4.array(_a16_proj, view._matProj)); - this._device.setUniform('_viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - - // sort items - stageItems.sort((a, b) => { - if (a.tech._priority !== b.tech._priority) { - return a.tech._priority - b.tech._priority; - } - return a.model._userKey - b.model._userKey; - }); - - // draw it - for (let i = 0; i < stageItems.length; ++i) { - let item = stageItems.data[i]; - this._drawModel(item); - } - } - - _drawPass(item) { - const device = this._device; - const programLib = this._programLib; - const { node, ia, effect, pass, defines, dependencies } = item; - - // reset the pool - // NOTE: we can use drawCounter optimize this - // TODO: should be configurable - _float2_pool.reset(); - _float3_pool.reset(); - _float4_pool.reset(); - _float9_pool.reset(); - _float16_pool.reset(); - _float64_pool.reset(); - _int2_pool.reset(); - _int3_pool.reset(); - _int4_pool.reset(); - _int64_pool.reset(); - - node.getWorldMatrix(_m4_tmp); - device.setUniform('_model', mat4.array(_float16_pool.add(), _m4_tmp)); - - mat3.normalFromMat4(_m3_tmp, _m4_tmp); - device.setUniform('_normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp)); - - // set uniforms - for (let name in effect._properties) { - let propInfo = effect._properties[name]; - let prop = propInfo.value; - - if (prop === undefined || prop === null) { - prop = this._type2defaultValue[propInfo.type]; - } - - if (prop === undefined || prop === null) { - console.warn(`Failed to set technique property ${name}, value not found.`); - continue; - } - - if ( - propInfo.type === enums.PARAM_TEXTURE_2D || - propInfo.type === enums.PARAM_TEXTURE_CUBE - ) { - if (defines['USE_' + name.toUpperCase()] == false) continue; - if (propInfo.size !== undefined) { - if (propInfo.size !== prop.length) { - console.error(`The length of texture array (${prop.length}) is not corrent(expect ${propInfo.size}).`); - continue; - } - let slots = _int64_pool.add(); - for (let index = 0; index < prop.length; ++index) { - slots[index] = this._allocTextureUnit(); - } - device.setTextureArray(name, prop, slots); - } else { - device.setTexture(name, prop, this._allocTextureUnit()); - } - } else { - let convertedValue; - if (propInfo.size !== undefined) { - let convertArray = _type2uniformArrayValue[propInfo.type]; - if (convertArray.func === undefined) { - console.error('Uniform array of color3/int3/float3/mat3 can not be supportted!'); - continue; - } - if (propInfo.size * convertArray.size > 64) { - console.error('Uniform array is too long!'); - continue; - } - convertedValue = convertArray.func(prop); - } else { - let convertFn = _type2uniformValue[propInfo.type]; - convertedValue = convertFn(prop); - } - device.setUniform(name, convertedValue); - } - } - - let count = ia.count; - - // set vertex buffer - device.setVertexBuffer(0, ia._vertexBuffer); - - // set index buffer - if (ia._indexBuffer) { - device.setIndexBuffer(ia._indexBuffer); - } - - // set primitive type - device.setPrimitiveType(ia._primitiveType); - - // set program - let program = programLib.getProgram(pass._programName, defines, dependencies, effect._name); - device.setProgram(program); - - // cull mode - device.setCullMode(pass._cullMode); - - // blend - if (pass._blend) { - device.enableBlend(); - device.setBlendFuncSep( - pass._blendSrc, - pass._blendDst, - pass._blendSrcAlpha, - pass._blendDstAlpha - ); - device.setBlendEqSep( - pass._blendEq, - pass._blendAlphaEq - ); - device.setBlendColor32(pass._blendColor); - } - - // depth test & write - if (pass._depthTest) { - device.enableDepthTest(); - device.setDepthFunc(pass._depthFunc); - } - if (pass._depthWrite) { - device.enableDepthWrite(); - } - - // stencil - if (pass._stencilTest) { - device.enableStencilTest(); - - // front - device.setStencilFuncFront( - pass._stencilFuncFront, - pass._stencilRefFront, - pass._stencilMaskFront - ); - device.setStencilOpFront( - pass._stencilFailOpFront, - pass._stencilZFailOpFront, - pass._stencilZPassOpFront, - pass._stencilWriteMaskFront - ); - - // back - device.setStencilFuncBack( - pass._stencilFuncBack, - pass._stencilRefBack, - pass._stencilMaskBack - ); - device.setStencilOpBack( - pass._stencilFailOpBack, - pass._stencilZFailOpBack, - pass._stencilZPassOpBack, - pass._stencilWriteMaskBack - ); - } - - // draw pass - device.draw(ia._start, count); - - this._resetTextureUnit(); - } -} diff --git a/cocos/renderer/core/input-assembler.js b/cocos/renderer/core/input-assembler.js deleted file mode 100644 index ebe23ca6fb..0000000000 --- a/cocos/renderer/core/input-assembler.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; - -export default class InputAssembler { - constructor(vb, ib, pt = gfx.PT_TRIANGLES) { - this._vertexBuffer = vb; - this._indexBuffer = ib; - this._primitiveType = pt; - this._start = 0; - this._count = -1; - - // TODO: instancing data - // this._stream = 0; - } - - /** - * @property {Number} count The number of indices or vertices to dispatch in the draw call. - */ - get count() { - if (this._count !== -1) { - return this._count; - } - - if (this._indexBuffer) { - return this._indexBuffer.count; - } - - return this._vertexBuffer.count; - } -} \ No newline at end of file diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index fa5f12b445..63f3d4f2d7 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -1,6 +1,8 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import { IBlockInfo, IPassInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; +import { builtinResMgr } from '../../3d/builtin'; +import { TextureBase } from '../../assets/texture-base'; import { color4, mat2, mat3, mat4, vec2, vec3, vec4 } from '../../core/vmath'; import { GFXBindingLayout, IGFXBinding } from '../../gfx/binding-layout'; import { GFXBuffer } from '../../gfx/buffer'; @@ -15,7 +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 { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; +import { UBOGlobal } from '../../pipeline/render-pipeline'; export interface IPassInfoFull extends IPassInfo { // generated part @@ -61,9 +63,11 @@ const _type2default = { [GFXType.MAT2]: [1, 0, 0, 1], [GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1], [GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], + [GFXType.SAMPLER2D]: 'default-texture', + [GFXType.SAMPLER_CUBE]: 'default-cube-texture', }; -const builtinRE = new RegExp(UBOGlobal.BLOCK.name + '|' + UBOLocal.BLOCK.name); +const builtinRE = /^cc/i; const btMask = 0xf0000000; // 4 bits, 16 slots const typeMask = 0x0fc00000; // 6 bits, 64 slots @@ -143,9 +147,7 @@ export class Pass { this._fillinPipelineInfo(info); for (const u of info.blocks) { - if (builtinRE.test(u.name)) { - continue; - } + if (builtinRE.test(u.name)) { continue; } // create gfx buffer resource const buffer = device.createBuffer({ memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, @@ -182,6 +184,7 @@ export class Pass { } for (const u of info.samplers) { + if (builtinRE.test(u.name)) { continue; } this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); const sampler = device.createSampler({ name: u.name, @@ -192,6 +195,9 @@ export class Pass { } else { console.error('create sampler failed.'); } + const inf = info.properties && info.properties[u.name]; + const name = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; + this._textureViews[u.binding] = builtinResMgr.get(name).getGFXTextureView()!; } } diff --git a/cocos/renderer/core/view.js b/cocos/renderer/core/view.js deleted file mode 100644 index a9bc6af502..0000000000 --- a/cocos/renderer/core/view.js +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { vec3, color4, mat4 } from '../../core/vmath'; -import * as enums from '../enums'; -import { frustum } from '../../3d/geom-utils'; - -let _m4_tmp = mat4.create(); -let _genID = 0; - -/** - * A representation of a single camera view - */ -export default class View { - /** - * Setup a default view - */ - constructor() { - this._id = _genID++; - - // priority. the smaller one will be rendered first - this._priority = 0; - - // viewport - this._rect = { - x: 0, y: 0, w: 1, h: 1 - }; - - // TODO: - // this._scissor = { - // x: 0, y: 0, w: 1, h: 1 - // }; - - // clear options - this._color = color4.create(0.3, 0.3, 0.3, 1); - this._depth = 1; - this._stencil = 0; - this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH; - this._clearModel = null; - - // matrix - this._matView = mat4.create(); - this._matProj = mat4.create(); - this._matViewProj = mat4.create(); - this._matInvViewProj = mat4.create(); - - // stages & framebuffer - this._stages = []; - this._cullingByID = false; - this._framebuffer = null; - - this._shadowLight = null; // TODO: should not refer light in view. - - this._frustum = frustum.create(); - } - - /** - * Get the view's forward direction - * @param {vec3} out the receiving vector - * @returns {vec3} the receiving vector - */ - getForward(out) { - return vec3.set( - out, - -this._matView.m02, - -this._matView.m06, - -this._matView.m10 - ); - } - - /** - * Get the view's observing location - * @param {vec3} out the receiving vector - * @returns {vec3} the receiving vector - */ - getPosition(out) { - mat4.invert(_m4_tmp, this._matView); - return mat4.getTranslation(out, _m4_tmp); - } -} diff --git a/cocos/renderer/enums.js b/cocos/renderer/enums.js deleted file mode 100644 index 80737d1aa9..0000000000 --- a/cocos/renderer/enums.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -// projection -export const PROJ_PERSPECTIVE = 0; -export const PROJ_ORTHO = 1; - -// lights -export const LIGHT_DIRECTIONAL = 0; -export const LIGHT_POINT = 1; -export const LIGHT_SPOT = 2; - -// shadows -export const SHADOW_NONE = 0; -export const SHADOW_HARD = 1; -export const SHADOW_SOFT = 2; - -// parameter type -export const PARAM_INT = 0; -export const PARAM_INT2 = 1; -export const PARAM_INT3 = 2; -export const PARAM_INT4 = 3; -export const PARAM_FLOAT = 4; -export const PARAM_FLOAT2 = 5; -export const PARAM_FLOAT3 = 6; -export const PARAM_FLOAT4 = 7; -export const PARAM_COLOR3 = 8; -export const PARAM_COLOR4 = 9; -export const PARAM_MAT2 = 10; -export const PARAM_MAT3 = 11; -export const PARAM_MAT4 = 12; -export const PARAM_TEXTURE_2D = 13; -export const PARAM_TEXTURE_CUBE = 14; - -// clear flags -export const CLEAR_COLOR = 1; -export const CLEAR_DEPTH = 2; -export const CLEAR_STENCIL = 4; -export const CLEAR_SKYBOX = 8; - -// -export const BUFFER_VIEW_INT8 = 0; -export const BUFFER_VIEW_UINT8 = 1; -export const BUFFER_VIEW_INT16 = 2; -export const BUFFER_VIEW_UINT16 = 3; -export const BUFFER_VIEW_INT32 = 4; -export const BUFFER_VIEW_UINT32 = 5; -export const BUFFER_VIEW_FLOAT32 = 6; diff --git a/cocos/renderer/gfx/device.js b/cocos/renderer/gfx/device.js deleted file mode 100644 index 3165c109ed..0000000000 --- a/cocos/renderer/gfx/device.js +++ /dev/null @@ -1,1287 +0,0 @@ -import State from './state'; -import { enums } from './enums'; - -import Texture2D from './texture-2d'; -import TextureCube from './texture-cube'; - -const GL_INT = 5124; -const GL_FLOAT = 5126; -const GL_FLOAT_VEC2 = 35664; -const GL_FLOAT_VEC3 = 35665; -const GL_FLOAT_VEC4 = 35666; -const GL_INT_VEC2 = 35667; -const GL_INT_VEC3 = 35668; -const GL_INT_VEC4 = 35669; -const GL_BOOL = 35670; -const GL_BOOL_VEC2 = 35671; -const GL_BOOL_VEC3 = 35672; -const GL_BOOL_VEC4 = 35673; -const GL_FLOAT_MAT2 = 35674; -const GL_FLOAT_MAT3 = 35675; -const GL_FLOAT_MAT4 = 35676; -const GL_SAMPLER_2D = 35678; -const GL_SAMPLER_CUBE = 35680; - -/** - * _type2uniformCommit - */ -let _type2uniformCommit = { - [GL_INT]: function (gl, id, value) { - gl.uniform1i(id, value); - }, - - [GL_FLOAT]: function (gl, id, value) { - gl.uniform1f(id, value); - }, - - [GL_FLOAT_VEC2]: function (gl, id, value) { - gl.uniform2fv(id, value); - }, - - [GL_FLOAT_VEC3]: function (gl, id, value) { - gl.uniform3fv(id, value); - }, - - [GL_FLOAT_VEC4]: function (gl, id, value) { - gl.uniform4fv(id, value); - }, - - [GL_INT_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_INT_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_INT_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_BOOL]: function (gl, id, value) { - gl.uniform1i(id, value); - }, - - [GL_BOOL_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_BOOL_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_BOOL_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_FLOAT_MAT2]: function (gl, id, value) { - gl.uniformMatrix2fv(id, false, value); - }, - - [GL_FLOAT_MAT3]: function (gl, id, value) { - gl.uniformMatrix3fv(id, false, value); - }, - - [GL_FLOAT_MAT4]: function (gl, id, value) { - gl.uniformMatrix4fv(id, false, value); - }, - - [GL_SAMPLER_2D]: function (gl, id, value) { - gl.uniform1i(id, value); - }, - - [GL_SAMPLER_CUBE]: function (gl, id, value) { - gl.uniform1i(id, value); - }, -}; - -/** - * _type2uniformArrayCommit - */ -let _type2uniformArrayCommit = { - [GL_INT]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, - - [GL_FLOAT]: function (gl, id, value) { - gl.uniform1fv(id, value); - }, - - [GL_FLOAT_VEC2]: function (gl, id, value) { - gl.uniform2fv(id, value); - }, - - [GL_FLOAT_VEC3]: function (gl, id, value) { - gl.uniform3fv(id, value); - }, - - [GL_FLOAT_VEC4]: function (gl, id, value) { - gl.uniform4fv(id, value); - }, - - [GL_INT_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_INT_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_INT_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_BOOL]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, - - [GL_BOOL_VEC2]: function (gl, id, value) { - gl.uniform2iv(id, value); - }, - - [GL_BOOL_VEC3]: function (gl, id, value) { - gl.uniform3iv(id, value); - }, - - [GL_BOOL_VEC4]: function (gl, id, value) { - gl.uniform4iv(id, value); - }, - - [GL_FLOAT_MAT2]: function (gl, id, value) { - gl.uniformMatrix2fv(id, false, value); - }, - - [GL_FLOAT_MAT3]: function (gl, id, value) { - gl.uniformMatrix3fv(id, false, value); - }, - - [GL_FLOAT_MAT4]: function (gl, id, value) { - gl.uniformMatrix4fv(id, false, value); - }, - - [GL_SAMPLER_2D]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, - - [GL_SAMPLER_CUBE]: function (gl, id, value) { - gl.uniform1iv(id, value); - }, -}; - -/** - * _commitBlendStates - */ -function _commitBlendStates(gl, cur, next) { - // enable/disable blend - if (cur.blend !== next.blend) { - if (!next.blend) { - gl.disable(gl.BLEND); - return; - } - - gl.enable(gl.BLEND); - - if ( - next.blendSrc === enums.BLEND_CONSTANT_COLOR || - next.blendSrc === enums.BLEND_ONE_MINUS_CONSTANT_COLOR || - next.blendDst === enums.BLEND_CONSTANT_COLOR || - next.blendDst === enums.BLEND_ONE_MINUS_CONSTANT_COLOR - ) { - gl.blendColor( - (next.blendColor >> 24) / 255, - (next.blendColor >> 16 & 0xff) / 255, - (next.blendColor >> 8 & 0xff) / 255, - (next.blendColor & 0xff) / 255 - ); - } - - if (next.blendSep) { - gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); - gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); - } else { - gl.blendFunc(next.blendSrc, next.blendDst); - gl.blendEquation(next.blendEq); - } - - return; - } - - // nothing to update - if (next.blend === false) { - return; - } - - // blend-color - if (cur.blendColor !== next.blendColor) { - gl.blendColor( - (next.blendColor >> 24) / 255, - (next.blendColor >> 16 & 0xff) / 255, - (next.blendColor >> 8 & 0xff) / 255, - (next.blendColor & 0xff) / 255 - ); - } - - // separate diff, reset all - if (cur.blendSep !== next.blendSep) { - if (next.blendSep) { - gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); - gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); - } else { - gl.blendFunc(next.blendSrc, next.blendDst); - gl.blendEquation(next.blendEq); - } - - return; - } - - if (next.blendSep) { - // blend-func-separate - if ( - cur.blendSrc !== next.blendSrc || - cur.blendDst !== next.blendDst || - cur.blendSrcAlpha !== next.blendSrcAlpha || - cur.blendDstAlpha !== next.blendDstAlpha - ) { - gl.blendFuncSeparate(next.blendSrc, next.blendDst, next.blendSrcAlpha, next.blendDstAlpha); - } - - // blend-equation-separate - if ( - cur.blendEq !== next.blendEq || - cur.blendAlphaEq !== next.blendAlphaEq - ) { - gl.blendEquationSeparate(next.blendEq, next.blendAlphaEq); - } - } else { - // blend-func - if ( - cur.blendSrc !== next.blendSrc || - cur.blendDst !== next.blendDst - ) { - gl.blendFunc(next.blendSrc, next.blendDst); - } - - // blend-equation - if (cur.blendEq !== next.blendEq) { - gl.blendEquation(next.blendEq); - } - } -} - -/** - * _commitDepthStates - */ -function _commitDepthStates(gl, cur, next) { - // enable/disable depth-test - if (cur.depthTest !== next.depthTest) { - if (!next.depthTest) { - gl.disable(gl.DEPTH_TEST); - return; - } - - gl.enable(gl.DEPTH_TEST); - gl.depthFunc(next.depthFunc); - gl.depthMask(next.depthWrite); - - return; - } - - // commit depth-write - if (cur.depthWrite !== next.depthWrite) { - gl.depthMask(next.depthWrite); - } - - // check if depth-write enabled - if (next.depthTest === false) { - if (next.depthWrite) { - next.depthTest = true; - next.depthFunc = enums.DS_FUNC_ALWAYS; - - gl.enable(gl.DEPTH_TEST); - gl.depthFunc(next.depthFunc); - } - - return; - } - - // depth-func - if (cur.depthFunc !== next.depthFunc) { - gl.depthFunc(next.depthFunc); - } -} - -/** - * _commitStencilStates - */ -function _commitStencilStates(gl, cur, next) { - if (next.stencilTest !== cur.stencilTest) { - if (!next.stencilTest) { - gl.disable(gl.STENCIL_TEST); - return; - } - - gl.enable(gl.STENCIL_TEST); - - if (next.stencilSep) { - gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); - gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); - gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); - gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); - } else { - gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMask(next.stencilWriteMaskFront); - gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - - return; - } - - // fast return - if (!next.stencilTest) { - return; - } - - if (cur.stencilSep !== next.stencilSep) { - if (next.stencilSep) { - gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); - gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); - gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); - gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); - } else { - gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - gl.stencilMask(next.stencilWriteMaskFront); - gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - return; - } - - if (next.stencilSep) { - // front - if ( - cur.stencilFuncFront !== next.stencilFuncFront || - cur.stencilRefFront !== next.stencilRefFront || - cur.stencilMaskFront !== next.stencilMaskFront - ) { - gl.stencilFuncSeparate(gl.FRONT, next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - } - if (cur.stencilWriteMaskFront !== next.stencilWriteMaskFront) { - gl.stencilMaskSeparate(gl.FRONT, next.stencilWriteMaskFront); - } - if ( - cur.stencilFailOpFront !== next.stencilFailOpFront || - cur.stencilZFailOpFront !== next.stencilZFailOpFront || - cur.stencilZPassOpFront !== next.stencilZPassOpFront - ) { - gl.stencilOpSeparate(gl.FRONT, next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - - // back - if ( - cur.stencilFuncBack !== next.stencilFuncBack || - cur.stencilRefBack !== next.stencilRefBack || - cur.stencilMaskBack !== next.stencilMaskBack - ) { - gl.stencilFuncSeparate(gl.BACK, next.stencilFuncBack, next.stencilRefBack, next.stencilMaskBack); - } - if (cur.stencilWriteMaskBack !== next.stencilWriteMaskBack) { - gl.stencilMaskSeparate(gl.BACK, next.stencilWriteMaskBack); - } - if ( - cur.stencilFailOpBack !== next.stencilFailOpBack || - cur.stencilZFailOpBack !== next.stencilZFailOpBack || - cur.stencilZPassOpBack !== next.stencilZPassOpBack - ) { - gl.stencilOpSeparate(gl.BACK, next.stencilFailOpBack, next.stencilZFailOpBack, next.stencilZPassOpBack); - } - } else { - if ( - cur.stencilFuncFront !== next.stencilFuncFront || - cur.stencilRefFront !== next.stencilRefFront || - cur.stencilMaskFront !== next.stencilMaskFront - ) { - gl.stencilFunc(next.stencilFuncFront, next.stencilRefFront, next.stencilMaskFront); - } - if (cur.stencilWriteMaskFront !== next.stencilWriteMaskFront) { - gl.stencilMask(next.stencilWriteMaskFront); - } - if ( - cur.stencilFailOpFront !== next.stencilFailOpFront || - cur.stencilZFailOpFront !== next.stencilZFailOpFront || - cur.stencilZPassOpFront !== next.stencilZPassOpFront - ) { - gl.stencilOp(next.stencilFailOpFront, next.stencilZFailOpFront, next.stencilZPassOpFront); - } - } - -} - -/** - * _commitCullMode - */ -function _commitCullMode(gl, cur, next) { - if (cur.cullMode === next.cullMode) { - return; - } - - if (next.cullMode === enums.CULL_NONE) { - gl.disable(gl.CULL_FACE); - return; - } - - gl.enable(gl.CULL_FACE); - gl.cullFace(next.cullMode); -} - -/** - * _commitVertexBuffers - */ -function _commitVertexBuffers(device, gl, cur, next) { - let attrsDirty = false; - - // nothing changed for vertex buffer - if (next.maxStream === -1) { - console.warn('VertexBuffer not assigned, please call setVertexBuffer before every draw.'); - return; - } - - if (cur.maxStream !== next.maxStream) { - attrsDirty = true; - } else if (cur.program !== next.program) { - attrsDirty = true; - } else { - for (let i = 0; i < next.maxStream + 1; ++i) { - if ( - cur.vertexBuffers[i] !== next.vertexBuffers[i] || - cur.vertexBufferOffsets[i] !== next.vertexBufferOffsets[i] - ) { - attrsDirty = true; - break; - } - } - } - - if (attrsDirty) { - for (let i = 0; i < device._caps.maxVertexAttribs; ++i) { - device._newAttributes[i] = 0; - } - - for (let i = 0; i < next.maxStream + 1; ++i) { - let vb = next.vertexBuffers[i]; - let vbOffset = next.vertexBufferOffsets[i]; - if (!vb) { - continue; - } - - gl.bindBuffer(gl.ARRAY_BUFFER, vb._glID); - - for (let j = 0; j < next.program._attributes.length; ++j) { - let attr = next.program._attributes[j]; - - let el = vb._format.element(attr.name); - if (!el) { - console.warn(`Can not find vertex attribute: ${attr.name}`); - continue; - } - - if (device._enabledAttributes[attr.location] === 0) { - gl.enableVertexAttribArray(attr.location); - device._enabledAttributes[attr.location] = 1; - } - device._newAttributes[attr.location] = 1; - - gl.vertexAttribPointer( - attr.location, - el.num, - el.type, - el.normalize, - el.stride, - el.offset + vbOffset * el.stride - ); - } - } - - // disable unused attributes - for (let i = 0; i < device._caps.maxVertexAttribs; ++i) { - if (device._enabledAttributes[i] !== device._newAttributes[i]) { - gl.disableVertexAttribArray(i); - device._enabledAttributes[i] = 0; - } - } - } -} - -/** - * _commitTextures - */ -function _commitTextures(gl, cur, next) { - for (let i = 0; i < next.maxTextureSlot + 1; ++i) { - if (cur.textureUnits[i] !== next.textureUnits[i]) { - let texture = next.textureUnits[i]; - if (texture !== undefined && texture._glID !== -1) { - gl.activeTexture(gl.TEXTURE0 + i); - gl.bindTexture(texture._target, texture._glID); - } - } - } -} - -/** - * _attach - */ -function _attach(gl, location, attachment, face = 0) { - if (attachment instanceof Texture2D) { - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - location, - gl.TEXTURE_2D, - attachment._glID, - 0 - ); - } else if (attachment instanceof TextureCube) { - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - location, - gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, - attachment._glID, - 0 - ); - } else { - gl.framebufferRenderbuffer( - gl.FRAMEBUFFER, - location, - gl.RENDERBUFFER, - attachment._glID - ); - } -} - -export default class Device { - /** - * @param {HTMLElement} canvasEL - * @param {object} opts - */ - constructor(canvasEL, opts) { - let gl; - - // default options - opts = opts || {}; - if (opts.alpha === undefined) { - opts.alpha = false; - } - if (opts.stencil === undefined) { - opts.stencil = true; - } - if (opts.depth === undefined) { - opts.depth = true; - } - if (opts.antialias === undefined) { - opts.antialias = false; - } - // NOTE: it is said the performance improved in mobile device with this flag off. - if (opts.preserveDrawingBuffer === undefined) { - opts.preserveDrawingBuffer = false; - } - - try { - gl = canvasEL.getContext('webgl', opts); - } catch (err) { - console.error(err); - return; - } - - // No errors are thrown using try catch - // Tested through ios baidu browser 4.14.1 - if (!gl) { - console.error('This device does not support webgl'); - } - - // statics - /** - * @type {WebGLRenderingContext} - */ - this._gl = gl; - this._extensions = {}; - this._caps = {}; // capability - this._stats = { - texture: 0, - vb: 0, - ib: 0, - drawcalls: 0, - }; - - let builtin_exts = [ - 'EXT_texture_filter_anisotropic', - 'EXT_shader_texture_lod', - 'OES_standard_derivatives', - 'OES_texture_float', - 'OES_texture_float_linear', - 'OES_texture_half_float', - 'OES_texture_half_float_linear', - 'OES_vertex_array_object', - 'WEBGL_compressed_texture_atc', - 'WEBGL_compressed_texture_etc1', - 'WEBGL_compressed_texture_pvrtc', - 'WEBGL_compressed_texture_s3tc', - 'WEBGL_depth_texture', - 'WEBGL_draw_buffers', - ]; - for (let i = 0; i < builtin_exts.length; ++i) { - this._initExtension(builtin_exts[i]); - } - let exts = gl.getSupportedExtensions(); - this._supportedExts = exts.reduce((acc, cur) => { acc[cur] = true; return acc; }, {}); - - this._initCaps(); - this._initStates(); - - // runtime - State.initDefault(this); - this._current = new State(this); - this._next = new State(this); - this._uniforms = {}; // name: { value, num, dirty } - this._vx = this._vy = this._vw = this._vh = 0; - this._sx = this._sy = this._sw = this._sh = 0; - this._framebuffer = null; - - // - this._enabledAttributes = new Array(this._caps.maxVertexAttribs); - this._newAttributes = new Array(this._caps.maxVertexAttribs); - - for (let i = 0; i < this._caps.maxVertexAttribs; ++i) { - this._enabledAttributes[i] = 0; - this._newAttributes[i] = 0; - } - } - - _initCaps() { - const gl = this._gl; - const extDrawBuffers = this.ext('WEBGL_draw_buffers'); - - this._caps.maxVertexStreams = 4; - this._caps.maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - this._caps.maxFragUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); - this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - this._caps.maxVertexAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - this._caps.maxDrawBuffers = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_DRAW_BUFFERS_WEBGL) : 1; - this._caps.maxColorAttachments = extDrawBuffers ? gl.getParameter(extDrawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL) : 1; - } - - _initStates() { - const gl = this._gl; - - // gl.frontFace(gl.CCW); - gl.disable(gl.BLEND); - gl.blendFunc(gl.ONE, gl.ZERO); - gl.blendEquation(gl.FUNC_ADD); - gl.blendColor(1,1,1,1); - - gl.colorMask(true, true, true, true); - - gl.enable(gl.CULL_FACE); - gl.cullFace(gl.BACK); - - gl.disable(gl.DEPTH_TEST); - gl.depthFunc(gl.LESS); - gl.depthMask(false); - gl.disable(gl.POLYGON_OFFSET_FILL); - gl.depthRange(0,1); - - gl.disable(gl.STENCIL_TEST); - gl.stencilFunc(gl.ALWAYS, 0, 0xFF); - gl.stencilMask(0xFF); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - - // TODO: - // this.setAlphaToCoverage(false); - // this.setTransformFeedbackBuffer(null); - // this.setRaster(true); - // this.setDepthBias(false); - - gl.clearDepth(1); - gl.clearColor(0, 0, 0, 0); - gl.clearStencil(0); - - gl.disable(gl.SCISSOR_TEST); - } - - _restoreTexture(unit) { - const gl = this._gl; - - let texture = this._current.textureUnits[unit]; - if (texture && texture._glID !== -1) { - gl.bindTexture(texture._target, texture._glID); - } else { - gl.bindTexture(gl.TEXTURE_2D, null); - } - } - - _restoreIndexBuffer () { - const gl = this._gl; - - let ib = this._current.indexBuffer; - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib ? ib._glID : null); - } - - _initExtension(name) { - const gl = this._gl; - let ext = gl.getExtension(name); - return this._extensions[name] = ext; - } - - /** - * @method ext - * @param {string} name - */ - ext(name) { - let ext = this._extensions[name]; - if (ext) return ext; - if (this.supportExtension(name)) return this._initExtension(name); - } - - supportExtension(name) { - return this._supportedExts[name] === true; - } - - allowFloatTexture() { - return this.ext("OES_texture_float") != null; - } - - // =============================== - // Immediate Settings - // =============================== - - /** - * @method setFrameBuffer - * @param {FrameBuffer} fb - null means use the backbuffer - */ - setFrameBuffer(fb) { - if (this._framebuffer === fb) { - return; - } - - this._framebuffer = fb; - const gl = this._gl; - - if (fb === null) { - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - return; - } - - gl.bindFramebuffer(gl.FRAMEBUFFER, fb._glID); - - let numColors = fb._colors.length; - for (let i = 0; i < numColors; ++i) { - let colorBuffer = fb._colors[i]; - _attach(gl, gl.COLOR_ATTACHMENT0 + i, colorBuffer); - - // TODO: what about cubemap face??? should be the target parameter for colorBuffer - } - for (let i = numColors; i < this._caps.maxColorAttachments; ++i) { - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - gl.COLOR_ATTACHMENT0 + i, - gl.TEXTURE_2D, - null, - 0 - ); - } - - if (fb._depth) { - _attach(gl, gl.DEPTH_ATTACHMENT, fb._depth); - } - - if (fb._stencil) { - _attach(gl, gl.STENCIL_ATTACHMENT, fb._stencil); - } - - if (fb._depthStencil) { - _attach(gl, gl.DEPTH_STENCIL_ATTACHMENT, fb._depthStencil); - } - } - - /** - * @method setViewport - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - setViewport(x, y, w, h) { - if ( - this._vx !== x || - this._vy !== y || - this._vw !== w || - this._vh !== h - ) { - this._gl.viewport(x, y, w, h); - this._vx = x; - this._vy = y; - this._vw = w; - this._vh = h; - } - } - - /** - * @method setScissor - * @param {Number} x - * @param {Number} y - * @param {Number} w - * @param {Number} h - */ - setScissor(x, y, w, h) { - if ( - this._sx !== x || - this._sy !== y || - this._sw !== w || - this._sh !== h - ) { - this._gl.scissor(x, y, w, h); - this._sx = x; - this._sy = y; - this._sw = w; - this._sh = h; - } - } - - /** - * @method clear - * @param {Object} opts - * @param {Array} opts.color - * @param {Number} opts.depth - * @param {Number} opts.stencil - */ - clear(opts) { - const gl = this._gl; - let flags = 0; - - if (opts.color !== undefined) { - flags |= gl.COLOR_BUFFER_BIT; - gl.clearColor(opts.color[0], opts.color[1], opts.color[2], opts.color[3]); - } - - if (opts.depth !== undefined) { - flags |= gl.DEPTH_BUFFER_BIT; - gl.clearDepth(opts.depth); - - gl.enable(gl.DEPTH_TEST); - gl.depthMask(true); - gl.depthFunc(gl.ALWAYS); - } - - if (opts.stencil !== undefined) { - flags |= gl.STENCIL_BUFFER_BIT; - gl.clearStencil(opts.stencil); - } - - gl.clear(flags); - - // restore depth-write - if (opts.depth !== undefined) { - if (this._current.depthTest === false) { - gl.disable(gl.DEPTH_TEST); - } else { - if (this._current.depthWrite === false) { - gl.depthMask(false); - } - if (this._current.depthFunc !== enums.DS_FUNC_ALWAYS) { - gl.depthFunc(this._current.depthFunc); - } - } - } - } - - // =============================== - // Deferred States - // =============================== - - /** - * @method enableBlend - */ - enableBlend() { - this._next.blend = true; - } - - /** - * @method enableDepthTest - */ - enableDepthTest() { - this._next.depthTest = true; - } - - /** - * @method enableDepthWrite - */ - enableDepthWrite() { - this._next.depthWrite = true; - } - - /** - * @method enableStencilTest - */ - enableStencilTest() { - this._next.stencilTest = true; - } - - /** - * @method setStencilFunc - * @param {DS_FUNC_*} func - * @param {Number} ref - * @param {Number} mask - */ - setStencilFunc(func, ref, mask) { - this._next.stencilSep = false; - this._next.stencilFuncFront = this._next.stencilFuncBack = func; - this._next.stencilRefFront = this._next.stencilRefBack = ref; - this._next.stencilMaskFront = this._next.stencilMaskBack = mask; - } - - /** - * @method setStencilFuncFront - * @param {DS_FUNC_*} func - * @param {Number} ref - * @param {Number} mask - */ - setStencilFuncFront(func, ref, mask) { - this._next.stencilSep = true; - this._next.stencilFuncFront = func; - this._next.stencilRefFront = ref; - this._next.stencilMaskFront = mask; - } - - /** - * @method setStencilFuncBack - * @param {DS_FUNC_*} func - * @param {Number} ref - * @param {Number} mask - */ - setStencilFuncBack(func, ref, mask) { - this._next.stencilSep = true; - this._next.stencilFuncBack = func; - this._next.stencilRefBack = ref; - this._next.stencilMaskBack = mask; - } - - /** - * @method setStencilOp - * @param {STENCIL_OP_*} failOp - * @param {STENCIL_OP_*} zFailOp - * @param {STENCIL_OP_*} zPassOp - * @param {Number} writeMask - */ - setStencilOp(failOp, zFailOp, zPassOp, writeMask) { - this._next.stencilFailOpFront = this._next.stencilFailOpBack = failOp; - this._next.stencilZFailOpFront = this._next.stencilZFailOpBack = zFailOp; - this._next.stencilZPassOpFront = this._next.stencilZPassOpBack = zPassOp; - this._next.stencilWriteMaskFront = this._next.stencilWriteMaskBack = writeMask; - } - - /** - * @method setStencilOpFront - * @param {STENCIL_OP_*} failOp - * @param {STENCIL_OP_*} zFailOp - * @param {STENCIL_OP_*} zPassOp - * @param {Number} writeMask - */ - setStencilOpFront(failOp, zFailOp, zPassOp, writeMask) { - this._next.stencilSep = true; - this._next.stencilFailOpFront = failOp; - this._next.stencilZFailOpFront = zFailOp; - this._next.stencilZPassOpFront = zPassOp; - this._next.stencilWriteMaskFront = writeMask; - } - - /** - * @method setStencilOpBack - * @param {STENCIL_OP_*} failOp - * @param {STENCIL_OP_*} zFailOp - * @param {STENCIL_OP_*} zPassOp - * @param {Number} writeMask - */ - setStencilOpBack(failOp, zFailOp, zPassOp, writeMask) { - this._next.stencilSep = true; - this._next.stencilFailOpBack = failOp; - this._next.stencilZFailOpBack = zFailOp; - this._next.stencilZPassOpBack = zPassOp; - this._next.stencilWriteMaskBack = writeMask; - } - - /** - * @method setDepthFunc - * @param {DS_FUNC_*} depthFunc - */ - setDepthFunc(depthFunc) { - this._next.depthFunc = depthFunc; - } - - /** - * @method setBlendColor32 - * @param {Number} rgba - */ - setBlendColor32(rgba) { - this._next.blendColor = rgba; - } - - /** - * @method setBlendColor - * @param {Number} r - * @param {Number} g - * @param {Number} b - * @param {Number} a - */ - setBlendColor(r, g, b, a) { - this._next.blendColor = ((r * 255) << 24 | (g * 255) << 16 | (b * 255) << 8 | a * 255) >>> 0; - } - - /** - * @method setBlendFunc - * @param {BELND_*} src - * @param {BELND_*} dst - */ - setBlendFunc(src, dst) { - this._next.blendSep = false; - this._next.blendSrc = src; - this._next.blendDst = dst; - } - - /** - * @method setBlendFuncSep - * @param {BELND_*} src - * @param {BELND_*} dst - * @param {BELND_*} srcAlpha - * @param {BELND_*} dstAlpha - */ - setBlendFuncSep(src, dst, srcAlpha, dstAlpha) { - this._next.blendSep = true; - this._next.blendSrc = src; - this._next.blendDst = dst; - this._next.blendSrcAlpha = srcAlpha; - this._next.blendDstAlpha = dstAlpha; - } - - /** - * @method setBlendEq - * @param {BELND_FUNC_*} eq - */ - setBlendEq(eq) { - this._next.blendSep = false; - this._next.blendEq = eq; - } - - /** - * @method setBlendEqSep - * @param {BELND_FUNC_*} eq - * @param {BELND_FUNC_*} alphaEq - */ - setBlendEqSep(eq, alphaEq) { - this._next.blendSep = true; - this._next.blendEq = eq; - this._next.blendAlphaEq = alphaEq; - } - - /** - * @method setCullMode - * @param {CULL_*} mode - */ - setCullMode(mode) { - this._next.cullMode = mode; - } - - /** - * @method setVertexBuffer - * @param {Number} stream - * @param {VertexBuffer} buffer - * @param {Number} start - start vertex - */ - setVertexBuffer(stream, buffer, start = 0) { - this._next.vertexBuffers[stream] = buffer; - this._next.vertexBufferOffsets[stream] = start; - if (this._next.maxStream < stream) { - this._next.maxStream = stream; - } - } - - /** - * @method setIndexBuffer - * @param {IndexBuffer} buffer - */ - setIndexBuffer(buffer) { - this._next.indexBuffer = buffer; - } - - /** - * @method setProgram - * @param {Program} program - */ - setProgram(program) { - this._next.program = program; - } - - /** - * @method setTexture - * @param {String} name - * @param {Texture} texture - * @param {Number} slot - */ - setTexture(name, texture, slot) { - if (slot >= this._caps.maxTextureUnits) { - console.warn(`Can not set texture ${name} at stage ${slot}, max texture exceed: ${this._caps.maxTextureUnits}`); - return; - } - - this._next.textureUnits[slot] = texture; - this.setUniform(name, slot); - - if (this._next.maxTextureSlot < slot) { - this._next.maxTextureSlot = slot; - } - } - - /** - * @method setTextureArray - * @param {String} name - * @param {Array} textures - * @param {Int32Array} slots - */ - setTextureArray(name, textures, slots) { - let len = textures.length; - if (len >= this._caps.maxTextureUnits) { - console.warn(`Can not set ${len} textures for ${name}, max texture exceed: ${this._caps.maxTextureUnits}`); - return; - } - for (let i = 0; i < len; ++i) { - let slot = slots[i]; - this._next.textureUnits[slot] = textures[i]; - } - this.setUniform(name, slots); - } - - /** - * @method setUniform - * @param {String} name - * @param {*} value - */ - setUniform(name, value) { - let uniform = this._uniforms[name]; - if (!uniform) { - uniform = { - dirty: true, - value: value, - }; - } else { - uniform.dirty = true; - uniform.value = value; - } - this._uniforms[name] = uniform; - } - - /** - * @method setPrimitiveType - * @param {PT_*} type - */ - setPrimitiveType(type) { - this._next.primitiveType = type; - } - - /** - * @method draw - * @param {Number} base - * @param {Number} count - */ - draw(base, count) { - const gl = this._gl; - let cur = this._current; - let next = this._next; - - // commit blend - _commitBlendStates(gl, cur, next); - - // commit depth - _commitDepthStates(gl, cur, next); - - // commit stencil - _commitStencilStates(gl, cur, next); - - // commit cull - _commitCullMode(gl, cur, next); - - // commit vertex-buffer - _commitVertexBuffers(this, gl, cur, next); - - // commit index-buffer - if (cur.indexBuffer !== next.indexBuffer) { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, next.indexBuffer ? next.indexBuffer._glID : null); - } - - // commit program - let programDirty = false; - if (cur.program !== next.program) { - if (next.program._linked) { - gl.useProgram(next.program._glID); - } - programDirty = true; - } - - // commit texture/sampler - _commitTextures(gl, cur, next); - - // commit uniforms - for (let i = 0; i < next.program._uniforms.length; ++i) { - let uniformInfo = next.program._uniforms[i]; - let uniform = this._uniforms[uniformInfo.name]; - if (!uniform) { - // console.warn(`Can not find uniform ${uniformInfo.name}`); - continue; - } - - if (!programDirty && !uniform.dirty) { - continue; - } - - uniform.dirty = false; - - // TODO: please consider array uniform: uniformInfo.size > 0 - - let commitFunc = (uniformInfo.size === undefined) ? _type2uniformCommit[uniformInfo.type] : _type2uniformArrayCommit[uniformInfo.type]; - if (!commitFunc) { - console.warn(`Can not find commit function for uniform ${uniformInfo.name}`); - continue; - } - - commitFunc(gl, uniformInfo.location, uniform.value); - } - - // drawPrimitives - if (next.indexBuffer) { - gl.drawElements( - this._next.primitiveType, - count, - next.indexBuffer._format, - base * next.indexBuffer._bytesPerIndex - ); - } else { - gl.drawArrays( - this._next.primitiveType, - base, - count - ); - } - - // TODO: autogen mipmap for color buffer - // if (this._framebuffer && this._framebuffer.colors[0].mipmap) { - // gl.bindTexture(this._framebuffer.colors[i]._target, colors[i]._glID); - // gl.generateMipmap(this._framebuffer.colors[i]._target); - // } - - // update stats - this._stats.drawcalls += 1; - - // reset states - cur.set(next); - next.reset(); - } -} diff --git a/cocos/renderer/gfx/enums.js b/cocos/renderer/gfx/enums.js deleted file mode 100644 index 16e34dfc7a..0000000000 --- a/cocos/renderer/gfx/enums.js +++ /dev/null @@ -1,336 +0,0 @@ -const GL_NEAREST = 9728; // gl.NEAREST -const GL_LINEAR = 9729; // gl.LINEAR -const GL_NEAREST_MIPMAP_NEAREST = 9984; // gl.NEAREST_MIPMAP_NEAREST -const GL_LINEAR_MIPMAP_NEAREST = 9985; // gl.LINEAR_MIPMAP_NEAREST -const GL_NEAREST_MIPMAP_LINEAR = 9986; // gl.NEAREST_MIPMAP_LINEAR -const GL_LINEAR_MIPMAP_LINEAR = 9987; // gl.LINEAR_MIPMAP_LINEAR - -// const GL_BYTE = 5120; // gl.BYTE -const GL_UNSIGNED_BYTE = 5121; // gl.UNSIGNED_BYTE -// const GL_SHORT = 5122; // gl.SHORT -const GL_UNSIGNED_SHORT = 5123; // gl.UNSIGNED_SHORT -const GL_UNSIGNED_INT = 5125; // gl.UNSIGNED_INT -const GL_FLOAT = 5126; // gl.FLOAT -const GL_UNSIGNED_SHORT_5_6_5 = 33635; // gl.UNSIGNED_SHORT_5_6_5 -const GL_UNSIGNED_SHORT_4_4_4_4 = 32819; // gl.UNSIGNED_SHORT_4_4_4_4 -const GL_UNSIGNED_SHORT_5_5_5_1 = 32820; // gl.UNSIGNED_SHORT_5_5_5_1 -const GL_HALF_FLOAT_OES = 36193; // gl.HALF_FLOAT_OES - -const GL_DEPTH_COMPONENT = 6402; // gl.DEPTH_COMPONENT - -const GL_ALPHA = 6406; // gl.ALPHA -const GL_RGB = 6407; // gl.RGB -const GL_RGBA = 6408; // gl.RGBA -const GL_LUMINANCE = 6409; // gl.LUMINANCE -const GL_LUMINANCE_ALPHA = 6410; // gl.LUMINANCE_ALPHA - -const GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0; // ext.COMPRESSED_RGB_S3TC_DXT1_EXT -const GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1; // ext.COMPRESSED_RGBA_S3TC_DXT1_EXT -const GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2; // ext.COMPRESSED_RGBA_S3TC_DXT3_EXT -const GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3; // ext.COMPRESSED_RGBA_S3TC_DXT5_EXT - -const GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00; // ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG -const GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01; // ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG -const GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02; // ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG -const GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03; // ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG - -const GL_COMPRESSED_RGB_ETC1_WEBGL = 0x8D64; // ext.COMPRESSED_RGB_ETC1_WEBGL - -const _filterGL = [ - [ GL_NEAREST, GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR ], - [ GL_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_LINEAR ], -]; - -const _textureFmtGL = [ - // TEXTURE_FMT_RGB_DXT1: 0 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_S3TC_DXT1_EXT, pixelType: null }, - - // TEXTURE_FMT_RGBA_DXT1: 1 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixelType: null }, - - // TEXTURE_FMT_RGBA_DXT3: 2 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, pixelType: null }, - - // TEXTURE_FMT_RGBA_DXT5: 3 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, pixelType: null }, - - // TEXTURE_FMT_RGB_ETC1: 4 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_ETC1_WEBGL, pixelType: null }, - - // TEXTURE_FMT_RGB_PVRTC_2BPPV1: 5 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_RGBA_PVRTC_2BPPV1: 6 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_RGB_PVRTC_4BPPV1: 7 - { format: GL_RGB, internalFormat: GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_RGBA_PVRTC_4BPPV1: 8 - { format: GL_RGBA, internalFormat: GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, pixelType: null }, - - // TEXTURE_FMT_A8: 9 - { format: GL_ALPHA, internalFormat: GL_ALPHA, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_L8: 10 - { format: GL_LUMINANCE, internalFormat: GL_LUMINANCE, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_L8_A8: 11 - { format: GL_LUMINANCE_ALPHA, internalFormat: GL_LUMINANCE_ALPHA, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_R5_G6_B5: 12 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_UNSIGNED_SHORT_5_6_5 }, - - // TEXTURE_FMT_R5_G5_B5_A1: 13 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_SHORT_5_5_5_1 }, - - // TEXTURE_FMT_R4_G4_B4_A4: 14 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_SHORT_4_4_4_4 }, - - // TEXTURE_FMT_RGB8: 15 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_RGBA8: 16 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_UNSIGNED_BYTE }, - - // TEXTURE_FMT_RGB16F: 17 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_HALF_FLOAT_OES }, - - // TEXTURE_FMT_RGBA16F: 18 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_HALF_FLOAT_OES }, - - // TEXTURE_FMT_RGB32F: 19 - { format: GL_RGB, internalFormat: GL_RGB, pixelType: GL_FLOAT }, - - // TEXTURE_FMT_RGBA32F: 20 - { format: GL_RGBA, internalFormat: GL_RGBA, pixelType: GL_FLOAT }, - - // TEXTURE_FMT_R32F: 21 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_111110F: 22 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_SRGB: 23 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_SRGBA: 24 - { format: null, internalFormat: null, pixelType: null }, - - // TEXTURE_FMT_D16: 25 - { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_SHORT }, - - // TEXTURE_FMT_D32: 26 - { format: GL_DEPTH_COMPONENT, internalFormat: GL_DEPTH_COMPONENT, pixelType: GL_UNSIGNED_INT }, - - // TEXTURE_FMT_D24S8: 27 - { format: null, internalFormat: null, pixelType: null }, -]; - -/** - * enums - */ -export const enums = { - // buffer usage - USAGE_STATIC: 35044, // gl.STATIC_DRAW - USAGE_DYNAMIC: 35048, // gl.DYNAMIC_DRAW - USAGE_STREAM: 35040, // gl.STREAM_DRAW - - // index buffer format - INDEX_FMT_UINT8: 5121, // gl.UNSIGNED_BYTE - INDEX_FMT_UINT16: 5123, // gl.UNSIGNED_SHORT - INDEX_FMT_UINT32: 5125, // gl.UNSIGNED_INT (OES_element_index_uint) - - // vertex attribute semantic - ATTR_POSITION: 'a_position', - ATTR_NORMAL: 'a_normal', - ATTR_TANGENT: 'a_tangent', - ATTR_BITANGENT: 'a_bitangent', - ATTR_WEIGHTS: 'a_weights', - ATTR_JOINTS: 'a_joints', - ATTR_COLOR: 'a_color', - ATTR_COLOR0: 'a_color0', - ATTR_COLOR1: 'a_color1', - ATTR_UV: 'a_uv', - ATTR_UV0: 'a_uv0', - ATTR_UV1: 'a_uv1', - ATTR_UV2: 'a_uv2', - ATTR_UV3: 'a_uv3', - ATTR_UV4: 'a_uv4', - ATTR_UV5: 'a_uv5', - ATTR_UV6: 'a_uv6', - ATTR_UV7: 'a_uv7', - - // vertex attribute type - ATTR_TYPE_INT8: 5120, // gl.BYTE - ATTR_TYPE_UINT8: 5121, // gl.UNSIGNED_BYTE - ATTR_TYPE_INT16: 5122, // gl.SHORT - ATTR_TYPE_UINT16: 5123, // gl.UNSIGNED_SHORT - ATTR_TYPE_INT32: 5124, // gl.INT - ATTR_TYPE_UINT32: 5125, // gl.UNSIGNED_INT - ATTR_TYPE_FLOAT32: 5126, // gl.FLOAT - - // texture filter - FILTER_NEAREST: 0, - FILTER_LINEAR: 1, - - // texture wrap mode - WRAP_REPEAT: 10497, // gl.REPEAT - WRAP_CLAMP: 33071, // gl.CLAMP_TO_EDGE - WRAP_MIRROR: 33648, // gl.MIRRORED_REPEAT - - // texture format - // compress formats - TEXTURE_FMT_RGB_DXT1: 0, - TEXTURE_FMT_RGBA_DXT1: 1, - TEXTURE_FMT_RGBA_DXT3: 2, - TEXTURE_FMT_RGBA_DXT5: 3, - TEXTURE_FMT_RGB_ETC1: 4, - TEXTURE_FMT_RGB_PVRTC_2BPPV1: 5, - TEXTURE_FMT_RGBA_PVRTC_2BPPV1: 6, - TEXTURE_FMT_RGB_PVRTC_4BPPV1: 7, - TEXTURE_FMT_RGBA_PVRTC_4BPPV1: 8, - - // normal formats - TEXTURE_FMT_A8: 9, - TEXTURE_FMT_L8: 10, - TEXTURE_FMT_L8_A8: 11, - TEXTURE_FMT_R5_G6_B5: 12, - TEXTURE_FMT_R5_G5_B5_A1: 13, - TEXTURE_FMT_R4_G4_B4_A4: 14, - TEXTURE_FMT_RGB8: 15, - TEXTURE_FMT_RGBA8: 16, - TEXTURE_FMT_RGB16F: 17, - TEXTURE_FMT_RGBA16F: 18, - TEXTURE_FMT_RGB32F: 19, - TEXTURE_FMT_RGBA32F: 20, - TEXTURE_FMT_R32F: 21, - TEXTURE_FMT_111110F: 22, - TEXTURE_FMT_SRGB: 23, - TEXTURE_FMT_SRGBA: 24, - - // depth formats - TEXTURE_FMT_D16: 25, - TEXTURE_FMT_D32: 26, - TEXTURE_FMT_D24S8: 27, - - // depth and stencil function - DS_FUNC_NEVER: 512, // gl.NEVER - DS_FUNC_LESS: 513, // gl.LESS - DS_FUNC_EQUAL: 514, // gl.EQUAL - DS_FUNC_LEQUAL: 515, // gl.LEQUAL - DS_FUNC_GREATER: 516, // gl.GREATER - DS_FUNC_NOTEQUAL: 517, // gl.NOTEQUAL - DS_FUNC_GEQUAL: 518, // gl.GEQUAL - DS_FUNC_ALWAYS: 519, // gl.ALWAYS - - // render-buffer format - RB_FMT_RGBA4: 32854, // gl.RGBA4 - RB_FMT_RGB5_A1: 32855, // gl.RGB5_A1 - RB_FMT_RGB565: 36194, // gl.RGB565 - RB_FMT_D16: 33189, // gl.DEPTH_COMPONENT16 - RB_FMT_S8: 36168, // gl.STENCIL_INDEX8 - RB_FMT_D24S8: 34041, // gl.DEPTH_STENCIL - - // blend-equation - BLEND_FUNC_ADD: 32774, // gl.FUNC_ADD - BLEND_FUNC_SUBTRACT: 32778, // gl.FUNC_SUBTRACT - BLEND_FUNC_REVERSE_SUBTRACT: 32779, // gl.FUNC_REVERSE_SUBTRACT - - // blend - BLEND_ZERO: 0, // gl.ZERO - BLEND_ONE: 1, // gl.ONE - BLEND_SRC_COLOR: 768, // gl.SRC_COLOR - BLEND_ONE_MINUS_SRC_COLOR: 769, // gl.ONE_MINUS_SRC_COLOR - BLEND_DST_COLOR: 774, // gl.DST_COLOR - BLEND_ONE_MINUS_DST_COLOR: 775, // gl.ONE_MINUS_DST_COLOR - BLEND_SRC_ALPHA: 770, // gl.SRC_ALPHA - BLEND_ONE_MINUS_SRC_ALPHA: 771, // gl.ONE_MINUS_SRC_ALPHA - BLEND_DST_ALPHA: 772, // gl.DST_ALPHA - BLEND_ONE_MINUS_DST_ALPHA: 773, // gl.ONE_MINUS_DST_ALPHA - BLEND_CONSTANT_COLOR: 32769, // gl.CONSTANT_COLOR - BLEND_ONE_MINUS_CONSTANT_COLOR: 32770, // gl.ONE_MINUS_CONSTANT_COLOR - BLEND_CONSTANT_ALPHA: 32771, // gl.CONSTANT_ALPHA - BLEND_ONE_MINUS_CONSTANT_ALPHA: 32772, // gl.ONE_MINUS_CONSTANT_ALPHA - BLEND_SRC_ALPHA_SATURATE: 776, // gl.SRC_ALPHA_SATURATE - - // stencil operation - STENCIL_OP_KEEP: 7680, // gl.KEEP - STENCIL_OP_ZERO: 0, // gl.ZERO - STENCIL_OP_REPLACE: 7681, // gl.REPLACE - STENCIL_OP_INCR: 7682, // gl.INCR - STENCIL_OP_INCR_WRAP: 34055, // gl.INCR_WRAP - STENCIL_OP_DECR: 7683, // gl.DECR - STENCIL_OP_DECR_WRAP: 34056, // gl.DECR_WRAP - STENCIL_OP_INVERT: 5386, // gl.INVERT - - // cull - CULL_NONE: 0, - CULL_FRONT: 1028, - CULL_BACK: 1029, - CULL_FRONT_AND_BACK: 1032, - - // primitive type - PT_POINTS: 0, // gl.POINTS - PT_LINES: 1, // gl.LINES - PT_LINE_LOOP: 2, // gl.LINE_LOOP - PT_LINE_STRIP: 3, // gl.LINE_STRIP - PT_TRIANGLES: 4, // gl.TRIANGLES - PT_TRIANGLE_STRIP: 5, // gl.TRIANGLE_STRIP - PT_TRIANGLE_FAN: 6, // gl.TRIANGLE_FAN -}; - -/** - * @method attrTypeBytes - * @param {ATTR_TYPE_*} attrType - */ -export function attrTypeBytes(attrType) { - if (attrType === enums.ATTR_TYPE_INT8) { - return 1; - } else if (attrType === enums.ATTR_TYPE_UINT8) { - return 1; - } else if (attrType === enums.ATTR_TYPE_INT16) { - return 2; - } else if (attrType === enums.ATTR_TYPE_UINT16) { - return 2; - } else if (attrType === enums.ATTR_TYPE_INT32) { - return 4; - } else if (attrType === enums.ATTR_TYPE_UINT32) { - return 4; - } else if (attrType === enums.ATTR_TYPE_FLOAT32) { - return 4; - } - - console.warn(`Unknown ATTR_TYPE: ${attrType}`); - return 0; -} - -/** - * @method glFilter - * @param {WebGLContext} gl - * @param {FILTER_*} filter - * @param {FILTER_*} mipFilter - */ -export function glFilter(gl, filter, mipFilter = -1) { - let result = _filterGL[filter][mipFilter+1]; - if (result === undefined) { - console.warn(`Unknown FILTER: ${filter}`); - return mipFilter === -1 ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR; - } - - return result; -} - -/** - * @method glTextureFmt - * @param {TEXTURE_FMT_*} fmt - */ -export function glTextureFmt(fmt) { - let result = _textureFmtGL[fmt]; - if (result === undefined) { - console.warn(`Unknown TEXTURE_FMT: ${fmt}`); - return _textureFmtGL[enums.TEXTURE_FMT_RGBA8]; - } - - return result; -} \ No newline at end of file diff --git a/cocos/renderer/gfx/frame-buffer.js b/cocos/renderer/gfx/frame-buffer.js deleted file mode 100644 index bd43954818..0000000000 --- a/cocos/renderer/gfx/frame-buffer.js +++ /dev/null @@ -1,41 +0,0 @@ -export default class FrameBuffer { - /** - * @constructor - * @param {Device} device - * @param {Number} width - * @param {Number} height - * @param {Object} options - * @param {Array} options.colors - * @param {RenderBuffer|Texture2D|TextureCube} options.depth - * @param {RenderBuffer|Texture2D|TextureCube} options.stencil - * @param {RenderBuffer|Texture2D|TextureCube} options.depthStencil - */ - constructor(device, width, height, options) { - this._device = device; - this._width = width; - this._height = height; - - this._colors = options.colors || []; - this._depth = options.depth || null; - this._stencil = options.stencil || null; - this._depthStencil = options.depthStencil || null; - - this._glID = device._gl.createFramebuffer(); - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === null) { - console.error('The frame-buffer already destroyed'); - return; - } - - const gl = this._device._gl; - - gl.deleteFramebuffer(this._glID); - - this._glID = null; - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/index-buffer.js b/cocos/renderer/gfx/index-buffer.js deleted file mode 100644 index 029a5f0b28..0000000000 --- a/cocos/renderer/gfx/index-buffer.js +++ /dev/null @@ -1,134 +0,0 @@ -import { enums } from './enums'; - -class IndexBuffer { - /** - * @constructor - * @param {Device} device - * @param {INDEX_FMT_*} format - * @param {USAGE_*} usage - * @param {ArrayBuffer | Uint8Array} data - * @param {Number} numIndices - */ - constructor(device, format, usage, data, numIndices) { - this._device = device; - this._format = format; - this._usage = usage; - this._numIndices = numIndices; - this._bytesPerIndex = 0; - - // calculate bytes - if (format === enums.INDEX_FMT_UINT8) { - this._bytesPerIndex = 1; - } else if (format === enums.INDEX_FMT_UINT16) { - this._bytesPerIndex = 2; - } else if (format === enums.INDEX_FMT_UINT32) { - this._bytesPerIndex = 4; - } - this._bytes = this._bytesPerIndex * numIndices; - - // update - this._glID = device._gl.createBuffer(); - this.update(0, data); - - // stats - device._stats.ib += this._bytes; - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === -1) { - console.error('The buffer already destroyed'); - return; - } - - let gl = this._device._gl; - gl.deleteBuffer(this._glID); - this._device._stats.ib -= this.bytes; - - this._glID = -1; - } - - /** - * @method update - * @param {Number} offset - * @param {ArrayBuffer} data - */ - update(offset, data) { - if (this._glID === -1) { - console.error('The buffer is destroyed'); - return; - } - - if (data && data.byteLength + offset > this._bytes) { - console.error('Failed to update data, bytes exceed.'); - return; - } - - /** @type{WebGLRenderingContext} */ - let gl = this._device._gl; - let glUsage = this._usage; - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glID); - if (!data) { - if (this._bytes) { - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._bytes, glUsage); - } else { - console.warn('bufferData should not submit 0 bytes data'); - } - } else { - if (offset) { - gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, offset, data); - } else { - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, glUsage); - } - } - this._device._restoreIndexBuffer(); - } - - get count () { - return this._numIndices; - } -} - -if (CC_EDITOR) { - let _type2fn = { - [enums.ATTR_TYPE_INT8]: 'getInt8', - [enums.ATTR_TYPE_UINT8]: 'getUint8', - [enums.ATTR_TYPE_INT16]: 'getInt16', - [enums.ATTR_TYPE_UINT16]: 'getUint16', - [enums.ATTR_TYPE_INT32]: 'getInt32', - [enums.ATTR_TYPE_UINT32]: 'getUint32', - [enums.ATTR_TYPE_FLOAT32]: 'getFloat32' - }; - let littleEndian = (function() { - let buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - let createCache = function(ib, data) { - if (!data) return []; - let icount = data.byteLength / ib._bytesPerIndex; - let result = new Array(icount); - for (let i = 0; i < icount; i++) { - let fname = _type2fn[ib._format]; - result[i] = data[fname](i * ib._bytesPerIndex, littleEndian); - } - return result; - }; - IndexBuffer.prototype.do_update = IndexBuffer.prototype.update; - IndexBuffer.prototype.update = function(offset, data) { - this.do_update(offset, data); - // don't need to create for IA pools - if (data && this._bytes !== data.byteLength) return; - if (data instanceof ArrayBuffer) - data = new DataView(data); - else if (ArrayBuffer.isView(data) && !(data instanceof DataView)) - data = new DataView(data.buffer, data.byteOffset, data.byteLength); - this._data = createCache(this, data); - }; -} - -export default IndexBuffer; diff --git a/cocos/renderer/gfx/index.js b/cocos/renderer/gfx/index.js deleted file mode 100644 index 7687de6774..0000000000 --- a/cocos/renderer/gfx/index.js +++ /dev/null @@ -1,40 +0,0 @@ -import { - enums, - attrTypeBytes, - glFilter, - glTextureFmt, -} from './enums'; - -import VertexFormat from './vertex-format'; -import IndexBuffer from './index-buffer'; -import VertexBuffer from './vertex-buffer'; -import Program from './program'; -import Texture from './texture'; -import Texture2D from './texture-2d'; -import TextureCube from './texture-cube'; -import RenderBuffer from './render-buffer'; -import FrameBuffer from './frame-buffer'; -import Device from './device'; - -let gfx = { - // classes - VertexFormat, - IndexBuffer, - VertexBuffer, - Program, - Texture, - Texture2D, - TextureCube, - RenderBuffer, - FrameBuffer, - Device, - - // functions - attrTypeBytes, - glFilter, - glTextureFmt, -}; -Object.assign(gfx, enums); - -export default gfx; -cc.gfx = gfx; diff --git a/cocos/renderer/gfx/misc.js b/cocos/renderer/gfx/misc.js deleted file mode 100644 index 9825541ea8..0000000000 --- a/cocos/renderer/gfx/misc.js +++ /dev/null @@ -1,3 +0,0 @@ -export function isPow2(v) { - return !(v & (v - 1)) && (!!v); -} \ No newline at end of file diff --git a/cocos/renderer/gfx/program.js b/cocos/renderer/gfx/program.js deleted file mode 100644 index 6961b73372..0000000000 --- a/cocos/renderer/gfx/program.js +++ /dev/null @@ -1,176 +0,0 @@ -let _genID = 0; - -function _parseError(out, type, errorLog) { - errorLog.split('\n').forEach(msg => { - if (msg.length < 5) { - return; - } - - let parts = /^ERROR:\s+(\d+):(\d+):\s*(.*)$/.exec(msg); - if (parts) { - out.push({ - type: type, - fileID: parts[1] | 0, - line: parts[2] | 0, - message: parts[3].trim() - }); - } else if (msg.length > 0) { - out.push({ - type: type, - fileID: -1, - line: 0, - message: msg - }); - } - }); -} - -export default class Program { - /** - * @param {ef.GraphicsDevice} device - graphic device - * @param {object} options - shader definition - * @param {string} options.vert - vertex shader source code - * @param {string} options.frag - fragment shader shader source code - * @example - * let prog = new Program(device, { - * vert: ` - * attribute vec3 a_position; - * void main() { - * gl_Position = vec4( a_position, 1.0 ); - * } - * `, - * frag: ` - * precision mediump float; - * void main() { - * gl_FragColor = vec4( 1.0, 1.0, 1.0, 1.0 ); - * } - * ` - * }); - */ - constructor(device, options) { - this._device = device; - - // stores gl information: { location, type } - this._attributes = []; - this._uniforms = []; - this._samplers = []; - this._errors = []; - this._linked = false; - this._vertSource = options.vert; - this._fragSource = options.frag; - this._glID = null; - this._id = _genID++; - } - - get id() { - return this._id; - } - - link() { - if (this._linked) { - return; - } - - let gl = this._device._gl; - - let vertShader = _createShader(gl, gl.VERTEX_SHADER, this._vertSource); - let fragShader = _createShader(gl, gl.FRAGMENT_SHADER, this._fragSource); - - let program = gl.createProgram(); - gl.attachShader(program, vertShader); - gl.attachShader(program, fragShader); - gl.linkProgram(program); - - let failed = false; - let errors = this._errors; - - if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { - _parseError(errors, 'vs', gl.getShaderInfoLog(vertShader)); - failed = true; - } - - if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { - _parseError(errors, 'fs', gl.getShaderInfoLog(fragShader)); - failed = true; - } - - gl.deleteShader(vertShader); - gl.deleteShader(fragShader); - - if (failed) { - errors.forEach(err => { - console.error(`Failed to compile ${err.type} ${err.fileID} (ln ${err.line}): ${err.message}`); - }); - return; - } - - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - console.error(`Failed to link shader program: ${gl.getProgramInfoLog(program)}`); - failed = true; - } - - if (failed) { - return; - } - - this._glID = program; - - // parse attribute - let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (let i = 0; i < numAttributes; ++i) { - let info = gl.getActiveAttrib(program, i); - let location = gl.getAttribLocation(program, info.name); - - this._attributes.push({ - name: info.name, - location: location, - type: info.type, - }); - } - - // parse uniform - let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (let i = 0; i < numUniforms; ++i) { - let info = gl.getActiveUniform(program, i); - let name = info.name; - let location = gl.getUniformLocation(program, name); - let isArray = name.substr(name.length - 3) === '[0]'; - if (isArray) { - name = name.substr(0, name.length - 3); - } - - let uniform = { - name: name, - location: location, - type: info.type, - size: isArray ? info.size : undefined, // used when uniform is an array - }; - this._uniforms.push(uniform); - } - - this._linked = true; - } - - destroy() { - let gl = this._device._gl; - gl.deleteProgram(this._glID); - - this._linked = false; - this._glID = null; - this._attributes = []; - this._uniforms = []; - this._samplers = []; - } -} - -// ==================== -// internal -// ==================== - -function _createShader(gl, type, src) { - let shader = gl.createShader(type); - gl.shaderSource(shader, src); - gl.compileShader(shader); - - return shader; -} \ No newline at end of file diff --git a/cocos/renderer/gfx/render-buffer.js b/cocos/renderer/gfx/render-buffer.js deleted file mode 100644 index ca7c3d2733..0000000000 --- a/cocos/renderer/gfx/render-buffer.js +++ /dev/null @@ -1,42 +0,0 @@ -export default class RenderBuffer { - /** - * @constructor - * @param {Device} device - * @param {RB_FMT_*} format - * @param {Number} width - * @param {Number} height - */ - constructor(device, format, width, height) { - this._device = device; - this._format = format; - - this._glID = device._gl.createRenderbuffer(); - this.update(width, height); - } - - update(width, height) { - this._width = width; - this._height = height; - const gl = this._device._gl; - gl.bindRenderbuffer(gl.RENDERBUFFER, this._glID); - gl.renderbufferStorage(gl.RENDERBUFFER, this._format, width, height); - gl.bindRenderbuffer(gl.RENDERBUFFER, null); - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === null) { - console.error('The render-buffer already destroyed'); - return; - } - - const gl = this._device._gl; - - gl.bindRenderbuffer(gl.RENDERBUFFER, null); - gl.deleteRenderbuffer(this._glID); - - this._glID = null; - } -} diff --git a/cocos/renderer/gfx/state.js b/cocos/renderer/gfx/state.js deleted file mode 100644 index 747ed4a7b9..0000000000 --- a/cocos/renderer/gfx/state.js +++ /dev/null @@ -1,133 +0,0 @@ -import { enums } from './enums'; - -const _default = { - // blend - blend: false, - blendSep: false, - blendColor: 0xffffffff, - blendEq: enums.BLEND_FUNC_ADD, - blendAlphaEq: enums.BLEND_FUNC_ADD, - blendSrc: enums.BLEND_ONE, - blendDst: enums.BLEND_ZERO, - blendSrcAlpha: enums.BLEND_ONE, - blendDstAlpha: enums.BLEND_ZERO, - - // depth - depthTest: false, - depthWrite: false, - depthFunc: enums.DS_FUNC_LESS, - - // stencil - stencilTest: false, - stencilSep: false, - stencilFuncFront: enums.DS_FUNC_ALWAYS, - stencilRefFront: 0, - stencilMaskFront: 0xff, - stencilFailOpFront: enums.STENCIL_OP_KEEP, - stencilZFailOpFront: enums.STENCIL_OP_KEEP, - stencilZPassOpFront: enums.STENCIL_OP_KEEP, - stencilWriteMaskFront: 0xff, - stencilFuncBack: enums.DS_FUNC_ALWAYS, - stencilRefBack: 0, - stencilMaskBack: 0xff, - stencilFailOpBack: enums.STENCIL_OP_KEEP, - stencilZFailOpBack: enums.STENCIL_OP_KEEP, - stencilZPassOpBack: enums.STENCIL_OP_KEEP, - stencilWriteMaskBack: 0xff, - - // cull-mode - cullMode: enums.CULL_BACK, - - // primitive-type - primitiveType: enums.PT_TRIANGLES, - - // bindings - maxStream: -1, - vertexBuffers: [], - vertexBufferOffsets: [], - indexBuffer: null, - maxTextureSlot: -1, - textureUnits: [], - program: null, -}; - -export default class State { - constructor(device) { - // bindings - this.vertexBuffers = new Array(device._caps.maxVertexStreams); - this.vertexBufferOffsets = new Array(device._caps.maxVertexStreams); - this.textureUnits = new Array(device._caps.maxTextureUnits); - - this.set(_default); - } - - static initDefault(device) { - _default.vertexBuffers = new Array(device._caps.maxVertexStreams); - _default.vertexBufferOffsets = new Array(device._caps.maxVertexStreams); - _default.textureUnits = new Array(device._caps.maxTextureUnits); - } - - reset () { - this.set(_default); - } - - set (cpy) { - // blending - this.blend = cpy.blend; - this.blendSep = cpy.blendSep; - this.blendColor = cpy.blendColor; - this.blendEq = cpy.blendEq; - this.blendAlphaEq = cpy.blendAlphaEq; - this.blendSrc = cpy.blendSrc; - this.blendDst = cpy.blendDst; - this.blendSrcAlpha = cpy.blendSrcAlpha; - this.blendDstAlpha = cpy.blendDstAlpha; - - // depth - this.depthTest = cpy.depthTest; - this.depthWrite = cpy.depthWrite; - this.depthFunc = cpy.depthFunc; - - // stencil - this.stencilTest = cpy.stencilTest; - this.stencilSep = cpy.stencilSep; - this.stencilFuncFront = cpy.stencilFuncFront; - this.stencilRefFront = cpy.stencilRefFront; - this.stencilMaskFront = cpy.stencilMaskFront; - this.stencilFailOpFront = cpy.stencilFailOpFront; - this.stencilZFailOpFront = cpy.stencilZFailOpFront; - this.stencilZPassOpFront = cpy.stencilZPassOpFront; - this.stencilWriteMaskFront = cpy.stencilWriteMaskFront; - this.stencilFuncBack = cpy.stencilFuncBack; - this.stencilRefBack = cpy.stencilRefBack; - this.stencilMaskBack = cpy.stencilMaskBack; - this.stencilFailOpBack = cpy.stencilFailOpBack; - this.stencilZFailOpBack = cpy.stencilZFailOpBack; - this.stencilZPassOpBack = cpy.stencilZPassOpBack; - this.stencilWriteMaskBack = cpy.stencilWriteMaskBack; - - // cull-mode - this.cullMode = cpy.cullMode; - - // primitive-type - this.primitiveType = cpy.primitiveType; - - // buffer bindings - this.maxStream = cpy.maxStream; - for (let i = 0; i < cpy.vertexBuffers.length; ++i) { - this.vertexBuffers[i] = cpy.vertexBuffers[i]; - } - for (let i = 0; i < cpy.vertexBufferOffsets.length; ++i) { - this.vertexBufferOffsets[i] = cpy.vertexBufferOffsets[i]; - } - this.indexBuffer = cpy.indexBuffer; - - // texture bindings - this.maxTextureSlot = cpy.maxTextureSlot; - for (let i = 0; i < cpy.textureUnits.length; ++i) { - this.textureUnits[i] = cpy.textureUnits[i]; - } - - this.program = cpy.program; - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/texture-2d.js b/cocos/renderer/gfx/texture-2d.js deleted file mode 100644 index 3a732514ed..0000000000 --- a/cocos/renderer/gfx/texture-2d.js +++ /dev/null @@ -1,333 +0,0 @@ -// @ts-check -import Texture from './texture'; -import { enums, glFilter, glTextureFmt } from './enums'; -import { isPow2 } from './misc'; - -/** - * @typedef {HTMLImageElement | HTMLCanvasElement} HTMLImageSource - * @typedef {HTMLImageSource | ArrayBufferView} ImageSource - * @typedef {{width?: number, height?: number, minFilter?: number, magFilter?: number, mipFilter?: number, wrapS?: number, wrapT?: number, format?: number, mipmap?: boolean, images?: ImageSource[], image?: ImageSource, flipY?: boolean, premultiplyAlpha?: boolean, anisotropy?: number}} TextureUpdateOpts - * @typedef {import("../gfx/device").default} Device - */ - -export default class Texture2D extends Texture { - /** - * @constructor - * @param {Device} device - * @param {TextureUpdateOpts} options - */ - constructor(device, options) { - super(device); - - let gl = this._device._gl; - this._target = gl.TEXTURE_2D; - this._glID = gl.createTexture(); - - // always alloc texture in GPU when we create it. - options.images = options.images || [null]; - this.update(options); - } - - /** - * @method update - * @param {TextureUpdateOpts} options - */ - update(options) { - let gl = this._device._gl; - let genMipmap = this._hasMipmap; - - if (options) { - if (options.width !== undefined) { - this._width = options.width; - } - if (options.height !== undefined) { - this._height = options.height; - } - if (options.anisotropy !== undefined) { - this._anisotropy = options.anisotropy; - } - if (options.minFilter !== undefined) { - this._minFilter = options.minFilter; - } - if (options.magFilter !== undefined) { - this._magFilter = options.magFilter; - } - if (options.mipFilter !== undefined) { - this._mipFilter = options.mipFilter; - } - if (options.wrapS !== undefined) { - this._wrapS = options.wrapS; - } - if (options.wrapT !== undefined) { - this._wrapT = options.wrapT; - } - if (options.format !== undefined) { - this._format = options.format; - this._compressed = ( - this._format >= enums.TEXTURE_FMT_RGB_DXT1 && - this._format <= enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1 - ); - } - - // check if generate mipmap - if (options.mipmap !== undefined) { - this._hasMipmap = options.mipmap; - genMipmap = options.mipmap; - } - - if (options.images !== undefined) { - if (options.images.length > 1) { - genMipmap = false; - let maxLength = options.width > options.height ? options.width : options.height; - if (maxLength >> (options.images.length - 1) !== 1) { - console.error('texture-2d mipmap is invalid, should have a 1x1 mipmap.'); - } - } - } - } - - // NOTE: get pot after this._width, this._height has been assigned. - let pot = isPow2(this._width) && isPow2(this._height); - if (!pot) { - genMipmap = false; - } - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this._glID); - if (options.images !== undefined && options.images.length > 0) { - this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); - if (options.images.length > 1) this._hasMipmap = true; - } - if (genMipmap) { - gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); - gl.generateMipmap(gl.TEXTURE_2D); - this._hasMipmap = true; - } - - this._setTexInfo(); - this._device._restoreTexture(0); - } - - /** - * @method updateSubImage - * @param {Object} options - * @param {Number} options.x - * @param {Number} options.y - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateSubImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this._glID); - this._setSubImage(glFmt, options); - this._device._restoreTexture(0); - } - - /** - * @method updateImage - * @param {Object} options - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this._glID); - this._setImage(glFmt, options); - this._device._restoreTexture(0); - } - - _setSubImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let img = options.image; - - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - gl.texSubImage2D(gl.TEXTURE_2D, options.level, options.x, options.y, glFmt.format, glFmt.pixelType, img); - } else { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - if (this._compressed) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - img - ); - } else { - gl.texSubImage2D( - gl.TEXTURE_2D, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - _setImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let img = options.image; - - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - gl.texImage2D( - gl.TEXTURE_2D, - options.level, - glFmt.internalFormat, - glFmt.format, - glFmt.pixelType, - img - ); - } else { - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - if (this._compressed) { - gl.compressedTexImage2D( - gl.TEXTURE_2D, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - img - ); - } else { - gl.texImage2D( - gl.TEXTURE_2D, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - _setMipmap(images, flipY, premultiplyAlpha) { - let glFmt = glTextureFmt(this._format); - let options = { - width: this._width, - height: this._height, - flipY: flipY, - premultiplyAlpha: premultiplyAlpha, - level: 0, - image: null - }; - - for (let i = 0; i < images.length; ++i) { - options.level = i; - options.width = this._width >> i; - options.height = this._height >> i; - options.image = images[i]; - this._setImage(glFmt, options); - } - } - - _setTexInfo() { - let gl = this._device._gl; - let pot = isPow2(this._width) && isPow2(this._height); - - // WebGL1 doesn't support all wrap modes with NPOT textures - if (!pot && (this._wrapS !== enums.WRAP_CLAMP || this._wrapT !== enums.WRAP_CLAMP)) { - console.warn('WebGL1 doesn\'t support all wrap modes with NPOT textures'); - this._wrapS = enums.WRAP_CLAMP; - this._wrapT = enums.WRAP_CLAMP; - } - - let mipFilter = this._hasMipmap ? this._mipFilter : -1; - if (!pot && mipFilter !== -1) { - console.warn('NPOT textures do not support mipmap filter'); - mipFilter = -1; - } - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilter(gl, this._minFilter, mipFilter)); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilter(gl, this._magFilter, -1)); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT); - - let ext = this._device.ext('EXT_texture_filter_anisotropic'); - if (ext) { - gl.texParameteri(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); - } - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/texture-cube.js b/cocos/renderer/gfx/texture-cube.js deleted file mode 100644 index c5d9f5c6a2..0000000000 --- a/cocos/renderer/gfx/texture-cube.js +++ /dev/null @@ -1,346 +0,0 @@ -import Texture from './texture'; -import { enums, glFilter, glTextureFmt } from './enums'; -import { isPow2 } from './misc'; - -export default class TextureCube extends Texture { - /** - * @constructor - * @param {Device} device - * @param {Object} options - * @param {Array} options.images - * @param {Boolean} options.mipmap - * @param {Number} options.width - * @param {Number} options.height - * @param {TEXTURE_FMT_*} options.format - * @param {Number} options.anisotropy - * @param {FILTER_*} options.minFilter - * @param {FILTER_*} options.magFilter - * @param {FILTER_*} options.mipFilter - * @param {WRAP_*} options.wrapS - * @param {WRAP_*} options.wrapT - * @param {WRAP_*} options.wrapR - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - constructor(device, options) { - super(device); - let gl = this._device._gl; - this._target = gl.TEXTURE_CUBE_MAP; - this._glID = gl.createTexture(); - this.update(options); - } - - /** - * @method update - * @param {Object} options - * @param {Array} options.images - * @param {Boolean} options.mipmap - * @param {Number} options.width - * @param {Number} options.height - * @param {TEXTURE_FMT_*} options.format - * @param {Number} options.anisotropy - * @param {FILTER_*} options.minFilter - * @param {FILTER_*} options.magFilter - * @param {FILTER_*} options.mipFilter - * @param {WRAP_*} options.wrapS - * @param {WRAP_*} options.wrapT - * @param {WRAP_*} options.wrapR - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - update(options) { - let gl = this._device._gl; - let genMipmap = this._hasMipmap; - - if (options) { - if (options.width !== undefined) { - this._width = options.width; - } - if (options.height !== undefined) { - this._height = options.height; - } - if (options.anisotropy !== undefined) { - this._anisotropy = options.anisotropy; - } - if (options.minFilter !== undefined) { - this._minFilter = options.minFilter; - } - if (options.magFilter !== undefined) { - this._magFilter = options.magFilter; - } - if (options.mipFilter !== undefined) { - this._mipFilter = options.mipFilter; - } - if (options.wrapS !== undefined) { - this._wrapS = options.wrapS; - } - if (options.wrapT !== undefined) { - this._wrapT = options.wrapT; - } - // wrapR available in webgl2 - // if (options.wrapR !== undefined) { - // this._wrapR = options.wrapR; - // } - if (options.format !== undefined) { - this._format = options.format; - this._compressed = ( - this._format >= enums.TEXTURE_FMT_RGB_DXT1 && - this._format <= enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1 - ); - } - - // check if generate mipmap - if (options.mipmap !== undefined) { - this._hasMipmap = options.mipmap; - genMipmap = options.mipmap; - } - - if (options.images !== undefined) { - if (options.images.length > 1) { - genMipmap = false; - if (options.width !== options.height) { - console.warn('texture-cube width and height should be identical.'); - } - if (options.width >> (options.images.length - 1) !== 1) { - console.error('texture-cube mipmap is invalid. please set mipmap as 1x1, 2x2, 4x4 ... nxn'); - } - } - } - } - - // NOTE: get pot after this._width, this._height has been assigned. - let pot = isPow2(this._width) && isPow2(this._height); - if (!pot) { - genMipmap = false; - } - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); - if (options.images !== undefined && options.images.length > 0) { - this._setMipmap(options.images, options.flipY, options.premultiplyAlpha); - if (options.images.length > 1) this._hasMipmap = true; - } - if (genMipmap) { - gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST); - gl.generateMipmap(gl.TEXTURE_CUBE_MAP); - this._hasMipmap = true; - } - - this._setTexInfo(); - - this._device._restoreTexture(0); - } - - /** - * @method updateSubImage - * @param {Object} options - * @param {Number} options.x - * @param {Number} options.y - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {Number} options.faceIndex - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateSubImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); - this._setSubImage(glFmt, options); - - this._device._restoreTexture(0); - } - - /** - * @method updateImage - * @param {Object} options - * @param {Number} options.width - * @param {Number} options.height - * @param {Number} options.level - * @param {Number} options.faceIndex - * @param {HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | ArrayBufferView} options.image - * @param {Boolean} options.flipY - * @param {Boolean} options.premultiplyAlpha - */ - updateImage(options) { - let gl = this._device._gl; - let glFmt = glTextureFmt(this._format); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this._glID); - this._setImage(glFmt, options); - this._device._restoreTexture(0); - } - - _setSubImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let faceIndex = options.faceIndex; - let img = options.image; - - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, options.level, options.x, options.y, glFmt.format, glFmt.pixelType, img); - } else { - if (this._compressed) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - img - ); - } else { - gl.texSubImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - options.x, - options.y, - options.width, - options.height, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - _setImage(glFmt, options) { - let gl = this._device._gl; - let flipY = options.flipY; - let premultiplyAlpha = options.premultiplyAlpha; - let faceIndex = options.faceIndex; - let img = options.image; - - if (flipY === undefined) { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); - } - - if (premultiplyAlpha === undefined) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); - } else { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); - } - if ( - img instanceof HTMLCanvasElement || - img instanceof HTMLImageElement || - img instanceof HTMLVideoElement - ) { - gl.texImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - glFmt.internalFormat, - glFmt.format, - glFmt.pixelType, - img - ); - } else { - if (this._compressed) { - gl.compressedTexImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - img - ); - } else { - gl.texImage2D( - gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, - options.level, - glFmt.internalFormat, - options.width, - options.height, - 0, - glFmt.format, - glFmt.pixelType, - img - ); - } - } - } - - // levelImages = [imagePosX, imageNegX, imagePosY, imageNegY, imagePosZ, imageNegz] - // images = [levelImages0, levelImages1, ...] - _setMipmap(images, flipY, premultiplyAlpha) { - let glFmt = glTextureFmt(this._format); - let options = { - width: this._width, - height: this._height, - faceIndex: 0, - flipY: flipY, - premultiplyAlpha: premultiplyAlpha, - level: 0, - image: null - }; - - for (let i = 0; i < images.length; ++i) { - let levelImages = images[i]; - options.level = i; - options.width = this._width >> i; - options.height = this._height >> i; - - for (let face = 0; face < 6; ++face) { - options.faceIndex = face; - options.image = levelImages[face]; - this._setImage(glFmt, options); - } - } - } - - _setTexInfo() { - let gl = this._device._gl; - let pot = isPow2(this._width) && isPow2(this._height); - - // WebGL1 doesn't support all wrap modes with NPOT textures - if (!pot && (this._wrapS !== enums.WRAP_CLAMP || this._wrapT !== enums.WRAP_CLAMP)) { - console.warn('WebGL1 doesn\'t support all wrap modes with NPOT textures'); - this._wrapS = enums.WRAP_CLAMP; - this._wrapT = enums.WRAP_CLAMP; - } - - let mipFilter = this._hasMipmap ? this._mipFilter : -1; - if (!pot && mipFilter !== -1) { - console.warn('NPOT textures do not support mipmap filter'); - mipFilter = -1; - } - - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, glFilter(gl, this._minFilter, mipFilter)); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, glFilter(gl, this._magFilter, -1)); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, this._wrapS); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, this._wrapT); - // wrapR available in webgl2 - // gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_R, this._wrapR); - - let ext = this._device.ext('EXT_texture_filter_anisotropic'); - if (ext) { - gl.texParameteri(gl.TEXTURE_CUBE_MAP, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisotropy); - } - } -} diff --git a/cocos/renderer/gfx/texture.js b/cocos/renderer/gfx/texture.js deleted file mode 100644 index fc26054d4d..0000000000 --- a/cocos/renderer/gfx/texture.js +++ /dev/null @@ -1,52 +0,0 @@ -import { enums } from './enums'; - -/** - * @type {WebGLTexture} - */ -const _nullWebGLTexture = null; - -/** - * @typedef {import("../gfx/device").default} Device - */ - -export default class Texture { - /** - * @param {Device} device - */ - constructor(device) { - this._device = device; - - this._width = 4; - this._height = 4; - this._hasMipmap = false; - this._compressed = false; - - this._anisotropy = 1; - this._minFilter = enums.FILTER_LINEAR; - this._magFilter = enums.FILTER_LINEAR; - this._mipFilter = enums.FILTER_LINEAR; - this._wrapS = enums.WRAP_REPEAT; - this._wrapT = enums.WRAP_REPEAT; - // wrapR available in webgl2 - // this._wrapR = enums.WRAP_REPEAT; - this._format = enums.TEXTURE_FMT_RGBA8; - - this._target = -1; - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === _nullWebGLTexture) { - console.error('The texture already destroyed'); - return; - } - - let gl = this._device._gl; - gl.deleteTexture(this._glID); - - this._device._stats.tex -= this.bytes; - this._glID = _nullWebGLTexture; - } -} \ No newline at end of file diff --git a/cocos/renderer/gfx/vertex-buffer.js b/cocos/renderer/gfx/vertex-buffer.js deleted file mode 100644 index 64f377db79..0000000000 --- a/cocos/renderer/gfx/vertex-buffer.js +++ /dev/null @@ -1,154 +0,0 @@ -import { enums } from './enums'; - -class VertexBuffer { - /** - * @constructor - * @param {Device} device - * @param {VertexFormat} format - * @param {USAGE_*} usage - * @param {ArrayBuffer | Uint8Array} data - * @param {Number} numVertices - */ - constructor(device, format, usage, data, numVertices) { - this._device = device; - this._format = format; - this._usage = usage; - this._numVertices = numVertices; - - // calculate bytes - this._bytes = this._format._bytes * numVertices; - - // update - this._glID = device._gl.createBuffer(); - this.update(0, data); - - // stats - device._stats.vb += this._bytes; - } - - /** - * @method destroy - */ - destroy() { - if (this._glID === -1) { - console.error('The buffer already destroyed'); - return; - } - - let gl = this._device._gl; - gl.deleteBuffer(this._glID); - this._device._stats.vb -= this.bytes; - - this._glID = -1; - } - - /** - * @method update - * @param {Number} offset - * @param {ArrayBuffer} data - */ - update(offset, data) { - if (this._glID === -1) { - console.error('The buffer is destroyed'); - return; - } - - if (data && data.byteLength + offset > this._bytes) { - console.error('Failed to update data, bytes exceed.'); - return; - } - - let gl = this._device._gl; - let glUsage = this._usage; - - gl.bindBuffer(gl.ARRAY_BUFFER, this._glID); - if (!data) { - if (this._bytes) { - gl.bufferData(gl.ARRAY_BUFFER, this._bytes, glUsage); - } else { - console.warn('bufferData should not submit 0 bytes data'); - } - } else { - if (offset) { - gl.bufferSubData(gl.ARRAY_BUFFER, offset, data); - } else { - gl.bufferData(gl.ARRAY_BUFFER, data, glUsage); - } - } - gl.bindBuffer(gl.ARRAY_BUFFER, null); - } - - get count () { - return this._numVertices; - } -} - -if (CC_EDITOR) { - let _typeMap = { - [enums.ATTR_TYPE_INT8]: 'Int8', - [enums.ATTR_TYPE_UINT8]: 'Uint8', - [enums.ATTR_TYPE_INT16]: 'Int16', - [enums.ATTR_TYPE_UINT16]: 'Uint16', - [enums.ATTR_TYPE_INT32]: 'Int32', - [enums.ATTR_TYPE_UINT32]: 'Uint32', - [enums.ATTR_TYPE_FLOAT32]: 'Float32' - }; - let littleEndian = (function() { - let buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256; - })(); - let createAttrCache = function(fmt, data) { - if (!data) return []; - let vcount = data.byteLength / fmt.stride; - let bytes = fmt.bytes / fmt.num; - let fname = `get${_typeMap[fmt.type]}`; - let result = new Array(vcount * fmt.num); - for (let i = 0; i < vcount; i++) { - let offset = i * fmt.stride + fmt.offset; - for (let j = 0; j < fmt.num; j++) - result[i * fmt.num + j] = data[fname](offset + j * bytes, littleEndian); - } - return result; - }; - let writeAttrBack = function(fmt, attrData, data) { - let vcount = attrData.length / fmt.num; - let bytes = fmt.bytes / fmt.num; - let fname =`set${_typeMap[fmt.type]}`; - for (let i = 0; i < vcount; i++) { - let offset = i * fmt.stride + fmt.offset; - for (let j = 0; j < fmt.num; j++) { - data[fname](offset + j * bytes, attrData[i * fmt.num + j], littleEndian); - } - } - }; - VertexBuffer.getAttrAt = function(data, idx, fmt, out = []) { - let offset = idx * fmt.stride + fmt.offset; - let bytes = fmt.bytes / fmt.num; - let fname = `get${_typeMap[fmt.type]}`; - for (let i = 0; i < fmt.num; i++) { - out[i] = data[fname](offset + i * bytes, littleEndian); - } - return out; - }; - VertexBuffer.prototype.do_update = VertexBuffer.prototype.update; - VertexBuffer.prototype.update = function(offset, data) { - this.do_update(offset, data); - // don't need to create for IA pools - if (data && this._bytes !== data.byteLength) return; - if (data instanceof ArrayBuffer) - data = new DataView(data); - else if (ArrayBuffer.isView(data) && !(data instanceof DataView)) - data = new DataView(data.buffer, data.byteOffset, data.byteLength); - this.data = data; this.offset = offset; - this[enums.ATTR_POSITION] = createAttrCache(this._format.element(enums.ATTR_POSITION), data); - }; - VertexBuffer.prototype.updateAttr = function(attr, data) { - if (!data) data = this[attr]; - writeAttrBack(this._format.element(attr), data, this.data); - this.do_update(this.offset, this.data); - }; -} - -export default VertexBuffer; diff --git a/cocos/renderer/gfx/vertex-format.js b/cocos/renderer/gfx/vertex-format.js deleted file mode 100644 index 8f3fc4981a..0000000000 --- a/cocos/renderer/gfx/vertex-format.js +++ /dev/null @@ -1,56 +0,0 @@ -import { attrTypeBytes } from './enums'; - -// ==================== -// exports -// ==================== - -export default class VertexFormat { - /** - * @constructor - * @param {Array} infos - * - * @example - * let vertexFmt = new VertexFormat([ - * { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - * { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, - * { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4, normalize: true }, - * ]) - */ - constructor(infos) { - this._attr2el = {}; - this._elements = []; - this._bytes = 0; - - for (let i = 0, len = infos.length; i < len; ++i) { - let info = infos[i]; - let el = { - name: info.name, - offset: this._bytes, - stride: 0, - stream: -1, - type: info.type, - num: info.num, - normalize: (info.normalize === undefined) ? false : info.normalize, - bytes: info.num * attrTypeBytes(info.type), - }; - - this._attr2el[el.name] = el; - this._elements.push(el); - - this._bytes += el.bytes; - } - - for (let i = 0, len = this._elements.length; i < len; ++i) { - let el = this._elements[i]; - el.stride = this._bytes; - } - } - - /** - * @method element - * @param {string} attrName - */ - element(attrName) { - return this._attr2el[attrName]; - } -} \ No newline at end of file diff --git a/cocos/renderer/index.js b/cocos/renderer/index.ts similarity index 71% rename from cocos/renderer/index.js rename to cocos/renderer/index.ts index ab3d39982a..4a5e1eac1b 100644 --- a/cocos/renderer/index.js +++ b/cocos/renderer/index.ts @@ -1,5 +1,3 @@ -export * from './enums'; - export { createIA } from './utils'; import config from './config'; @@ -9,17 +7,12 @@ export { addStage }; export { RenderQueue, PassStage } from './core/constants'; export { Pass } from './core/pass'; export { Effect } from './core/effect'; -export { default as InputAssembler } from './core/input-assembler'; -export { default as View } from './core/view'; export { Light } from './scene/light'; export { Camera } from './scene/camera'; export { Model } from './scene/model'; -export { default as Scene } from './scene/scene'; export { default as LineBatchModel } from './models/line-batch-model'; export { default as SpriteBatchModel } from './models/sprite-batch-model'; export { default as ParticleBatchModel } from './models/particle-batch-model'; export { default as SkinningModel } from './models/skinning-model'; - -export { default as ForwardRenderer } from './renderers/forward-renderer'; diff --git a/cocos/renderer/models/particle-batch-model.ts b/cocos/renderer/models/particle-batch-model.ts index d56794d8e2..89c6fface4 100644 --- a/cocos/renderer/models/particle-batch-model.ts +++ b/cocos/renderer/models/particle-batch-model.ts @@ -1,7 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import gfx from '../gfx'; - +import { IRenderingSubmesh } from '../../3d/assets/mesh'; import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../gfx/buffer'; import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; @@ -9,7 +8,6 @@ import { IGFXInputAttribute } from '../../gfx/input-assembler'; import { Node } from '../../scene-graph'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; -import { IRenderingSubmesh } from '../../3d/assets/mesh'; export default class ParticleBatchModel extends Model { @@ -130,7 +128,7 @@ export default class ParticleBatchModel extends Model { } public disableStretchedBillboard () { - if (this._vertAttrs!.find((attr) => attr.name === gfx.ATTR_COLOR0) !== undefined) { + if (this._vertAttrs!.find((attr) => attr.name === GFXAttributeName.ATTR_COLOR) !== undefined) { this._vertAttrs!.pop(); this.setVertexAttributes(this._vertAttrs!); } @@ -175,17 +173,17 @@ export default class ParticleBatchModel extends Model { this.getSubModel(0).inputAssembler!.indexCount = 0; } - private destroySubMeshData () { - for (const vb of this._subMeshData!.vertexBuffers) { - vb.destroy(); - } - this._subMeshData!.indexBuffer.destroy(); - } - public destroy () { super.destroy(); this._vdataF32 = null; this.destroySubMeshData(); this._iaInfoBuffer.destroy(); } + + private destroySubMeshData () { + for (const vb of this._subMeshData!.vertexBuffers) { + vb.destroy(); + } + this._subMeshData!.indexBuffer.destroy(); + } } diff --git a/cocos/renderer/renderers/forward-renderer.js b/cocos/renderer/renderers/forward-renderer.js deleted file mode 100644 index 6d5cbb2924..0000000000 --- a/cocos/renderer/renderers/forward-renderer.js +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../gfx'; -import { vec3, mat4 } from '../../core/vmath'; - -import BaseRenderer from '../core/base-renderer'; -import DynamicIAPool from '../core/dynamic-ia-pool'; -import * as enums from '../enums'; -import { PassStage } from '../core/constants'; - -// import GaussianBlur from './gaussian-blur'; - -let _camPos = vec3.create(0, 0, 0); -let _camFwd = vec3.create(0, 0, 0); - -let _a16_view = new Float32Array(16); -let _a16_proj = new Float32Array(16); -let _a16_viewProj = new Float32Array(16); -let _a16_lightViewProj = new Float32Array(16); -let _a3_camPos = new Float32Array(3); - -export default class ForwardRenderer extends BaseRenderer { - constructor(device, builtin) { - super(device, builtin); - this._directionalLights = []; - this._pointLights = []; - this._spotLights = []; - this._shadowLights = []; - this._sceneAmbient = new Float32Array([0.5, 0.5, 0.5]); - - this._registerStage(PassStage.SHADOWCAST, this._shadowStage.bind(this)); - this._registerStage(PassStage.DEFAULT, this._defaultStage.bind(this)); - this._registerStage(PassStage.FORWARD, this._forwardStage.bind(this)); - - this._registerModel('default', this._draw.bind(this)); - this._registerModel('line-batch', this._drawLineBatch.bind(this)); - this._registerModel('sprite-batch', this._drawSpriteBatch.bind(this)); - this._registerModel('particle-batch', this._drawParticleBatch.bind(this)); - this._registerModel('skinning', this._drawSkinning.bind(this)); - - // this._blur = new GaussianBlur(device, this._programLib); - - // lineIAs - this._lineIAs = new DynamicIAPool( - device, 2, - gfx.PT_LINES, - new gfx.VertexFormat([ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 3 } - ]), - 2000 - ); - - // spriteIAs - this._spriteIAs = new DynamicIAPool( - device, 2, - gfx.PT_TRIANGLES, - new gfx.VertexFormat([ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, - { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4 } - ]), - 2000, - gfx.INDEX_FMT_UINT16, - 2000 - ); - } - - updateLights(scene) { - this._directionalLights.length = 0; - this._pointLights.length = 0; - this._spotLights.length = 0; - this._shadowLights.length = 0; - let lights = scene._lights; - for (let i = 0; i < lights.length; ++i) { - let light = lights.data[i]; - light.update(this._device); - if (light.shadowType !== enums.SHADOW_NONE) { - this._shadowLights.push(light); - let view = this._requestView(); - light.extractView(view, PassStage.SHADOWCAST); - } - if (light._type === enums.LIGHT_DIRECTIONAL) { - this._directionalLights.push(light); - } else if (light._type === enums.LIGHT_POINT) { - this._pointLights.push(light); - } else { - this._spotLights.push(light); - } - } - } - - render(scene) { - this._reset(); - - const canvas = this._device._gl.canvas; - - // update lights, extract shadow view. - this.updateLights(scene); - - // extract views from cameras, lights and so on - if (scene._debugCamera) { - let view = this._requestView(); - scene._debugCamera.extractView(view, canvas.width, canvas.height); - } else { - for (let i = 0; i < scene._cameras.length; ++i) { - let view = this._requestView(); - scene._cameras.data[i].extractView(view, canvas.width, canvas.height); - } - } - - // render by cameras - this._viewPools.sort((a, b) => { - return (a._priority - b._priority); - }); - scene._views.sort((a, b) => { - return (a._priority - b._priority); - }); - for (let i = 0; i < this._viewPools.length; ++i) { - let view = this._viewPools.data[i]; - this._render(view, scene); - } - - // render by views (ui) - for (let i = 0; i < scene._views.length; ++i) { - let view = scene._views[i]; - this._render(view, scene); - } - } - - _submitLightUniforms() { - this._device.setUniform('_sceneAmbient', this._sceneAmbient); - - if (this._directionalLights.length > 0) { - for (let index = 0; index < this._directionalLights.length; ++index) { - let light = this._directionalLights[index]; - this._device.setUniform(`_dir_light${index}_direction`, light._directionUniform); - this._device.setUniform(`_dir_light${index}_color`, light._colorUniform); - } - } - if (this._pointLights.length > 0) { - for (let index = 0; index < this._pointLights.length; ++index) { - let light = this._pointLights[index]; - this._device.setUniform(`_point_light${index}_position`, light._positionUniform); - this._device.setUniform(`_point_light${index}_color`, light._colorUniform); - this._device.setUniform(`_point_light${index}_range`, light._range); - } - } - - if (this._spotLights.length > 0) { - for (let index = 0; index < this._spotLights.length; ++index) { - let light = this._spotLights[index]; - this._device.setUniform(`_spot_light${index}_position`, light._positionUniform); - this._device.setUniform(`_spot_light${index}_direction`, light._directionUniform); - this._device.setUniform(`_spot_light${index}_color`, light._colorUniform); - this._device.setUniform(`_spot_light${index}_range`, light._range); - this._device.setUniform(`_spot_light${index}_spot`, light._spotUniform); - } - } - } - - _submitShadowStageUniforms(view) { - let light = view._shadowLight; - this._device.setUniform('_minDepth', light.shadowMinDepth); - this._device.setUniform('_maxDepth', light.shadowMaxDepth); - this._device.setUniform('_bias', light.shadowBias); - this._device.setUniform('_depthScale', light.shadowDepthScale); - } - - _submitOtherStagesUniforms() { - for (let index = 0; index < this._shadowLights.length; ++index) { - let light = this._shadowLights[index]; - this._device.setUniform(`_lightViewProjMatrix_${index}`, mat4.array(_a16_lightViewProj, light.viewProjMatrix)); - this._device.setUniform(`_minDepth_${index}`, light.shadowMinDepth); - this._device.setUniform(`_maxDepth_${index}`, light.shadowMaxDepth); - this._device.setUniform(`_bias_${index}`, light.shadowBias); - this._device.setUniform(`_depthScale_${index}`, light.shadowDepthScale); - this._device.setUniform(`_darkness_${index}`, light.shadowDarkness); - this._device.setUniform(`_frustumEdgeFalloff_${index}`, light.frustumEdgeFalloff); - this._device.setUniform(`_texelSize_${index}`, new Float32Array([1.0 / light.shadowResolution, 1.0 / light.shadowResolution])); - } - } - - _updateShaderDefines(item) { - // for (let i = 0; i < items.length; ++i) { - // let item = items.data[i]; - let defines = item.defines; - - defines['_NUM_DIR_LIGHTS'] = Math.min(4, this._directionalLights.length); - defines['_NUM_POINT_LIGHTS'] = Math.min(4, this._pointLights.length); - defines['_NUM_SPOT_LIGHTS'] = Math.min(4, this._spotLights.length); - - defines['_NUM_SHADOW_LIGHTS'] = Math.min(4, this._shadowLights.length); - // } - } - - _shadowStage(item) { - this._device.setUniform('_lightViewProjMatrix', mat4.array(_a16_viewProj, this._currentView._matViewProj)); - - // update rendering - // this._submitLightUniforms(); - this._submitShadowStageUniforms(this._currentView); - this._updateShaderDefines(item); - - - // draw it - - if (item.model._castShadow) { - this._drawPass(item); - } - - } - - _defaultStage(item) { - this._drawPass(item); - } - - _forwardStage(item) { - - // update rendering - this._submitLightUniforms(); - this._submitOtherStagesUniforms(); - this._updateShaderDefines(item); - - - for (let index = 0; index < this._shadowLights.length; ++index) { - let light = this._shadowLights[index]; - this._device.setTexture(`_shadowMap_${index}`, light.shadowMap, this._allocTextureUnit()); - } - - this._drawPass(item); - } - - - - _drawSkinning(item) { - let { model, defines } = item; - - defines['_USE_SKINNING'] = true; - if (model._jointsTexture != null) { - defines['_USE_JOINTS_TEXTURE'] = true; - this._device.setTexture('_u_jointsTexture', model._jointsTexture, this._allocTextureUnit()); - this._device.setUniform('_u_jointsTextureSize', model._jointsTexture._width); - } else if (model._jointsMatrixArray != null) { - defines['_USE_JOINTS_TEXTURE'] = false; - this._device.setUniform("_u_jointMatrices", model._jointsMatrixArray); - } - - this._draw(item); - } - - _drawLineBatch(item) { - let model = item.model; - let curVertCount = 0; - let vdata = this._lineIAs.requestVData(model.vertCount); - let vdataF32 = vdata.float32View; - - for (let i = model.lineCount - 1; i >= 0; --i) { - let line = model.getLine(i); - - // flush when verts exceeds - if (curVertCount + 2 >= this._lineIAs.maxVerts) { - let ia = this._lineIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._start = 0; - ia._count = curVertCount; - - item.ia = ia; - this._draw(item); - curVertCount = 0; - } - - // - let idx = curVertCount * 6; - vdataF32[idx] = line.start.x; - vdataF32[idx + 1] = line.start.y; - vdataF32[idx + 2] = line.start.z; - vdataF32[idx + 3] = line.color.r; - vdataF32[idx + 4] = line.color.g; - vdataF32[idx + 5] = line.color.b; - - vdataF32[idx + 6] = line.end.x; - vdataF32[idx + 7] = line.end.y; - vdataF32[idx + 8] = line.end.z; - vdataF32[idx + 9] = line.color.r; - vdataF32[idx + 10] = line.color.g; - vdataF32[idx + 11] = line.color.b; - - curVertCount += 2; - } - - // flush rest verts - if (curVertCount > 0) { - let ia = this._lineIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._start = 0; - ia._count = curVertCount; - - item.ia = ia; - this._draw(item); - } - } - - _drawSpriteBatch(item) { - let model = item.model; - let curVertOffset = 0; - let curVertCount = 0; - let curIndexCount = 0; - let vdata = this._spriteIAs.requestVData(model.vertCount); - let idata = this._spriteIAs.requestIData(model.indexCount); - let vdataF32 = vdata.float32View; - let idataU16 = idata.uint16View; - - for (let i = 0; i < model.spriteCount; ++i) { - let sprite = model.getSprite(i); - let vcount = sprite.refPositions.length; - let icount = sprite.refIndices.length; - - // flush when verts exceeds - if ( - curVertCount + vcount >= this._spriteIAs.maxVerts || - curIndexCount + icount >= this._spriteIAs.maxIndices - ) { - let ia = this._spriteIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._indexBuffer.update(0, idataU16); - - ia._start = 0; - ia._count = curIndexCount; - - item.ia = ia; - this._draw(item); - - curVertOffset = 0; - curVertCount = 0; - curIndexCount = 0; - } - - // - for (let j = 0; j < vcount; ++j) { - let idx = curVertCount * 9; - - vdataF32[idx] = sprite.refPositions[j].x; - vdataF32[idx + 1] = sprite.refPositions[j].y; - vdataF32[idx + 2] = sprite.refPositions[j].z; - vdataF32[idx + 3] = sprite.refUVs[j].x; - vdataF32[idx + 4] = sprite.refUVs[j].y; - vdataF32[idx + 5] = sprite.refColor.r; - vdataF32[idx + 6] = sprite.refColor.g; - vdataF32[idx + 7] = sprite.refColor.b; - vdataF32[idx + 8] = sprite.refColor.a; - - curVertCount += 1; - } - - for (let j = 0; j < icount; ++j) { - let idx = curIndexCount; - - idataU16[idx] = curVertOffset + sprite.refIndices[j]; - - curIndexCount += 1; - } - - curVertOffset += vcount; - } - - // flush rest verts & indices - if (curIndexCount > 0) { - let ia = this._spriteIAs.requestIA(); - ia._vertexBuffer.update(0, vdataF32); - ia._indexBuffer.update(0, idataU16); - ia._start = 0; - ia._count = curIndexCount; - - item.ia = ia; - this._draw(item); - } - } - - _drawParticleBatch(item) { - item.ia = item.model._ia; - if (item.model._renderer) { - item.model._renderer.updateShaderUniform(); - } - this._draw(item); - } -} diff --git a/cocos/renderer/renderers/gaussian-blur.js b/cocos/renderer/renderers/gaussian-blur.js deleted file mode 100644 index 251d8d93ea..0000000000 --- a/cocos/renderer/renderers/gaussian-blur.js +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import gfx from '../../gfx'; - -export default class GaussianBlur { - constructor(device, proglib) { - this._device = device; - this._width = 1024; - this._height = 1024; - this._XBlurFrameBuffer = null; - this._XBluredTexture = null; - this._YBlurFrameBuffer = null; - this._YBluredTexture = null; - this._sourceTexture = null; - this._programLib = proglib; - } - - setupBlur(tex) { - this._sourceTexture = tex; - this._width = tex._width; - this._height = tex._height; - if (!this._XBlurFrameBuffer || !this._YBlurFrameBuffer) { - this._XBluredTexture = new gfx.Texture2D(this._device, { - width: this._width, - height: this._height, - format: gfx.TEXTURE_FMT_RGBA8, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - }); - this._XBlurFrameBuffer = new gfx.FrameBuffer(this._device, this._width, this._height, { - colors: [this._XBluredTexture], - }); - this._YBluredTexture = new gfx.Texture2D(this._device, { - width: this._width, - height: this._height, - format: gfx.TEXTURE_FMT_RGBA8, - wrapS: gfx.WRAP_CLAMP, - wrapT: gfx.WRAP_CLAMP, - }); - this._YBlurFrameBuffer = new gfx.FrameBuffer(this._device, this._width, this._height, { - colors: [this._YBluredTexture], - }); - } - } - - processBlur() { - // position.xy uv - let verts = [ - -1, 1, 0, 1, - -1, -1, 0, 0, - 1, -1, 1, 0, - -1, 1, 0, 1, - 1, -1, 1, 0, - 1, 1, 1, 1 - ]; - let vfmt = [ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, - { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 } - ]; - let vb = new gfx.VertexBuffer( - this._device, - new gfx.VertexFormat(vfmt), - gfx.USAGE_STATIC, - new Float32Array(verts), - 6 - ); - // x-blur - this._device.setFrameBuffer(this._XBlurFrameBuffer); - this._device.setViewport(0, 0, this._width, this._height); - this._device.clear({ - color: [0, 0, 0, 1] - }); - this._device.setTexture('texture', this._sourceTexture, 0); - this._device.setUniform('pixelSize',new Float32Array([1.0 / this._width, 0.0])); - this._device.setVertexBuffer(0, vb); - this._device.setProgram(this._programLib.getProgram('gaussian-blur')); - this._device.draw(0, 6); - // y-blur - this._device.setFrameBuffer(this._YBlurFrameBuffer); - this._device.clear({ - color: [0, 0, 0, 1] - }); - this._device.setTexture('texture', this._XBluredTexture, 0); - this._device.setUniform('pixelSize',new Float32Array([0.0, 1.0 / this._height])); - this._device.setVertexBuffer(0, vb); - this._device.setProgram(this._programLib.getProgram('gaussian-blur')); - this._device.draw(0, 6); - this._device.setFrameBuffer(null); - } - - getBluredTexture() { - // TODO: should support only x-blur or y-blur ? - return this._YBluredTexture; - } - -} \ No newline at end of file diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index e0a9a781e7..4986fb4eea 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -142,11 +142,11 @@ export class Model { this._worldBounds = aabb.clone(this._modelBounds); } - public enable (isEnable: boolean) { + set enabled (isEnable) { this._isEnable = isEnable; } - public isEnable () { + get enabled () { return this._isEnable; } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index f6e842d5d2..73e16820a5 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -5,6 +5,7 @@ import { Root } from '../../core/root'; import { Mat4, Vec3 } from '../../core/value-types'; import { mat4, vec3 } from '../../core/vmath'; import { GFXPrimitiveMode } from '../../gfx/define'; +import { Node } from '../../scene-graph'; import { Layers } from '../../scene-graph/layers'; import { Camera, ICameraInfo } from './camera'; import { Light, LightType } from './light'; @@ -122,7 +123,7 @@ export class RenderScene { this._pointLights = []; } - public createModel (clazz: new (s: RenderScene, n: Node) => T, node: Node): T { + public createModel (clazz: new (scene: RenderScene, node: Node) => T, node: Node): T { const model = new clazz(this, node); this._models.push(model); return model; @@ -158,7 +159,7 @@ export class RenderScene { pool.reset(); for (const m of this._models) { const node = m.node; - if (!node.activeInHierarchy || !cc.Layers.check(node.layer, mask) || !m.modelBounds) { continue; } + if (!m.enabled || !cc.Layers.check(node.layer, mask) || !m.modelBounds) { continue; } // transform ray back to model space mat4.invert(m4, node.getWorldMatrix(m4)); vec3.transformMat4(modelRay.o, worldRay.o, m4); diff --git a/cocos/renderer/scene/scene.js b/cocos/renderer/scene/scene.js deleted file mode 100644 index 444603f306..0000000000 --- a/cocos/renderer/scene/scene.js +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { FixedArray, RecyclePool } from '../../3d/memop'; -import { ray, triangle, intersect } from '../../3d/geom-utils'; -import { Layers } from '../../scene-graph/layers'; -import { vec3, mat4 } from '../../core/vmath'; -import gfx from '../../renderer/gfx'; - -/** - * A representation of the scene - */ -class Scene { - /** - * Setup a default empty scene - */ - constructor() { - this._lights = new FixedArray(16); - this._models = new FixedArray(16); - this._cameras = new FixedArray(16); - this._debugCamera = null; - - // NOTE: we don't use pool for views (because it's less changed and it doesn't have poolID) - this._views = []; - } - - _add(pool, item) { - if (item._poolID !== -1) { - return; - } - - pool.push(item); - item._poolID = pool.length - 1; - } - - _remove(pool, item) { - if (item._poolID === -1) { - return; - } - - pool.data[pool.length-1]._poolID = item._poolID; - pool.fastRemove(item._poolID); - item._poolID = -1; - } - - /** - * update built-in bounding shapes if needed, - * used in the frustum culling process - */ - tick() { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models.data[i]; - model._updateTransform(); - } - } - - /** - * reset the model viewIDs - */ - reset() { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models.data[i]; - model._viewID = -1; - } - } - - /** - * Set the debug camera - * @param {Camera} cam the debug camera - */ - setDebugCamera(cam) { - this._debugCamera = cam; - } - - /** - * Get the debug camera - */ - getDebugCamera() { - return this._debugCamera; - } - - /** - * Get the count of registered cameras - * @returns {number} camera count - */ - getCameraCount() { - return this._cameras.length; - } - - /** - * Get the specified camera - * @param {number} idx camera index - * @returns {Camera} the specified camera - */ - getCamera(idx) { - return this._cameras.data[idx]; - } - - /** - * register a camera - * @param {Camera} camera the new camera - */ - addCamera(camera) { - this._add(this._cameras, camera); - } - - /** - * remove a camera - * @param {Camera} camera the camera to be removed - */ - removeCamera(camera) { - this._remove(this._cameras, camera); - } - - /** - * Get the count of registered model - * @returns {number} model count - */ - getModelCount() { - return this._models.length; - } - - /** - * Get the specified model - * @param {number} idx model index - * @returns {Model} the specified model - */ - getModel(idx) { - return this._models.data[idx]; - } - - /** - * register a model - * @param {Model} model the new model - */ - addModel(model) { - this._add(this._models, model); - } - - /** - * remove a model - * @param {Model} model the model to be removed - */ - removeModel(model) { - this._remove(this._models, model); - } - - /** - * Get the count of registered light - * @returns {number} light count - */ - getLightCount() { - return this._lights.length; - } - - /** - * Get the specified light - * @param {number} idx light index - * @returns {Light} the specified light - */ - getLight(idx) { - return this._lights.data[idx]; - } - - /** - * register a light - * @param {Light} light the new light - */ - addLight(light) { - this._add(this._lights, light); - } - - /** - * remove a light - * @param {Light} light the light to be removed - */ - removeLight(light) { - this._remove(this._lights, light); - } - - /** - * register a view - * @param {View} view the new view - */ - addView(view) { - if (this._views.indexOf(view) === -1) { - this._views.push(view); - } - } - - /** - * remove a view - * @param {View} view the view to be removed - */ - removeView(view) { - let idx = this._views.indexOf(view); - if (idx !== -1) { - this._views.splice(idx, 1); - } - } -} - -export default Scene; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 2e51e75b05..af29d13b4b 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -25,11 +25,7 @@ import { BaseNode } from '../../scene-graph/base-node'; import { Pass } from '../core/pass'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; -<<<<<<< HEAD -import { IUIMaterialInfo, UIMaterial } from './ui-material'; -======= import { SpriteFrame } from '../../assets/CCSpriteFrame'; ->>>>>>> 86462dac... add texture to IUIRenderData export interface IUIBufferBatch { vb: GFXBuffer; diff --git a/playground/gizmo.html b/playground/gizmo.html index 399c4d44be..e85417c61f 100644 --- a/playground/gizmo.html +++ b/playground/gizmo.html @@ -117,11 +117,11 @@ const moveTool = new cc.Node('moveTool'); moveTool.parent = scene; createArrow(cc.Color.RED, quat.fromEuler(cc.quat(), 90, 0, 0)).parent = moveTool; - // createArrow(cc.Color.GREEN, quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; - // createArrow(cc.Color.BLUE, quat.fromEuler(cc.quat(), 0, 0, -90)).parent = moveTool; - // createBorderPlane(cc.Color.RED, cc.v3(0.5, 0.5, 0), quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; - // createBorderPlane(cc.Color.GREEN, cc.v3(0.5, 0, 0.5), quat.fromEuler(cc.quat(), -90, -90, 0)).parent = moveTool; - // createBorderPlane(cc.Color.BLUE, cc.v3(0, 0.5, 0.5), quat.fromEuler(cc.quat(), 90, 0, 90)).parent = moveTool; + createArrow(cc.Color.GREEN, quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; + createArrow(cc.Color.BLUE, quat.fromEuler(cc.quat(), 0, 0, -90)).parent = moveTool; + createBorderPlane(cc.Color.RED, cc.v3(0.5, 0.5, 0), quat.fromEuler(cc.quat(), 0, 0, 0)).parent = moveTool; + createBorderPlane(cc.Color.GREEN, cc.v3(0.5, 0, 0.5), quat.fromEuler(cc.quat(), -90, -90, 0)).parent = moveTool; + createBorderPlane(cc.Color.BLUE, cc.v3(0, 0.5, 0.5), quat.fromEuler(cc.quat(), 90, 0, 90)).parent = moveTool; let vel = cc.v3(), speed = 0.1; canv.addEventListener('keydown', (e) => { From bf1a736a6de189ca3a8ca14167bb9d81226c035e Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 10:42:35 +0800 Subject: [PATCH 220/267] add resize buffer function --- cocos/gfx/buffer.ts | 6 ++ cocos/gfx/webgl/webgl-buffer.ts | 12 ++++ cocos/gfx/webgl/webgl-commands.ts | 41 ++++++++++++ cocos/gfx/webgl/webgl-device.ts | 34 +++++++--- cocos/renderer/ui/renderData.ts | 4 +- cocos/renderer/ui/ui.ts | 104 +++++++++++++++++++++--------- 6 files changed, 158 insertions(+), 43 deletions(-) diff --git a/cocos/gfx/buffer.ts b/cocos/gfx/buffer.ts index 2315a74ef5..13fcec273b 100644 --- a/cocos/gfx/buffer.ts +++ b/cocos/gfx/buffer.ts @@ -58,6 +58,10 @@ export abstract class GFXBuffer extends GFXObject { return this._stride; } + public get count (): number { + return this._count; + } + public get buffer (): GFXBufferSource | null { return this._buffer; } @@ -67,6 +71,7 @@ export abstract class GFXBuffer extends GFXObject { protected _memUsage: GFXMemoryUsage = GFXMemoryUsageBit.NONE; protected _size: number = 0; protected _stride: number = 1; + protected _count: number = 0; protected _buffer: GFXBufferSource | null = null; protected _uniforms: GFXBufferSource | null = null; @@ -77,5 +82,6 @@ export abstract class GFXBuffer extends GFXObject { public abstract initialize (info: IGFXBufferInfo): boolean; public abstract destroy (): void; + public abstract resize (size: number); public abstract update (buffer: GFXBufferSource, offset?: number, size?: number); } diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index f7cb4595b3..fe9fbac9e1 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -30,6 +30,7 @@ export class WebGLGFXBuffer extends GFXBuffer { this._stride = info.stride; } this._stride = Math.max(this._stride, 1); + this._count = this._size / this._stride; if (this._memUsage & GFXMemoryUsageBit.HOST) { if (this._usage & GFXBufferUsageBit.INDIRECT) { @@ -56,6 +57,17 @@ export class WebGLGFXBuffer extends GFXBuffer { this._status = GFXStatus.UNREADY; } + public resize (size: number) { + + if (this._memUsage & GFXMemoryUsageBit.HOST) { + if ((this._usage & GFXBufferUsageBit.INDIRECT) === GFXBufferUsageBit.NONE) { + this._buffer = new ArrayBuffer(this._size); + } + } + + this.webGLDevice.emitCmdResizeGPUBuffer(this._gpuBuffer!, this._buffer); + } + public update (buffer: GFXBufferSource, offset?: number, size?: number) { // const isUniformBuffer = (this._usage & GFXBufferUsageBit.UNIFORM) !== GFXBufferUsageBit.NONE; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index d917cdf370..2d6d886825 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -592,6 +592,47 @@ export function WebGLCmdFuncDestroyBuffer (device: WebGLGFXDevice, gpuBuffer: We } } +export function WebGLCmdFuncResizeBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer) { + + const gl = device.gl; + + if (gpuBuffer.usage & GFXBufferUsageBit.VERTEX) { + + if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.glBuffer); + } + + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, null); + device.stateCache.glArrayBuffer = 0; + } else if (gpuBuffer.usage & GFXBufferUsageBit.INDEX) { + + if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) { + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer); + } + + const glUsage: GLenum = gpuBuffer.memUsage & GFXMemoryUsageBit.DEVICE ? WebGLRenderingContext.STATIC_DRAW : WebGLRenderingContext.DYNAMIC_DRAW; + gl.bufferData(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage); + + gl.bindBuffer(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER, null); + device.stateCache.glElementArrayBuffer = 0; + } else if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { + // console.error("WebGL 1.0 doesn't support uniform buffer."); + if (gpuBuffer.buffer) { + gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer as ArrayBuffer); + } + } else if ((gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) || + (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_DST) || + (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC)) { + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } else { + console.error('Unsupported GFXBufferType, create buffer failed.'); + gpuBuffer.glTarget = WebGLRenderingContext.NONE; + } +} + export function WebGLCmdFuncUpdateBuffer (device: WebGLGFXDevice, gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { if (gpuBuffer.usage & GFXBufferUsageBit.UNIFORM) { diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index fc56e5b707..07d0e3df5b 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -42,6 +42,7 @@ import { WebGLCmdFuncDestroyFramebuffer, WebGLCmdFuncDestroyShader, WebGLCmdFuncDestroyTexture, + WebGLCmdFuncResizeBuffer, WebGLCmdFuncUpdateBuffer, } from './webgl-commands'; import { WebGLGFXFramebuffer } from './webgl-framebuffer'; @@ -505,7 +506,7 @@ export class WebGLGFXDevice extends GFXDevice { public copyBufferToTexture (buffer: ArrayBuffer, texture: GFXTexture, regions: GFXBufferTextureCopy[]) { WebGLCmdFuncCopyBufferToTexture( - this as WebGLGFXDevice, + this, buffer, (texture as WebGLGFXTexture).gpuTexture, regions); @@ -523,7 +524,7 @@ export class WebGLGFXDevice extends GFXDevice { const imgData = context.getImageData(0, 0, this._canvas2D.width, this._canvas2D.height); WebGLCmdFuncCopyBufferToTexture( - this as WebGLGFXDevice, + this, imgData.data, (texture as WebGLGFXTexture).gpuTexture, regions); @@ -603,14 +604,27 @@ export class WebGLGFXDevice extends GFXDevice { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncDestroyBuffer(this as WebGLGFXDevice, gpuBuffer); + WebGLCmdFuncDestroyBuffer(this, gpuBuffer); + } + + public emitCmdResizeGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource | null) { + + if (buffer) { + if ((gpuBuffer.usage & GFXBufferUsageBit.INDIRECT) === GFXBufferUsageBit.NONE) { + gpuBuffer.buffer = buffer as ArrayBuffer; + gpuBuffer.size = gpuBuffer.buffer.byteLength; + } + } + + // TODO: Async + WebGLCmdFuncResizeBuffer(this, gpuBuffer); } public emitCmdUpdateGPUBuffer (gpuBuffer: WebGLGPUBuffer, buffer: GFXBufferSource, offset: number, size: number) { // TODO: Async const isStagingBuffer = (gpuBuffer.usage & GFXBufferUsageBit.TRANSFER_SRC) !== GFXBufferUsageBit.NONE; if (!isStagingBuffer) { - WebGLCmdFuncUpdateBuffer(this as WebGLGFXDevice, gpuBuffer, buffer, offset, size); + WebGLCmdFuncUpdateBuffer(this, gpuBuffer, buffer, offset, size); } } @@ -681,7 +695,7 @@ export class WebGLGFXDevice extends GFXDevice { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.CREATE_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncCreateTexture(this as WebGLGFXDevice, gpuTexture); + WebGLCmdFuncCreateTexture(this, gpuTexture); return gpuTexture; } @@ -690,7 +704,7 @@ export class WebGLGFXDevice extends GFXDevice { // TODO: Async // let cmd : WebGLCmd = { type : WebGLCmdType.DESTROY_BUFFER, gpuObj : gpuBuffer, isFree : false }; - WebGLCmdFuncDestroyTexture(this as WebGLGFXDevice, gpuTexture); + WebGLCmdFuncDestroyTexture(this, gpuTexture); } public emitCmdCreateGPUTextureView (info: IGFXTextureViewInfo): WebGLGPUTextureView { @@ -756,7 +770,7 @@ export class WebGLGFXDevice extends GFXDevice { }; // TODO: Async - WebGLCmdFuncCreateFramebuffer(this as WebGLGFXDevice, gpuFramebuffer); + WebGLCmdFuncCreateFramebuffer(this, gpuFramebuffer); return gpuFramebuffer; @@ -777,7 +791,7 @@ export class WebGLGFXDevice extends GFXDevice { public emitCmdDestroyGPUFramebuffer (gpuFramebuffer: WebGLGPUFramebuffer) { if (gpuFramebuffer.isOffscreen) { // TODO: Async - WebGLCmdFuncDestroyFramebuffer(this as WebGLGFXDevice, gpuFramebuffer); + WebGLCmdFuncDestroyFramebuffer(this, gpuFramebuffer); } } @@ -864,14 +878,14 @@ export class WebGLGFXDevice extends GFXDevice { }; // TODO: Async - WebGLCmdFuncCreateShader(this as WebGLGFXDevice, gpuShader); + WebGLCmdFuncCreateShader(this, gpuShader); return gpuShader; } public emitCmdDestroyGPUShader (gpuShader: WebGLGPUShader) { // TODO: Async - WebGLCmdFuncDestroyShader(this as WebGLGFXDevice, gpuShader); + WebGLCmdFuncDestroyShader(this, gpuShader); } public emitCmdCreateGPUPipelineState (info: IGFXPipelineStateInfo): WebGLGPUPipelineState { diff --git a/cocos/renderer/ui/renderData.ts b/cocos/renderer/ui/renderData.ts index 8061eb194f..54a276b740 100644 --- a/cocos/renderer/ui/renderData.ts +++ b/cocos/renderer/ui/renderData.ts @@ -34,7 +34,7 @@ export class RenderData extends BaseRenderData { data[i] = _dataPool.add(); } for (i = value; i > length; i--) { - _dataPool.remove(i); + _dataPool.removeAt(i); data.splice(i, 1); } } @@ -54,7 +54,7 @@ export class RenderData extends BaseRenderData { public static remove (idx: number) { _pool.data[idx].clear(); - _pool.remove(idx); + _pool.removeAt(idx); } public uvDirty: boolean = true; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index af29d13b4b..8138aaf811 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -7,7 +7,7 @@ import { IMeshBufferInitData, MeshBuffer } from '../../3d/ui/mesh-buffer'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; import { GFXBindingLayout } from '../../gfx/binding-layout'; -import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXBufferUsageBit, @@ -18,25 +18,23 @@ import { } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; -import { GFXPipelineLayout } from '../../gfx/pipeline-layout'; -import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { GFXTexture } from '../../gfx/texture'; import { vfmt } from '../../gfx/vertex-format-sample'; import { BaseNode } from '../../scene-graph/base-node'; -import { Pass } from '../core/pass'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; import { SpriteFrame } from '../../assets/CCSpriteFrame'; -export interface IUIBufferBatch { - vb: GFXBuffer; - ib: GFXBuffer; - ia: GFXInputAssembler; +export class UIBufferBatch { + public vb: GFXBuffer | null = null; + public ib: GFXBuffer | null = null; + public ia: GFXInputAssembler | null = null; } -export interface IUIRenderItem { - camera: Camera; - bufferBatch: IUIBufferBatch; - uiMaterial: UIMaterial; +export class UIDrawBatch { + public camera: Camera | null = null; + public bufferBatch: UIBufferBatch | null = null; + public uiMaterial: UIMaterial | null = null; } export interface IUIRenderData { @@ -55,15 +53,21 @@ export class UI { private _bufferPool: RecyclePool = new RecyclePool(() => { return new MeshBuffer(); }, 128); + private _bufferBatchPool: RecyclePool = new RecyclePool(() => { + return new UIBufferBatch(); + }, 128); + private _drawBatchPool: RecyclePool = new RecyclePool(() => { + return new UIDrawBatch(); + }, 128); private _device: GFXDevice; private _cmdBuff: GFXCommandBuffer | null = null; private _renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; private _scene: RenderScene; private _attributes: IGFXInputAttribute[] = []; - private _bufferBatches: IUIBufferBatch[] = []; + private _bufferBatches: UIBufferBatch[] = []; private _uiMaterial: UIMaterial | null = null; private _uiMaterials: UIMaterial[] = []; - private _items: CachedArray; + private _batches: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; @@ -73,7 +77,7 @@ export class UI { name: 'GUIScene', }); - this._items = new CachedArray(64); + this._batches = new CachedArray(64); this._bufferInitData = { vertexCount: 0, indiceCount: 0, @@ -97,15 +101,12 @@ export class UI { }); // create ui material - - /* const material = new Material(); material.effectName = 'sprite-material'; // material.setProperty('mainTexture', texture); material.update(); this._uiMaterial = this.createUIMaterial( { material }); - */ return true; } @@ -114,8 +115,9 @@ export class UI { this.destroyUIMaterials(); for (const buffBatch of this._bufferBatches) { - buffBatch.vb.destroy(); - buffBatch.ib.destroy(); + buffBatch.vb!.destroy(); + buffBatch.ib!.destroy(); + buffBatch.ia!.destroy(); } this._bufferBatches = []; @@ -192,36 +194,73 @@ export class UI { } public update (dt: number) { - this._items.clear(); + this._batches.clear(); this._renderScreens(); - // TODO: Merge batch here. + // Merge batch + /* let curCamera: Camera | null = null; + let curTexture: GFXTexture | null = null; + let curBufferBatch: UIBufferBatch = this._bufferBatches[0]; + let vbOffset = 0; for (const uiRenderData of this._commitUIRenderDatas) { + if (curCamera === uiRenderData.camera && + curTexture === uiRenderData.texture.getGFXTexture()) { + + if (curBufferBatch.ib!.count + uiRenderData.meshBuffer.iData!.length < 65535) { + + const vf32: Float32Array = uiRenderData.meshBuffer.vData!; + const vbSize = uiRenderData.meshBuffer.vData!.length * 4 + vbOffset; + if (vbSize > curBufferBatch.vb!.size) { + curBufferBatch.vb!.resize(vbSize); + } + + curBufferBatch.vb!.update(vf32, vbOffset, vf32.length * 4); + vbOffset += vf32.length; + } + } + if (curCamera !== uiRenderData.camera) { + + if (curBufferBatch) { + + if (curBufferBatch.ib!.count + uiRenderData.meshBuffer.iData!.length > 65535) { + + } + } + curCamera = uiRenderData.camera; + curTexture = uiRenderData.texture.getGFXTexture(); + curBufferBatch = this._drawBatchPool.add(); + + continue; + } + + if (curTexture !== uiRenderData.texture.getGFXTexture()) { + curTexture = uiRenderData.texture.getGFXTexture(); } // uiRenderData.meshBuffer.iData.length; } + */ } public render () { const material = this._uiMaterial!; - if (this._items.length) { + if (this._batches.length) { const framebuffer = this._root.curWindow!.framebuffer; const cmdBuff = this._cmdBuff!; cmdBuff.begin(); - for (let i = 0; i < this._items.length; ++i) { - const item = this._items.array[i]; - const camera = item.camera; + for (let i = 0; i < this._batches.length; ++i) { + const batch = this._batches.array[i]; + const camera = batch.camera!; this._renderArea.width = camera.width; this._renderArea.height = camera.height; @@ -229,8 +268,8 @@ export class UI { cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); cmdBuff.bindPipelineState(material.pipelineState); cmdBuff.bindBindingLayout(material.bindingLayout); - // cmdBuff.bindInputAssembler(item.meshBuffer.indiceOffset); - // cmdBuff.draw(item.inputAssembler); + cmdBuff.bindInputAssembler(batch.bufferBatch!.ia!); + cmdBuff.draw(batch.bufferBatch!.ia!); cmdBuff.endRenderPass(); } @@ -294,9 +333,9 @@ export class UI { comp.postUpdateAssembler(); } - private createBufferBatch (): IUIBufferBatch { + private createBufferBatch (): UIBufferBatch { - const vbStride = Float32Array.BYTES_PER_ELEMENT * 6; + const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; const vb = this._device.createBuffer({ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, @@ -320,7 +359,10 @@ export class UI { indexBuffer: ib, }); - const batch: IUIBufferBatch = { vb, ib, ia }; + const batch = this._bufferBatchPool.add(); + batch.vb = vb; + batch.ib = ib; + batch.ia = ia; this._bufferBatches.push(batch); return batch; } From 1bba1fab87a84be3575b61aad811d8fa1d071b96 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 10:50:33 +0800 Subject: [PATCH 221/267] npm run build --- cocos/renderer/ui/ui-material.ts | 5 +++++ cocos/renderer/ui/ui.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos/renderer/ui/ui-material.ts b/cocos/renderer/ui/ui-material.ts index 1dee43b2da..c9e64ad757 100644 --- a/cocos/renderer/ui/ui-material.ts +++ b/cocos/renderer/ui/ui-material.ts @@ -34,6 +34,11 @@ export class UIMaterial { } public initialize (info: IUIMaterialInfo): boolean { + + if (!this._material) { + return false; + } + this._material = info.material; this._pass = this._material.passes[0]; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 8138aaf811..aec3f9b854 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -106,7 +106,7 @@ export class UI { // material.setProperty('mainTexture', texture); material.update(); - this._uiMaterial = this.createUIMaterial( { material }); + // this._uiMaterial = this.createUIMaterial( { material }); return true; } From 67d0a95e4d243734bbc6c844430f2c4830fabfdb Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 10:56:43 +0800 Subject: [PATCH 222/267] commit files --- cocos/renderer/ui/ui.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index aec3f9b854..605415bd8d 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -100,14 +100,15 @@ export class UI { type: GFXCommandBufferType.PRIMARY, }); + /* // create ui material const material = new Material(); material.effectName = 'sprite-material'; // material.setProperty('mainTexture', texture); material.update(); - // this._uiMaterial = this.createUIMaterial( { material }); - + this._uiMaterial = this.createUIMaterial( { material }); + */ return true; } From eedffd20dc71e7475f997d1d9ccb5723d057ecc4 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 23 Jan 2019 11:05:18 +0800 Subject: [PATCH 223/267] fix pass ubo error --- cocos/renderer/core/pass.ts | 3 +-- cocos/renderer/ui/ui.ts | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 63f3d4f2d7..6d207bd860 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -67,7 +67,7 @@ const _type2default = { [GFXType.SAMPLER_CUBE]: 'default-cube-texture', }; -const builtinRE = /^cc/i; +const builtinRE = /^CC.*?/; const btMask = 0xf0000000; // 4 bits, 16 slots const typeMask = 0x0fc00000; // 6 bits, 64 slots @@ -184,7 +184,6 @@ export class Pass { } for (const u of info.samplers) { - if (builtinRE.test(u.name)) { continue; } this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); const sampler = device.createSampler({ name: u.name, diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 605415bd8d..8dc5372b0f 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -4,6 +4,7 @@ import RecyclePool from '../../3d/memop/recycle-pool'; import { CanvasComponent } from '../../3d/ui/components/canvas-component'; import { UIRenderComponent } from '../../3d/ui/components/ui-render-component'; import { IMeshBufferInitData, MeshBuffer } from '../../3d/ui/mesh-buffer'; +import { SpriteFrame } from '../../assets/CCSpriteFrame'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; import { GFXBindingLayout } from '../../gfx/binding-layout'; @@ -23,7 +24,7 @@ import { vfmt } from '../../gfx/vertex-format-sample'; import { BaseNode } from '../../scene-graph/base-node'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; -import { SpriteFrame } from '../../assets/CCSpriteFrame'; +import { IUIMaterialInfo, UIMaterial } from './ui-material'; export class UIBufferBatch { public vb: GFXBuffer | null = null; From ba5ed365b2dfef83fc61cd1f3bdcd7a16271ef41 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 13:53:17 +0800 Subject: [PATCH 224/267] sampler from texture asset --- cocos/3d/assets/material.ts | 12 +++++-- cocos/3d/builtin/init.ts | 51 ++++++++++++++++-------------- cocos/assets/texture-base.ts | 12 +++---- cocos/core/data/object.d.ts | 2 +- cocos/renderer/core/pass.ts | 13 ++------ cocos/renderer/core/program-lib.ts | 5 +-- playground/simple.html | 3 +- 7 files changed, 50 insertions(+), 48 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index a740fad854..3a529ca937 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -213,9 +213,15 @@ export class Material extends Asset { if (bindingType === GFXBindingType.UNIFORM_BUFFER) { pass.setUniform(handle, val); } else if (bindingType === GFXBindingType.SAMPLER) { - const tv = val.getGFXTextureView(); - if (!tv) { console.warn('texture asset incomplete!'); return; } - pass.bindTextureView(Pass.getBindingFromHandle(handle), tv); + const sampler = val.getGFXSampler(); + const textureView = val.getGFXTextureView(); + if (!sampler || !textureView) { + console.warn('texture asset incomplete, missing ' + (sampler ? 'GFXTextureView' : 'GFXSampler')); + return false; + } + const binding = Pass.getBindingFromHandle(handle); + pass.bindSampler(binding, sampler); + pass.bindTextureView(binding, textureView); } return true; } diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts index d13175649e..df370cfb56 100644 --- a/cocos/3d/builtin/init.ts +++ b/cocos/3d/builtin/init.ts @@ -17,7 +17,8 @@ class BuiltinResMgr { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d')!; const imgAsset = new ImageAsset(canvas); - canvas.width = canvas.height = 2; + const l = canvas.width = canvas.height = 2; + const hl = l / 2; // ============================ // builtin textures @@ -25,7 +26,7 @@ class BuiltinResMgr { // black texture context.fillStyle = '#000'; - context.fillRect(0, 0, 2, 2); + context.fillRect(0, 0, l, l); const blackTexture = new Texture2D(); blackTexture._uuid = 'black-texture'; blackTexture.image = imgAsset; @@ -33,16 +34,24 @@ class BuiltinResMgr { // grey texture context.fillStyle = '#777'; - context.fillRect(0, 0, 2, 2); + context.fillRect(0, 0, l, l); const greyTexture = new Texture2D(); greyTexture._uuid = 'grey-texture'; greyTexture.image = imgAsset; resources[greyTexture._uuid] = greyTexture; - // grey cube texture - // const greyCubeTexture = new TextureCube(); - // greyCubeTexture._uuid = 'grey-cube-texture'; - // greyCubeTexture.image = { + // white texture + context.fillStyle = '#fff'; + context.fillRect(0, 0, l, l); + const whiteTexture = new Texture2D(); + whiteTexture._uuid = 'white-texture'; + whiteTexture.image = imgAsset; + resources[whiteTexture._uuid] = whiteTexture; + + // white cube texture + // const whiteCubeTexture = new TextureCube(); + // whiteCubeTexture._uuid = 'white-cube-texture'; + // whiteCubeTexture.image = { // front: new ImageAsset(canvas), // back: new ImageAsset(canvas), // left: new ImageAsset(canvas), @@ -50,19 +59,12 @@ class BuiltinResMgr { // top: new ImageAsset(canvas), // bottom: new ImageAsset(canvas), // }; - // resources[greyCubeTexture._uuid] = greyCubeTexture; - - // white texture - context.fillStyle = '#fff'; - context.fillRect(0, 0, 2, 2); - const whiteTexture = new Texture2D(); - whiteTexture._uuid = 'white-texture'; - whiteTexture.image = imgAsset; - resources[whiteTexture._uuid] = whiteTexture; + // whiteCubeTexture.onLoaded(); + // resources[whiteCubeTexture._uuid] = whiteCubeTexture; // normal texture context.fillStyle = '#7f7fff'; - context.fillRect(0, 0, 2, 2); + context.fillRect(0, 0, l, l); const normalTexture = new Texture2D(); normalTexture._uuid = 'normal-texture'; normalTexture.image = imgAsset; @@ -70,12 +72,14 @@ class BuiltinResMgr { // default texture context.fillStyle = '#ddd'; - context.fillRect(0, 0, 2, 2); + context.fillRect(0, 0, l, l); context.fillStyle = '#555'; - context.fillRect(0, 0, 1, 1); + context.fillRect(0, 0, hl, hl); context.fillStyle = '#555'; - context.fillRect(1, 1, 1, 1); + context.fillRect(hl, hl, hl, hl); const defaultTexture = new Texture2D(); + defaultTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + defaultTexture.setMipFilter(Texture2D.Filter.NEAREST); defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); defaultTexture._uuid = 'default-texture'; defaultTexture.image = imgAsset; @@ -92,6 +96,7 @@ class BuiltinResMgr { // top: new ImageAsset(canvas), // bottom: new ImageAsset(canvas), // }; + // defaultCubeTexture.onLoaded(); // resources.push(defaultCubeTexture); const spriteFrame = new SpriteFrame(); @@ -101,9 +106,7 @@ class BuiltinResMgr { spriteFrame.setOriginalSize(cc.size(imgAsset.width, imgAsset.height)); spriteFrame.setRect(new Rect(0, 0, imgAsset.width, imgAsset.height)); spriteFrame.image = imgAsset; - if (spriteFrame.onLoaded) { - spriteFrame.onLoaded(); - } + spriteFrame.onLoaded(); resources[spriteFrame._uuid] = spriteFrame; // default material @@ -123,7 +126,7 @@ class BuiltinResMgr { } public get (uuid: string): T { - return this._resources[uuid]; + return this._resources[uuid] as T; } } diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 550eb22339..87406f1567 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -30,7 +30,7 @@ import IDGenerator from '../core/utils/id-generator'; import {addon} from '../core/utils/js'; import { ccenum } from '../core/value-types/enum'; import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat, - GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; + GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define'; import { GFXDevice } from '../gfx/device'; import { GFXSampler } from '../gfx/sampler'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; @@ -243,7 +243,6 @@ export class TextureBase extends Asset { protected constructor (flipY: boolean = false) { super(); - // @ts-ignore EventTarget.call(this); this._flipY = flipY; @@ -268,6 +267,7 @@ export class TextureBase extends Asset { this._potientialHeight = height; this._format = format; this._mipmapLevel = 1; + this._updateSampler(); this._recreateTexture(); } @@ -558,19 +558,18 @@ export class TextureBase extends Asset { protected _getTextureCreateInfo (): IGFXTextureInfo { return { type: GFXTextureType.TEX2D, - /* tslint:disable:no-bitwise */ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST, - /* tslint:enable:no-bitwise */ format: toGfxFormat(this._format), width: this._potientialWidth, height: this._potientialHeight, mipLevel: this._mipmapLevel, + flags: this._genMipmap ? GFXTextureFlagBit.GEN_MIPMAP : GFXTextureFlagBit.NONE, }; } protected _getTextureViewCreateInfo (): IGFXTextureViewInfo { return { - texture: this._texture, + texture: this._texture!, type: GFXTextureViewType.TV2D, format: this._getGfxFormat(), }; @@ -622,8 +621,7 @@ export class TextureBase extends Asset { } } -/* tslint:disable:no-string-literal */ -cc['TextureBase'] = TextureBase; +cc.TextureBase = TextureBase; /** * !#zh diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts index 698ce0a7a5..96b70896d5 100644 --- a/cocos/core/data/object.d.ts +++ b/cocos/core/data/object.d.ts @@ -41,7 +41,7 @@ export class CCObject { protected _destruct(): void; protected _destroyImmediate(): void; - protected _serialize?(): any; + protected _serialize?(exporting?: any): any; protected _deserialize?(data: any, ctx: any): any; protected _onPreDestroy (): any; protected Flags: object; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 6d207bd860..247d5cdfb6 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -185,18 +185,11 @@ export class Pass { for (const u of info.samplers) { this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); - const sampler = device.createSampler({ - name: u.name, - // TODO: specify filter modes in effect - }); - if (sampler) { - this._samplers[u.binding] = sampler; - } else { - console.error('create sampler failed.'); - } const inf = info.properties && info.properties[u.name]; const name = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; - this._textureViews[u.binding] = builtinResMgr.get(name).getGFXTextureView()!; + const texture = builtinResMgr.get(name); + this._samplers[u.binding] = texture.getGFXSampler()!; + this._textureViews[u.binding] = texture.getGFXTextureView()!; } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index bb4f7964d3..2bfc0a874f 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -5,8 +5,8 @@ import { GFXGetTypeSize, GFXShaderType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXShader, GFXUniform, GFXUniformBlock } from '../../gfx/shader'; import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; -import { IDefineMap } from './effect'; import { SkinningUBO } from '../models/model-uniforms'; +import { IDefineMap } from './effect'; function _generateDefines ( device: GFXDevice, @@ -86,7 +86,7 @@ class ProgramLib { def._map = ((value: any) => (value ? (1 << def._offset) : 0)); } if (def.name === 'CC_USE_SKINNING') { - tmpl.blocks = tmpl.blocks.concat(convertToBlockInfo(SkinningUBO.BLOCK)); + tmpl.blocks = tmpl.blocks.concat(skinning); } offset += cnt; def._offset = offset; @@ -149,6 +149,7 @@ class ProgramLib { const globals = convertToBlockInfo(UBOGlobal.BLOCK); const locals = convertToBlockInfo(UBOLocal.BLOCK); +const skinning = convertToBlockInfo(SkinningUBO.BLOCK); function convertToUniformInfo (uniform: GFXUniform): IBlockMember { return { diff --git a/playground/simple.html b/playground/simple.html index b7b956af0a..ed0738541c 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -61,7 +61,7 @@ const texture = createTexture(cc.game.canvas.getElementsByTagName('img')); const material = new cc.Material(); - material.setDefines({ USE_COLOR: true }); + material.setDefines({ USE_COLOR: true, USE_TEXTURE: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js material.effectName = 'builtin-effect-unlit'; @@ -76,6 +76,7 @@ modelCom.mesh = cc.utils.createMesh(cc.primitives[geomList[i % geomList.length]]()); modelNode.setPosition(0, 0, i * 2); models.push(modelNode); + // material instance initialized here passes.push(modelCom.material.passes[0]); } const handle = passes[0].getHandle('color'); From 19e5e68a3cdc6035d7ca4ffd2aa249c0c68d78f6 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 14:49:44 +0800 Subject: [PATCH 225/267] fix floating texture update --- cocos/gfx/webgl/webgl-buffer.ts | 2 + cocos/gfx/webgl/webgl-commands.ts | 51 ++++++++++---- cocos/renderer/ui/ui.ts | 110 +++++++++++++++++------------- 3 files changed, 103 insertions(+), 60 deletions(-) diff --git a/cocos/gfx/webgl/webgl-buffer.ts b/cocos/gfx/webgl/webgl-buffer.ts index fe9fbac9e1..4a2280a25a 100644 --- a/cocos/gfx/webgl/webgl-buffer.ts +++ b/cocos/gfx/webgl/webgl-buffer.ts @@ -58,6 +58,8 @@ export class WebGLGFXBuffer extends GFXBuffer { } public resize (size: number) { + this._size = size; + this._count = this._size / this._stride; if (this._memUsage & GFXMemoryUsageBit.HOST) { if ((this._usage & GFXBufferUsageBit.INDIRECT) === GFXBufferUsageBit.NONE) { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 2d6d886825..16bc2a3c16 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1,9 +1,29 @@ import { CachedArray } from '../../core/memop/cached-array'; import { GFXBufferSource, IGFXDrawInfo, IGFXIndirectBuffer } from '../buffer'; -import { GFXBindingType, GFXBufferTextureCopy, GFXBufferUsageBit, GFXColorMask, - GFXCullMode, GFXDynamicState, GFXFormat, GFXFormatInfos, GFXFormatSize, GFXLoadOp, - GFXMemoryUsageBit, GFXShaderType, GFXStencilFace, GFXTextureFlagBit, - GFXTextureLayout, GFXTextureViewType, GFXType, IGFXColor, IGFXRect, IGFXViewport, WebGLEXT } from '../define'; +import { + GFXBindingType, + GFXBufferTextureCopy, + GFXBufferUsageBit, + GFXColorMask, + GFXCullMode, + GFXDynamicState, + GFXFormat, + GFXFormatInfos, + GFXFormatSize, + GFXLoadOp, + GFXMemoryUsageBit, + GFXShaderType, + GFXStencilFace, + GFXTextureFlagBit, + GFXTextureLayout, + GFXTextureViewType, + GFXType, + IGFXColor, + IGFXFormatInfo, + 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'; @@ -2195,7 +2215,8 @@ export function WebGLCmdFuncCopyBufferToTexture ( const gl = device.gl; - const bufferView = new Uint8Array(buffer as ArrayBuffer); + const buff = buffer as ArrayBuffer; + const fmtInfo: IGFXFormatInfo = GFXFormatInfos[gpuTexture.format]; switch (gpuTexture.glTarget) { case WebGLRenderingContext.TEXTURE_2D: { @@ -2215,11 +2236,12 @@ export function WebGLCmdFuncCopyBufferToTexture ( for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = bufferView.subarray(buffOffset, buffOffset + memSize); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, data); + gpuTexture.glFormat, gpuTexture.glType, pixels); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -2235,11 +2257,12 @@ export function WebGLCmdFuncCopyBufferToTexture ( for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = bufferView.subarray(buffOffset, buffOffset + memSize); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_2D, m, region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, data); + gpuTexture.glFormat, pixels); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -2267,11 +2290,12 @@ export function WebGLCmdFuncCopyBufferToTexture ( for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = bufferView.subarray(buffOffset, buffOffset + memSize); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); gl.texSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, data); + gpuTexture.glFormat, gpuTexture.glType, pixels); buffOffset += memSize; w = Math.max(1, w >> 1); @@ -2289,11 +2313,12 @@ export function WebGLCmdFuncCopyBufferToTexture ( for (let m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) { const memSize = GFXFormatSize(gpuTexture.format, w, h, 1); - const data = bufferView.subarray(buffOffset, buffOffset + memSize); + const data = buff.slice(buffOffset, buffOffset + memSize); + const pixels = !fmtInfo.isFloating ? new Uint8Array(data) : new Float32Array(data); gl.compressedTexSubImage2D(WebGLRenderingContext.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, data); + gpuTexture.glFormat, pixels); buffOffset += memSize; w = Math.max(1, w >> 1); diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 8dc5372b0f..9df0917ed7 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -26,22 +26,24 @@ import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; import { IUIMaterialInfo, UIMaterial } from './ui-material'; -export class UIBufferBatch { - public vb: GFXBuffer | null = null; - public ib: GFXBuffer | null = null; - public ia: GFXInputAssembler | null = null; +export interface IUIBufferBatch { + vb: GFXBuffer; + ib: GFXBuffer; + ia: GFXInputAssembler; + vf32: Float32Array; + vi16: Int16Array; } -export class UIDrawBatch { - public camera: Camera | null = null; - public bufferBatch: UIBufferBatch | null = null; - public uiMaterial: UIMaterial | null = null; +export interface IUIDrawBatch { + camera: Camera; + bufferBatch: IUIBufferBatch; + uiMaterial: UIMaterial; } export interface IUIRenderData { meshBuffer: MeshBuffer; material: Material; - texture: SpriteFrame, + texture: SpriteFrame; camera: Camera; } @@ -54,21 +56,21 @@ export class UI { private _bufferPool: RecyclePool = new RecyclePool(() => { return new MeshBuffer(); }, 128); - private _bufferBatchPool: RecyclePool = new RecyclePool(() => { - return new UIBufferBatch(); + private _bufferBatchPool: RecyclePool = new RecyclePool(() => { + return new Object() as IUIBufferBatch; }, 128); - private _drawBatchPool: RecyclePool = new RecyclePool(() => { - return new UIDrawBatch(); + private _drawBatchPool: RecyclePool = new RecyclePool(() => { + return new Object() as IUIDrawBatch; }, 128); private _device: GFXDevice; private _cmdBuff: GFXCommandBuffer | null = null; private _renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; private _scene: RenderScene; private _attributes: IGFXInputAttribute[] = []; - private _bufferBatches: UIBufferBatch[] = []; + private _bufferBatches: IUIBufferBatch[] = []; private _uiMaterial: UIMaterial | null = null; private _uiMaterials: UIMaterial[] = []; - private _batches: CachedArray; + private _batches: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; @@ -106,10 +108,11 @@ export class UI { const material = new Material(); material.effectName = 'sprite-material'; // material.setProperty('mainTexture', texture); - material.update(); + // material.update(); - this._uiMaterial = this.createUIMaterial( { material }); + this._uiMaterial = this.createUIMaterial({ material }); */ + return true; } @@ -200,52 +203,65 @@ export class UI { this._renderScreens(); - // Merge batch /* - let curCamera: Camera | null = null; - let curTexture: GFXTexture | null = null; - let curBufferBatch: UIBufferBatch = this._bufferBatches[0]; - let vbOffset = 0; + // Merge batch + if (this._commitUIRenderDatas.length) { + const first = this._commitUIRenderDatas[0]; - for (const uiRenderData of this._commitUIRenderDatas) { + let curCamera: Camera = first.camera; + let curTexture: GFXTexture | null = first.texture.getGFXTexture(); + let curBufferBatch: IUIBufferBatch = this._bufferBatches[0]; + let vbOffset = 0; + let ibOffset = 0; + let ibcount = 0; + let vb = curBufferBatch.vb; + let vbBuffer = (vb.buffer as ArrayBuffer); + let lastVF32; - if (curCamera === uiRenderData.camera && - curTexture === uiRenderData.texture.getGFXTexture()) { - - if (curBufferBatch.ib!.count + uiRenderData.meshBuffer.iData!.length < 65535) { + for (const uiRenderData of this._commitUIRenderDatas) { + if (ibcount + uiRenderData.meshBuffer.iData!.length < 65535) { const vf32: Float32Array = uiRenderData.meshBuffer.vData!; - const vbSize = uiRenderData.meshBuffer.vData!.length * 4 + vbOffset; - if (vbSize > curBufferBatch.vb!.size) { - curBufferBatch.vb!.resize(vbSize); + const vbSize = vf32.length * 4 + vbOffset; + if (vbSize > vb.size) { + vb.resize(vbSize); + + vbBuffer = (vb.buffer as ArrayBuffer); + lastVF32 = curBufferBatch.vf32; + curBufferBatch.vf32 = new Float32Array(vbBuffer); + curBufferBatch.vf32.set(lastVF32, 0); } - curBufferBatch.vb!.update(vf32, vbOffset, vf32.length * 4); - vbOffset += vf32.length; + curBufferBatch.vf32.set(vf32, vbOffset); + vbOffset += vf32.length * 4; + + + } else { + } - } - if (curCamera !== uiRenderData.camera) { + if (curCamera !== uiRenderData.camera) { - if (curBufferBatch) { + if (curBufferBatch) { - if (curBufferBatch.ib!.count + uiRenderData.meshBuffer.iData!.length > 65535) { + if (curBufferBatch.ib!.count + uiRenderData.meshBuffer.iData!.length > 65535) { + } } + + curCamera = uiRenderData.camera; + curTexture = uiRenderData.texture.getGFXTexture(); + curBufferBatch = this._drawBatchPool.add(); + + continue; } - curCamera = uiRenderData.camera; - curTexture = uiRenderData.texture.getGFXTexture(); - curBufferBatch = this._drawBatchPool.add(); + if (curTexture !== uiRenderData.texture.getGFXTexture()) { + curTexture = uiRenderData.texture.getGFXTexture(); + } - continue; + // uiRenderData.meshBuffer.iData.length; } - - if (curTexture !== uiRenderData.texture.getGFXTexture()) { - curTexture = uiRenderData.texture.getGFXTexture(); - } - - // uiRenderData.meshBuffer.iData.length; } */ } @@ -335,7 +351,7 @@ export class UI { comp.postUpdateAssembler(); } - private createBufferBatch (): UIBufferBatch { + private createBufferBatch (): IUIBufferBatch { const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; From 16f4ed3b936ae13c552937746e2ed1c9af732481 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 23 Jan 2019 15:01:48 +0800 Subject: [PATCH 226/267] fix particle rendering bug --- cocos/3d/framework/particle/animator/curve-range.js | 4 +++- cocos/3d/framework/particle/animator/gradient-range.js | 4 +++- cocos/3d/framework/particle/particle-system-component.js | 4 ++-- cocos/renderer/models/particle-batch-model.ts | 4 ++-- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/cocos/3d/framework/particle/animator/curve-range.js b/cocos/3d/framework/particle/animator/curve-range.js index 3320823e81..501e516025 100644 --- a/cocos/3d/framework/particle/animator/curve-range.js +++ b/cocos/3d/framework/particle/animator/curve-range.js @@ -14,7 +14,9 @@ const Mode = Enum({ @ccclass('cc.CurveRange') export default class CurveRange { - @property + @property({ + type: Mode + }) mode = Mode.Constant; @property({ diff --git a/cocos/3d/framework/particle/animator/gradient-range.js b/cocos/3d/framework/particle/animator/gradient-range.js index 65fb3906a8..d716ba4d82 100644 --- a/cocos/3d/framework/particle/animator/gradient-range.js +++ b/cocos/3d/framework/particle/animator/gradient-range.js @@ -24,7 +24,9 @@ const Mode = Enum({ @ccclass('cc.GradientRange') export default class GradientRange { - @property + @property({ + type: Mode + }) mode = Mode.Color; @property diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.js index 39e32fc75a..4e9168dc92 100644 --- a/cocos/3d/framework/particle/particle-system-component.js +++ b/cocos/3d/framework/particle/particle-system-component.js @@ -104,7 +104,7 @@ export default class ParticleSystemComponent extends Component { simulationSpeed = 1.0; @property - playOnAwake = false; + playOnAwake = true; @property({ type: CurveRange @@ -215,7 +215,7 @@ export default class ParticleSystemComponent extends Component { } onEnable() { - if (this._playOnAwake) { + if (this.playOnAwake) { this.play(); } } diff --git a/cocos/renderer/models/particle-batch-model.ts b/cocos/renderer/models/particle-batch-model.ts index 89c6fface4..689c56b2ef 100644 --- a/cocos/renderer/models/particle-batch-model.ts +++ b/cocos/renderer/models/particle-batch-model.ts @@ -61,7 +61,7 @@ export default class ParticleBatchModel extends Model { this._vertAttrs = attrs; this._vertSize = 0; for (const a of this._vertAttrs) { - this._vertSize += GFXFormatInfos[a.format].size * GFXFormatInfos[a.format].count; + this._vertSize += GFXFormatInfos[a.format].size; } // rebuid this._vBuffer = this._createSubMeshData(); @@ -128,7 +128,7 @@ export default class ParticleBatchModel extends Model { } public disableStretchedBillboard () { - if (this._vertAttrs!.find((attr) => attr.name === GFXAttributeName.ATTR_COLOR) !== undefined) { + if (this._vertAttrs!.find((attr) => attr.name === GFXAttributeName.ATTR_COLOR1) !== undefined) { this._vertAttrs!.pop(); this.setVertexAttributes(this._vertAttrs!); } From bac4eaf862c59e31b339bebdd40b52337c097804 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 15:18:20 +0800 Subject: [PATCH 227/267] fix texture parameters cache error bug --- cocos/gfx/webgl/webgl-commands.ts | 41 ++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 16bc2a3c16..ec81e36417 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -918,13 +918,15 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } const glProgram = gl.createProgram(); - if (glProgram) { - gpuShader.glProgram = glProgram; + if (!glProgram) { + return; + } - // link program - for (const gpuStage of gpuShader.gpuStages) { - gl.attachShader(gpuShader.glProgram, gpuStage.glShader); - } + gpuShader.glProgram = glProgram; + + // link program + for (const gpuStage of gpuShader.gpuStages) { + gl.attachShader(gpuShader.glProgram, gpuStage.glShader); } gl.linkProgram(gpuShader.glProgram); @@ -1066,6 +1068,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web const activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS); let unitIdx = 0; + const glActiveSamplers: WebGLGPUUniformSampler[] = []; + for (let i = 0; i < activeUniformCount; ++i) { const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i); if (uniformInfo) { @@ -1112,6 +1116,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web glSampler.glLoc = glLoc; unitIdx += uniformInfo.size; + glActiveSamplers.push(glSampler); break; } @@ -1120,6 +1125,17 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } } } // for + + if (glActiveSamplers.length) { + if (device.stateCache.glProgram !== gpuShader.glProgram) { + gl.useProgram(gpuShader.glProgram); + device.stateCache.glProgram = gpuShader.glProgram; + } + + for (const glSampler of glActiveSamplers) { + gl.uniform1iv(glSampler.glLoc, glSampler.units); + } + } } export function WebGLCmdFuncDestroyShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { @@ -1877,6 +1893,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } let glTexUnit: IWebGLTexUnit | null = null; + let isTexParamInvalied = false; switch (glSampler.glType) { case WebGLRenderingContext.SAMPLER_2D: { @@ -1884,6 +1901,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; + isTexParamInvalied = true; } break; } @@ -1893,6 +1911,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (glTexUnit.glTexture !== gpuTexture.glTexture) { gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); glTexUnit.glTexture = gpuTexture.glTexture; + isTexParamInvalied = true; } break; } @@ -1904,28 +1923,28 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web if (glTexUnit) { const gpuSampler = gpuBinding.gpuSampler; - if (glTexUnit.minFilter !== gpuSampler.glMinFilter) { + if (glTexUnit.minFilter !== gpuSampler.glMinFilter || isTexParamInvalied) { gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuSampler.glMinFilter); glTexUnit.minFilter = gpuSampler.glMinFilter; } - if (glTexUnit.magFilter !== gpuSampler.glMagFilter) { + if (glTexUnit.magFilter !== gpuSampler.glMagFilter || isTexParamInvalied) { gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter); glTexUnit.magFilter = gpuSampler.glMagFilter; } - if (glTexUnit.wrapS !== gpuSampler.glWrapS) { + if (glTexUnit.wrapS !== gpuSampler.glWrapS || isTexParamInvalied) { gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuSampler.glWrapS); glTexUnit.wrapS = gpuSampler.glWrapS; } - if (glTexUnit.wrapT !== gpuSampler.glWrapT) { + if (glTexUnit.wrapT !== gpuSampler.glWrapT || isTexParamInvalied) { gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuSampler.glWrapT); glTexUnit.wrapT = gpuSampler.glWrapT; } /* - if(glTexUnit.wrapR !== gpuSampler.glWrapR) { + if(glTexUnit.wrapR !== gpuSampler.glWrapR || isTexParamInvalied) { gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_R, gpuSampler.glWrapR); glTexUnit.wrapR = gpuSampler.glWrapR; } From 2bca6808602c00f39cde1cdb226ad07f642329a1 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 15:38:54 +0800 Subject: [PATCH 228/267] modify texture address mode from WRAP to CLAMP --- cocos/gfx/sampler.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/gfx/sampler.ts b/cocos/gfx/sampler.ts index 6d0afc5e89..d468316b49 100644 --- a/cocos/gfx/sampler.ts +++ b/cocos/gfx/sampler.ts @@ -22,9 +22,9 @@ export class GFXSamplerState { public minFilter: GFXFilter = GFXFilter.LINEAR; public magFilter: GFXFilter = GFXFilter.LINEAR; public mipFilter: GFXFilter = GFXFilter.NONE; - public addressU: GFXAddress = GFXAddress.WRAP; - public addressV: GFXAddress = GFXAddress.WRAP; - public addressW: GFXAddress = GFXAddress.WRAP; + public addressU: GFXAddress = GFXAddress.CLAMP; + public addressV: GFXAddress = GFXAddress.CLAMP; + public addressW: GFXAddress = GFXAddress.CLAMP; public maxAnisotropy: number = 16; public cmpFunc: GFXComparisonFunc = GFXComparisonFunc.NEVER; public borderColor: number[] = [0.0, 0.0, 0.0, 0.0]; From 031ad8fb18fc4689d8274c729175b1bfa08061e4 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 15:21:57 +0800 Subject: [PATCH 229/267] sampler from effect, again --- cocos/3d/assets/effect-asset.ts | 2 ++ cocos/3d/assets/material.ts | 10 +++------ cocos/3d/builtin/effects.js | 38 ++++++++++++++++----------------- cocos/3d/builtin/init.ts | 12 ++++------- cocos/gfx/define.ts | 2 +- cocos/renderer/core/pass.ts | 13 +++++++---- playground/simple.html | 2 +- 7 files changed, 39 insertions(+), 40 deletions(-) diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts index 3aef395d52..3cb9b4e16d 100644 --- a/cocos/3d/assets/effect-asset.ts +++ b/cocos/3d/assets/effect-asset.ts @@ -2,6 +2,7 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { GFXDynamicState, GFXPrimitiveMode, GFXType } from '../../gfx/define'; import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; +import { IGFXSamplerInfo } from '../../gfx/sampler'; import { RenderPassStage } from '../../pipeline/define'; import { programLib } from '../../renderer/core/program-lib'; @@ -9,6 +10,7 @@ export interface IPropertyInfo { type: number; // auto-extracted if not specified value?: number[] | string; displayName?: string; + sampler?: IGFXSamplerInfo; } export interface IPassInfo { program: string; diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 3a529ca937..90ad28af0e 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -26,6 +26,7 @@ import { Asset } from '../../assets/asset'; import { ccclass, property } from '../../core/data/class-decorator'; import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; import { GFXBindingType } from '../../gfx/define'; +import { GFXTextureView } from '../../gfx/texture-view'; import { Effect, IDefineMap } from '../../renderer/core/effect'; import { Pass, PassOverrides } from '../../renderer/core/pass'; import { RenderableComponent } from '../framework/renderable-component'; @@ -213,14 +214,9 @@ export class Material extends Asset { if (bindingType === GFXBindingType.UNIFORM_BUFFER) { pass.setUniform(handle, val); } else if (bindingType === GFXBindingType.SAMPLER) { - const sampler = val.getGFXSampler(); - const textureView = val.getGFXTextureView(); - if (!sampler || !textureView) { - console.warn('texture asset incomplete, missing ' + (sampler ? 'GFXTextureView' : 'GFXSampler')); - return false; - } + const textureView = val instanceof GFXTextureView ? val : val.getGFXTextureView(); + if (!textureView) { console.warn('texture asset incomplete!'); return false; } const binding = Pass.getBindingFromHandle(handle); - pass.bindSampler(binding, sampler); pass.bindTextureView(binding, textureView); } return true; diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index b3676546b9..83ef3ff9a7 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,7 +1,7 @@ export default [ { "name": "builtin-effect-unlit", - "techniques": [{"queue":"opaque", "lod":100, "passes":[{"properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}, "program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag"}]}], + "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}], "shaders": [ { "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", @@ -31,7 +31,7 @@ export default [ }, { "name": "builtin-effect-skybox", - "techniques": [{"queue":"opaque-1000", "lod":200, "passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "properties":{"cubeMap":{"type":32, "value":"greyCube"}}, "program":"builtin-effect-skybox|sky-vs|sky-fs"}]}], + "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], "shaders": [ { "name": "builtin-effect-skybox|sky-vs|sky-fs", @@ -50,7 +50,7 @@ export default [ }, { "name": "builtin-effect-sprite", - "techniques": [{"queue":"overlay", "passes":[{"depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "properties":{"mainTexture":{"type":29, "value":"grey"}}, "program":"builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag"}]}], + "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":"default"}}}]}], "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", @@ -67,36 +67,36 @@ export default [ }, { "name": "builtin-effect-particle-add", - "techniques": [{"queue": "transparent", "lod": 200, "passes": [{"rasterizerState": {"cullMode": 0}, "depthStencilState": {"depthTest": true, "depthWrite": false}, "blendState": {"targets": [{"blend": true, "blendSrc": 2, "blendDst": 1, "blendSrcAlpha": 2, "blendDstAlpha": 1}]}, "properties": {"mainTexture": {"type": 29, "value": "grey"}, "mainTiling": {"type": 14, "value": [1, 1]}, "mainOffset": {"type": 14, "value": [0, 0]}, "frameTile": {"type": 14, "value": [1, 1]}, "velocityScale": {"type": 13, "value": [0]}, "lengthScale": {"type": 13, "value": [0]}, "tintColor": {"type": 17, "value": [0.5, 0.5, 0.5, 0.5]}}, "program": "7b4748a3d0952030fe04084550aafa0c0d63899ce6b9537dfce75c0b"}]}], + "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":1, "blendSrcAlpha":2, "blendDstAlpha":1}]}, "program":"builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", "properties":{"mainTexture":{"type":29, "value":"grey"}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "frameTile":{"type":14, "value":[1, 1]}, "velocityScale":{"type":13, "value":[0]}, "lengthScale":{"type":13, "value":[0]}, "tintColor":{"type":17, "value":[0.5, 0.5, 0.5, 0.5]}}}]}], "shaders": [ { - "name": "7b4748a3d0952030fe04084550aafa0c0d63899ce6b9537dfce75c0b", - "vert": "\n uniform vec2 frameTile;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n uniform float velocityScale;\n uniform float lengthScale;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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\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", + "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 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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_uv; \nattribute vec2 a_uv0; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color0; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color0.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_uv.xy - 0.5) * a_uv0.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_uv0.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\n , velocity\n , velocityScale\n , lengthScale\n , a_uv0.x\n , a_uv.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_uv.z, a_uv.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": []}, - {"name": "USE_HORIZONTAL_BILLBOARD", "type": "boolean", "defines": []}, - {"name": "USE_VERTICAL_BILLBOARD", "type": "boolean", "defines": []}, - {"name": "USE_WORLD_SPACE", "type": "boolean", "defines": []} + {"name":"USE_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_STRETCHED_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_HORIZONTAL_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_VERTICAL_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_WORLD_SPACE", "type":"boolean", "defines":[]} ], "blocks": [ {"name": "Constants", "size": 32, "defines": [], "binding": 0, "members": [ - {"name": "frameTile", "type": 14, "count": 1, "size": 8}, - {"name": "mainTiling", "type": 14, "count": 1, "size": 8}, - {"name": "mainOffset", "type": 14, "count": 1, "size": 8}, - {"name": "velocityScale", "type": 13, "count": 1, "size": 4}, - {"name": "lengthScale", "type": 13, "count": 1, "size": 4} + {"name":"frameTile", "type":14, "count":1, "size":8}, + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8}, + {"name":"velocityScale", "type":13, "count":1, "size":4}, + {"name":"lengthScale", "type":13, "count":1, "size":4} ]}, {"name": "FragConstants", "size": 16, "defines": [], "binding": 1, "members": [ - {"name": "tintColor", "type": 16, "count": 1, "size": 16} + {"name":"tintColor", "type":16, "count":1, "size":16} ]} ], "samplers": [ - {"name": "mainTexture", "type": 29, "count": 1, "defines": [], "binding": 2} + {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":2} ], "dependencies": {} } ] - } + }, ]; diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts index df370cfb56..8497205fde 100644 --- a/cocos/3d/builtin/init.ts +++ b/cocos/3d/builtin/init.ts @@ -71,16 +71,14 @@ class BuiltinResMgr { resources[normalTexture._uuid] = normalTexture; // default texture + canvas.width = canvas.height = 16; context.fillStyle = '#ddd'; - context.fillRect(0, 0, l, l); + context.fillRect(0, 0, 16, 16); context.fillStyle = '#555'; - context.fillRect(0, 0, hl, hl); + context.fillRect(0, 0, 8, 8); context.fillStyle = '#555'; - context.fillRect(hl, hl, hl, hl); + context.fillRect(8, 8, 8, 8); const defaultTexture = new Texture2D(); - defaultTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - defaultTexture.setMipFilter(Texture2D.Filter.NEAREST); - defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); defaultTexture._uuid = 'default-texture'; defaultTexture.image = imgAsset; resources[defaultTexture._uuid] = defaultTexture; @@ -100,8 +98,6 @@ class BuiltinResMgr { // resources.push(defaultCubeTexture); const spriteFrame = new SpriteFrame(); - spriteFrame.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); - spriteFrame.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT); spriteFrame._uuid = 'default-spriteframe'; spriteFrame.setOriginalSize(cc.size(imgAsset.width, imgAsset.height)); spriteFrame.setRect(new Rect(0, 0, imgAsset.width, imgAsset.height)); diff --git a/cocos/gfx/define.ts b/cocos/gfx/define.ts index 03a8dd02d0..6b2831282b 100644 --- a/cocos/gfx/define.ts +++ b/cocos/gfx/define.ts @@ -294,8 +294,8 @@ export enum GFXPrimitiveMode { export enum GFXPolygonMode { FILL, - LINE, POINT, + LINE, } export enum GFXShadeModel { diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 247d5cdfb6..22f284e785 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -186,10 +186,15 @@ export class Pass { for (const u of info.samplers) { this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.type, u.binding); const inf = info.properties && info.properties[u.name]; - const name = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; - const texture = builtinResMgr.get(name); - this._samplers[u.binding] = texture.getGFXSampler()!; - this._textureViews[u.binding] = texture.getGFXTextureView()!; + const samplerInfo = Object.assign({ name: u.name }, inf && inf.sampler); + const sampler = device.createSampler(samplerInfo); + if (sampler) { + this._samplers[u.binding] = sampler; + } else { + console.error('create sampler failed.'); + } + const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; + this._textureViews[u.binding] = builtinResMgr.get(texName).getGFXTextureView()!; } } diff --git a/playground/simple.html b/playground/simple.html index ed0738541c..7b6edcfc33 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -61,7 +61,7 @@ const texture = createTexture(cc.game.canvas.getElementsByTagName('img')); const material = new cc.Material(); - material.setDefines({ USE_COLOR: true, USE_TEXTURE: true }); + material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js material.effectName = 'builtin-effect-unlit'; From fcdadf40b61bdfd5be3f53a93e19074d5936f993 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 16:35:58 +0800 Subject: [PATCH 230/267] reset hasChanged at the end of every frame --- cocos/3d/framework/model-component.js | 4 ++-- cocos/components/component.js | 2 +- cocos/core/director.js | 10 +++------- cocos/pipeline/render-pipeline.ts | 4 +--- cocos/renderer/scene/model.ts | 3 +-- 5 files changed, 8 insertions(+), 15 deletions(-) diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index f12afc3011..a52e2cd0a5 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -170,10 +170,11 @@ export class ModelComponent extends RenderableComponent { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); + if (this._model) { this._model.enabled = true; } } onDisable() { - if (this._model) { this._model.enabled = this.enabled; } + if (this._model) { this._model.enabled = false; } } onDestroy() { @@ -190,7 +191,6 @@ export class ModelComponent extends RenderableComponent { } else { this._model = this._createModel(); } - this._model.enable = this.enabled; this._model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); diff --git a/cocos/components/component.js b/cocos/components/component.js index 027555d5b1..867c106ea6 100644 --- a/cocos/components/component.js +++ b/cocos/components/component.js @@ -178,7 +178,7 @@ class Component extends CCObject { visible: false }) get enabledInHierarchy () { - return (this._objFlags & IsOnEnableCalled) > 0; + return this._enabled && this.node._activeInHierarchy; } /** diff --git a/cocos/core/director.js b/cocos/core/director.js index 4f475aef48..3eec6f45d7 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -918,18 +918,14 @@ class Director extends EventTarget { CCObject._deferredDestroy(); } - // Render this._physicsSystem.update(this._deltaTime); + this.emit(cc.Director.EVENT_BEFORE_DRAW); - //this._renderSystem.update(this._deltaTime); - - - this._root.frameMove(this._deltaTime); - - // After draw + this._root.frameMove(this._deltaTime); // Render this.emit(cc.Director.EVENT_AFTER_DRAW); eventManager.frameUpdateListeners(); + this._scene.resetHasChanged(); this._totalFrames++; } } diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index c85d96ae14..52bcc31cd6 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -349,9 +349,7 @@ export abstract class RenderPipeline { for (const model of scene.models) { // filter model by view visibility - if (view.visibility > 0 && model.viewID !== view.visibility || - !model.enabled || - !model.node.activeInHierarchy) { + if (view.visibility > 0 && model.viewID !== view.visibility || !model.enabled) { continue; } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index 4986fb4eea..af070d7b04 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -31,7 +31,7 @@ export class Model { private _scene: RenderScene; private _node: Node; private _id: number; - private _isEnable: boolean = true; + private _isEnable: boolean = false; private _viewID: number = -1; private _cameraID: number = -1; private _userKey: number = -1; @@ -99,7 +99,6 @@ export class Model { if (this._node.hasChanged) { this._node.updateWorldTransformFull(); if (this._modelBounds) { - this._modelBounds.transform( // @ts-ignore this._node._mat, this._node._pos, this._node._rot, this._node._scale, From a87815769c0d3f48a0fdb3db9892f4cf004b3582 Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Wed, 23 Jan 2019 18:22:58 +0800 Subject: [PATCH 231/267] make some modifications to editor inspector and add example for ui --- cocos/3d/ui/components/button-component.ts | 18 +-- cocos/3d/ui/components/canvas-component.ts | 38 ++--- .../components/editbox/edit-box-component.ts | 2 +- .../3d/ui/components/editbox/edit-box-impl.ts | 143 +++++++++++------- .../components/editbox/{types.js => types.ts} | 51 +++---- .../ui/components/progress-bar-component.ts | 16 +- cocos/3d/ui/components/slider-component.ts | 14 +- cocos/3d/ui/components/toggle-component.ts | 2 +- cocos/3d/ui/components/widget-component.ts | 6 +- cocos/3d/ui/index.ts | 46 +++--- playground/files.js | 3 +- playground/ui.html | 76 ++++++++++ 12 files changed, 270 insertions(+), 145 deletions(-) rename cocos/3d/ui/components/editbox/{types.js => types.ts} (91%) create mode 100644 playground/ui.html diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts index d68c5bf95c..a57b618c79 100644 --- a/cocos/3d/ui/components/button-component.ts +++ b/cocos/3d/ui/components/button-component.ts @@ -30,7 +30,7 @@ import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import Event from '../../../core/event/event'; import { lerp } from '../../../core/utils/misc'; -import { Color, Vec3 } from '../../../core/value-types/index'; +import { Color, Vec3, Enum } from '../../../core/value-types/index'; import * as math from '../../../core/vmath/index'; import { Node } from '../../../scene-graph'; import { SpriteComponent } from './sprite-component'; @@ -41,34 +41,34 @@ import { EventTouch } from '../../../core/platform/event-manager'; * !#zh 过渡类型 * @enum Button.Transition */ -const Transition = cc.Enum({ +enum Transition { /** * !#en The none type. * !#zh 不做任何过渡 * @property {Number} NONE */ - NONE: 0, + NONE = 0, /** * !#en The color type. * !#zh 颜色过渡 * @property {Number} COLOR */ - COLOR: 1, + COLOR = 1, /** * !#en The sprite type. * !#zh 精灵过渡 * @property {Number} SPRITE */ - SPRITE: 2, + SPRITE = 2, /** * !#en The scale type * !#zh 缩放过渡 * @property {Number} SCALE */ - SCALE: 3, -}); + SCALE = 3, +}; /** * !#en @@ -129,7 +129,7 @@ const Transition = cc.Enum({ @executionOrder(100) @menu('UI/Button') @executeInEditMode -export default class ButtonComponent extends Component { +export class ButtonComponent extends Component { /** * !#en @@ -193,7 +193,7 @@ export default class ButtonComponent extends Component { return this._transition; } - set transition (value: number) { + set transition(value: Transition) { if (this._transition === value) { return; } diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 50e0a6a7d4..972fc29372 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -30,7 +30,7 @@ import { ccclass, executeInEditMode, executionOrder, menu, property } from '../. import Rect from '../../../core/value-types/rect'; import Size from '../../../core/value-types/size'; import { GFXClearFlag } from '../../../gfx/define'; -import { Camera } from '../../../renderer/scene/camera'; +import { Camera, ICameraInfo } from '../../../renderer/scene/camera'; /** * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 @@ -109,15 +109,15 @@ export class CanvasComponent extends Component { } get visibility () { - if (this._camere) { - return this._camere.view.visibility; + if (this._camera) { + return this._camera.view.visibility; } return -1; } get camera () { - return this._camere; + return this._camera; } public static views = []; @@ -138,8 +138,8 @@ export class CanvasComponent extends Component { private _thisOnResized: Function | null = null; - private _camere: Camera | null = null; - private _cameraInfo: object | null = null; + private _camera: Camera | null = null; + private _cameraInfo: ICameraInfo | null = null; // /** // * !#en Current active canvas, the scene should only have one active canvas at the same time. @@ -194,23 +194,25 @@ export class CanvasComponent extends Component { public onEnable () { this._cameraInfo = { name: 'ui', - clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, node: this.node, - stencil: 0, projection: CameraComponent.ProjectionType.ORTHO, + fov: 45, + stencil: 0, orthoHeight: 10, far: 4096, - near: 0.1, + near: -0.1, + color: cc.color(255, 0, 0, 1), + clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, rect: new Rect(0, 0, 1, 1), - color: cc.color(255, 255, 255, 255), - }; - this._camere = this._getRenderScene().createCamera(this._cameraInfo); + depth: 1 + } as ICameraInfo; + this._camera = this._getRenderScene().createCamera(this._cameraInfo); cc.director.root.ui.addScreen(this); } public onDisable () { - if (this._camere) { - this._getRenderScene().destroyCamera(this._cameraInfo); + if (this._camera) { + this._getRenderScene().destroyCamera(this._camera); cc.director.root.ui.removeScreen(this); } } @@ -243,10 +245,10 @@ export class CanvasComponent extends Component { // public alignWithScreen () { - if (this._camere) { - this._camere.resize(cc.game.canvas.width, cc.game.canvas.height); - this._camere.orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2; - const viewport = this._camere.viewport; + if (this._camera) { + this._camera.resize(cc.game.canvas.width, cc.game.canvas.height); + this._camera.orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2; + const viewport = this._camera.viewport; viewport.x = viewport.y = 0; viewport.width = cc.game.canvas.width; viewport.height = cc.game.canvas.height; diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts index 71d9a1b5fb..b3538ae13f 100644 --- a/cocos/3d/ui/components/editbox/edit-box-component.ts +++ b/cocos/3d/ui/components/editbox/edit-box-component.ts @@ -672,7 +672,7 @@ export class EditBoxComponent extends Component { textLabel.string = displayText; if (this._impl) { this._impl.setString(text); - if (!this._impl._editing && !this.stayOnTop) { + if (!this._impl.editing && !this.stayOnTop) { this._showLabels(); } } diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts index 77d2fa9278..77d91165cc 100644 --- a/cocos/3d/ui/components/editbox/edit-box-impl.ts +++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts @@ -33,8 +33,8 @@ import macro from '../../../../core/platform/CCMacro'; import * as Types from './types'; import * as math from '../../../../core/vmath'; import { Size, Color } from '../../../../core/value-types'; -import { Node } from '../../../../scene-graph'; import { EditBoxComponent} from './edit-box-component'; +import { Node } from '../../../../scene-graph/node'; const InputMode = Types.InputMode; const InputFlag = Types.InputFlag; const KeyboardReturnType = Types.KeyboardReturnType; @@ -50,7 +50,7 @@ let _matrix = cc.mat4(); let _matrix_temp = cc.mat4(); let _vec3 = cc.v3(); -let _currentEditBoxImpl = null; +let _currentEditBoxImpl: EditBoxImpl | null= null; // polyfill let polyfill = { @@ -82,25 +82,61 @@ function getKeyboardReturnType(type) { @ccclass export class EditBoxImpl { - _delegate: EditBoxComponent | null = null; - _inputMode= -1; - _inputFlag= -1; - _returnType= KeyboardReturnType.DEFAULT; - _maxLength= 50; - _text = ''; - _placeholderText = ''; - _alwaysOnTop = false; - _size: Size = cc.size(); - _node: Node = null; - _editing = false; - __eventListeners: object = {}; - __fullscreen = false; - __autoResize = false; - __rotateScreen = false; - __orientationChanged: Function | null = null; - _edTxt: HTMLElement | null = null; - _textColor: Color = Color.WHITE; - _edFontSize = 14; + private _delegate: EditBoxComponent | null = null; + private _inputMode= -1; + private _inputFlag= -1; + private _returnType = KeyboardReturnType.DEFAULT; + private _maxLength= 50; + private _text = ''; + private _placeholderText = ''; + private _alwaysOnTop = false; + private _size: Size = cc.size(); + private _node: Node | null = null; + private _editing = false; + private __eventListeners: any = {}; + private __fullscreen = false; + private __autoResize = false; + private __rotateScreen = false; + private __orientationChanged: any; + private _edTxt: HTMLElement | null = null; + private _textColor: Color = Color.WHITE; + private _edFontSize = 14; + + get text() { + return this._text; + } + + set text(value: string) { + this._text = value; + } + + get textColor() { + return this._textColor; + } + + get fontSize() { + return this._edFontSize; + } + + set returnType(value: Types.KeyboardReturnType) { + this._returnType = value; + } + + get alwayOnTop() { + return this._alwaysOnTop; + } + + set editing(value: boolean) { + this._editing = value; + } + + get delegate() { + return this._delegate; + } + + get eventListeners() { + return this.__eventListeners; + } onEnable() { if (!this._edTxt) { @@ -316,7 +352,7 @@ export class EditBoxImpl { _updateDomInputType() { let inputMode = this._inputMode; - let edTxt = this._edTxt; + let edTxt = this._edTxt as HTMLInputElement; if (!edTxt) return; if (this._inputFlag === InputFlag.PASSWORD) { @@ -356,15 +392,18 @@ export class EditBoxImpl { _updateMatrix() { if (!this._edTxt) return; - let node = this._node, - scaleX = cc.view._scaleX, scaleY = cc.view._scaleY, - viewport = cc.view._viewportRect, - dpr = cc.view._devicePixelRatio; + const node = this._node; + let scaleX = cc.view._scaleX; + let scaleY = cc.view._scaleY; + const viewport = cc.view._viewportRect; + const dpr = cc.view._devicePixelRatio; - node.getWorldMatrix(_matrix); - let contentSize = node._contentSize; - _vec3.x = -node._anchorPoint.x * contentSize.width; - _vec3.y = -node._anchorPoint.y * contentSize.height; + node!.getWorldMatrix(_matrix); + const transform = node!.uiTransfromComp + if (transform) { + _vec3.x = -transform.anchorX.x * transform.width; + _vec3.y = -transform.anchorY.y * transform.height; + } math.mat4.translate(_matrix, _matrix, _vec3); @@ -376,7 +415,7 @@ export class EditBoxImpl { // else { // camera = cc.Camera.findCamera(node); // } - let renderComp = node.getComponent(cc.RenderComponent); + let renderComp = node!.getComponent(cc.RenderComponent); if (!renderComp) { return false; } @@ -422,7 +461,7 @@ export class EditBoxImpl { } _adjustEditBoxPosition() { - this._node.getWorldMatrix(_matrix); + this._node!.getWorldMatrix(_matrix); let y = _matrix.m13; let windowHeight = cc.visibleRect.height; let windowWidth = cc.visibleRect.width; @@ -484,7 +523,9 @@ export class EditBoxImpl { this.__rotateScreen = false; } - window.removeEventListener('orientationchange', this.__orientationChanged); + if (this.__orientationChanged) { + window.removeEventListener('orientationchange', this.__orientationChanged); + } if (this.__fullscreen) { cc.view.enableAutoFullScreen(true); @@ -506,11 +547,11 @@ export class EditBoxImpl { tmpEdTxt.type = 'text'; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = 0; + tmpEdTxt.style.border = '0px'; tmpEdTxt.style.background = 'transparent'; tmpEdTxt.style.width = '100%'; tmpEdTxt.style.height = '100%'; - tmpEdTxt.style.active = 0; + // tmpEdTxt.style.active = 0; tmpEdTxt.style.outline = 'medium'; tmpEdTxt.style.padding = '0'; tmpEdTxt.style.textTransform = 'uppercase'; @@ -519,7 +560,7 @@ export class EditBoxImpl { tmpEdTxt.style.bottom = "0px"; tmpEdTxt.style.left = LEFT_PADDING + "px"; tmpEdTxt.style['-moz-appearance'] = 'textfield'; - tmpEdTxt.style.className = "cocosEditBox"; + tmpEdTxt.className = "cocosEditBox"; tmpEdTxt.style.fontFamily = 'Arial'; registerInputEventListener(tmpEdTxt, this); @@ -531,24 +572,24 @@ export class EditBoxImpl { this.removeDom(); let tmpEdTxt = this._edTxt = document.createElement('textarea'); - tmpEdTxt.type = 'text'; + // tmpEdTxt.type = 'text'; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; tmpEdTxt.style.border = '0'; tmpEdTxt.style.background = 'transparent'; tmpEdTxt.style.width = '100%'; tmpEdTxt.style.height = '100%'; - tmpEdTxt.style.active = 0; + // tmpEdTxt.style.active = 0; tmpEdTxt.style.outline = 'medium'; tmpEdTxt.style.padding = '0'; tmpEdTxt.style.resize = 'none'; tmpEdTxt.style.textTransform = 'uppercase'; - tmpEdTxt.style.overflow_y = 'scroll'; + tmpEdTxt.style.overflowY = 'scroll'; tmpEdTxt.style.display = 'none'; tmpEdTxt.style.position = "absolute"; tmpEdTxt.style.bottom = "0px"; tmpEdTxt.style.left = LEFT_PADDING + "px"; - tmpEdTxt.style.className = "cocosEditBox"; + tmpEdTxt.className = "cocosEditBox"; tmpEdTxt.style.fontFamily = 'Arial'; registerInputEventListener(tmpEdTxt, this, true); @@ -601,7 +642,7 @@ function _inputValueHandle(input, editBoxImpl) { function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) { let inputLock = false; - let cbs = editBoxImpl.__eventListeners; + let cbs = editBoxImpl.eventListeners; cbs.compositionstart = function () { inputLock = true; }; @@ -622,19 +663,19 @@ function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxI tmpEdTxt.addEventListener('input', cbs.input); cbs.focus = function () { - this.style.fontSize = editBoxImpl._edFontSize + 'px'; - this.style.color = editBoxImpl._textColor.toCSS('rgba'); + this.style.fontSize = editBoxImpl.fontSize + 'px'; + this.style.color = editBoxImpl.textColor.toCSS('rgba'); // When stayOnTop, input will swallow touch event - if (editBoxImpl._alwaysOnTop) { - editBoxImpl._editing = true; + if (editBoxImpl.alwayOnTop) { + editBoxImpl.editing = true; } if (cc.sys.isMobile) { editBoxImpl._beginEditingOnMobile(); } - if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingDidBegan) { - editBoxImpl._delegate.editBoxEditingDidBegan(); + if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingDidBegan) { + editBoxImpl.delegate.editBoxEditingDidBegan(); } }; @@ -644,11 +685,11 @@ function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxI if (e.keyCode === macro.KEY.enter) { e.stopPropagation(); - if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingReturn) { - editBoxImpl._delegate.editBoxEditingReturn(); + if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingReturn) { + editBoxImpl.delegate.editBoxEditingReturn(); } if (!isTextarea) { - editBoxImpl._text = this.value; + editBoxImpl.text = this.value; editBoxImpl._endEditing(); cc.game.canvas.focus(); } @@ -657,7 +698,7 @@ function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxI tmpEdTxt.addEventListener('keypress', cbs.keypress); cbs.blur = function () { - editBoxImpl._text = this.value; + editBoxImpl.text = this.value; editBoxImpl._endEditing(); }; tmpEdTxt.addEventListener('blur', cbs.blur); diff --git a/cocos/3d/ui/components/editbox/types.js b/cocos/3d/ui/components/editbox/types.ts similarity index 91% rename from cocos/3d/ui/components/editbox/types.js rename to cocos/3d/ui/components/editbox/types.ts index 88b52a381b..cd78a8ab6e 100644 --- a/cocos/3d/ui/components/editbox/types.js +++ b/cocos/3d/ui/components/editbox/types.ts @@ -28,44 +28,44 @@ * @readonly * @enum EditBox.KeyboardReturnType */ -let KeyboardReturnType = cc.Enum({ +export enum KeyboardReturnType { /** * !#en TODO * !#zh 默认 * @property {Number} DEFAULT */ - DEFAULT: 0, + DEFAULT = 0, /** * !#en TODO * !#zh 完成类型 * @property {Number} DONE */ - DONE: 1, + DONE = 1, /** * !#en TODO * !#zh 发送类型 * @property {Number} SEND */ - SEND: 2, + SEND = 2, /** * !#en TODO * !#zh 搜索类型 * @property {Number} SEARCH */ - SEARCH: 3, + SEARCH = 3, /** * !#en TODO * !#zh 跳转类型 * @property {Number} GO */ - GO: 4, + GO = 4, /** * !#en TODO * !#zh 下一个类型 * @property {Number} NEXT */ - NEXT: 5 -}); + NEXT = 5 +}; /** * !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. @@ -73,37 +73,37 @@ let KeyboardReturnType = cc.Enum({ * @readonly * @enum EditBox.InputMode */ -let InputMode = cc.Enum({ +export enum InputMode { /** * !#en TODO * !#zh 用户可以输入任何文本,包括换行符。 * @property {Number} ANY */ - ANY: 0, + ANY = 0, /** * !#en The user is allowed to enter an e-mail address. * !#zh 允许用户输入一个电子邮件地址。 * @property {Number} EMAIL_ADDR */ - EMAIL_ADDR: 1, + EMAIL_ADDR = 1, /** * !#en The user is allowed to enter an integer value. * !#zh 允许用户输入一个整数值。 * @property {Number} NUMERIC */ - NUMERIC: 2, + NUMERIC = 2, /** * !#en The user is allowed to enter a phone number. * !#zh 允许用户输入一个电话号码。 * @property {Number} PHONE_NUMBER */ - PHONE_NUMBER: 3, + PHONE_NUMBER = 3, /** * !#en The user is allowed to enter a URL. * !#zh 允许用户输入一个 URL。 * @property {Number} URL */ - URL: 4, + URL = 4, /** * !#en * The user is allowed to enter a real number value. @@ -112,14 +112,14 @@ let InputMode = cc.Enum({ * 允许用户输入一个实数。 * @property {Number} DECIMAL */ - DECIMAL: 5, + DECIMAL = 5, /** * !#en The user is allowed to enter any text, except for line breaks. * !#zh 除了换行符以外,用户可以输入任何文本。 * @property {Number} SINGLE_LINE */ - SINGLE_LINE: 6 -}); + SINGLE_LINE = 6 +}; /** * !#en Enum for the EditBox's input flags @@ -127,7 +127,7 @@ let InputMode = cc.Enum({ * @readonly * @enum EditBox.InputFlag */ -let InputFlag = cc.Enum({ +export enum InputFlag { /** * !#en * Indicates that the text entered is confidential data that should be @@ -136,7 +136,7 @@ let InputFlag = cc.Enum({ * 表明输入的文本是保密的数据,任何时候都应该隐藏起来,它隐含了 EDIT_BOX_INPUT_FLAG_SENSITIVE。 * @property {Number} PASSWORD */ - PASSWORD: 0, + PASSWORD = 0, /** * !#en * Indicates that the text entered is sensitive data that the @@ -148,7 +148,7 @@ let InputFlag = cc.Enum({ * 一个信用卡号码就是一个敏感数据的例子。 * @property {Number} SENSITIVE */ - SENSITIVE: 1, + SENSITIVE = 1, /** * !#en * This flag is a hint to the implementation that during text editing, @@ -157,7 +157,7 @@ let InputFlag = cc.Enum({ * 这个标志用来指定在文本编辑的时候,是否把每一个单词的首字母大写。 * @property {Number} INITIAL_CAPS_WORD */ - INITIAL_CAPS_WORD: 2, + INITIAL_CAPS_WORD = 2, /** * !#en * This flag is a hint to the implementation that during text editing, @@ -166,18 +166,17 @@ let InputFlag = cc.Enum({ * 这个标志用来指定在文本编辑是否每个句子的首字母大写。 * @property {Number} INITIAL_CAPS_SENTENCE */ - INITIAL_CAPS_SENTENCE: 3, + INITIAL_CAPS_SENTENCE = 3, /** * !#en Capitalize all characters automatically. * !#zh 自动把输入的所有字符大写。 * @property {Number} INITIAL_CAPS_ALL_CHARACTERS */ - INITIAL_CAPS_ALL_CHARACTERS: 4, + INITIAL_CAPS_ALL_CHARACTERS = 4, /** * Don't do anything with the input text. * @property {Number} DEFAULT */ - DEFAULT: 5 -}); + DEFAULT = 5 +}; -export { KeyboardReturnType, InputMode, InputFlag } diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/3d/ui/components/progress-bar-component.ts index d7607d785a..604d3cf3cc 100644 --- a/cocos/3d/ui/components/progress-bar-component.ts +++ b/cocos/3d/ui/components/progress-bar-component.ts @@ -35,27 +35,27 @@ import { SpriteComponent } from './sprite-component'; * !#zh 进度条模式 * @enum ProgressBar.Mode */ -var Mode = cc.Enum({ +enum Mode { /** * !#en TODO * !#zh 水平方向模式 * @property {Number} HORIZONTAL */ - HORIZONTAL: 0, + HORIZONTAL = 0, /** * !#en TODO * !#zh 垂直方向模式 * @property {Number} VERTICAL */ - VERTICAL: 1, + VERTICAL = 1, /** * !#en TODO * !#zh 填充模式 * @property {Number} FILLED */ - FILLED: 2, -}); + FILLED = 2, +}; /** * !#en @@ -171,7 +171,11 @@ export class ProgressBarComponent extends Component { * !#zh 当前进度值,该数值的区间是 0-1 之间。 * @property {Number} progress */ - @property + @property({ + default: 0.1, + range: [0, 1, 0.1], + slide: true + }) get progress() { return this._progress; } diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index fca5e176d5..c8863f999e 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -38,20 +38,20 @@ import { UITransformComponent } from './ui-transfrom-component'; * !#zh 滑动器方向 * @enum Slider.Direction */ -var Direction = cc.Enum({ +enum Direction { /** * !#en The horizontal direction. * !#zh 水平方向 * @property {Number} Horizontal */ - Horizontal: 0, + Horizontal = 0, /** * !#en The vertical direction. * !#zh 垂直方向 * @property {Number} Vertical */ - Vertical: 1 -}); + Vertical = 1 +}; /** * !#en The Slider Control @@ -124,7 +124,11 @@ export class SliderComponent extends Component { * !#zh 当前进度值,该数值的区间是 0-1 之间 * @property {Number} progress */ - @property + @property({ + default: 0.1, + slide: true, + range: [0.1, 1, 0.01], + }) get progress() { return this._progress; } diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/3d/ui/components/toggle-component.ts index d6a5ead1ed..f91afe63f3 100644 --- a/cocos/3d/ui/components/toggle-component.ts +++ b/cocos/3d/ui/components/toggle-component.ts @@ -25,7 +25,7 @@ ****************************************************************************/ import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import ButtonComponent from './button-component'; +import { ButtonComponent} from './button-component'; import { SpriteComponent} from './sprite-component'; import { ToggleGroupComponent} from './toggle-group-component'; diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts index ceef11cd76..59086ceba9 100644 --- a/cocos/3d/ui/components/widget-component.ts +++ b/cocos/3d/ui/components/widget-component.ts @@ -28,7 +28,7 @@ import WidgetManager from '../../../2d/base-ui/CCWidgetManager'; import { Component} from '../../../components/component'; import { ccclass, property, executeInEditMode, menu, executionOrder } from '../../../core/data/class-decorator'; -import { Node } from '../../../scene-graph/index' +import { Node } from '../../../scene-graph/index'; /** * !#en Enum for Widget's alignment mode, indicating when the widget should refresh. * !#zh Widget 的对齐模式,表示 Widget 应该何时刷新。 @@ -83,7 +83,7 @@ var LEFT_RIGHT = LEFT | RIGHT; @executionOrder(100) @menu('UI/Widget') @executeInEditMode -export default class WidgetComponent extends Component { +export class WidgetComponent extends Component { /** * !#zh: 对齐开关,由 AlignFlags 组成 * @@ -144,7 +144,7 @@ export default class WidgetComponent extends Component { * @default null */ @property({ - type: cc.NodeUI + type: Node }) get target() { return this._target; diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts index cba2d5882e..8a62222931 100644 --- a/cocos/3d/ui/index.ts +++ b/cocos/3d/ui/index.ts @@ -1,30 +1,28 @@ -import { CanvasComponent} from './components/canvas-component'; -import { UIRenderComponent} from './components/ui-render-component'; -import { SpriteComponent} from './components/sprite-component'; -import { UITransformComponent } from './components/ui-transfrom-component'; -// import LabelComponent from './components/label-component'; -// import {UITransformComponent} from './components/ui-transfrom-componentent'; -// import ButtonComponent from './components/button-component'; -// import ToggleGroupComponent from './components/toggle-group-component'; -// import ToggleComponent from './components/toggle-component'; -// import ToggleContainerComponent from './components/toggle-container-component'; -// import SliderComponent from './components/slider-component'; -// import ProgressBarComponent from './components/progress-bar-component'; -// import WidgetComponent from './components/widget-component'; -// import EditBoxComponent from './components/editbox/edit-box-component'; +import { CanvasComponent } from './components/canvas-component'; +import { UIRenderComponent } from './components/ui-render-component'; +import { SpriteComponent } from './components/sprite-component'; +import './components/ui-transfrom-component'; +import { LabelComponent } from './components/label-component'; +import { ButtonComponent } from './components/button-component'; +import { ToggleGroupComponent } from './components/toggle-group-component'; +import { ToggleComponent } from './components/toggle-component'; +import { ToggleContainerComponent } from './components/toggle-container-component'; +import { SliderComponent } from './components/slider-component'; +import { ProgressBarComponent } from './components/progress-bar-component'; +import { WidgetComponent } from './components/widget-component'; +import { EditBoxComponent } from './components/editbox/edit-box-component'; import './assembler/index'; cc.CanvasComponent = CanvasComponent; cc.UIRenderComponent = UIRenderComponent; cc.SpriteComponent = SpriteComponent; -// cc.LabelComponent = LabelComponent; -// cc.UIRectComponent = UIRectComponent; -// cc.ButtonComponent = ButtonComponent; -// cc.ToggleGroupComponent = ToggleGroupComponent; -// cc.ToggleComponent = ToggleComponent; -// cc.ToggleContainerComponent = ToggleContainerComponent; -// cc.SliderComponent = SliderComponent; -// cc.ProgressBarComponent = ProgressBarComponent; -// cc.WidgetComponent = WidgetComponent; -// cc.EditBoxComponent = EditBoxComponent; +cc.LabelComponent = LabelComponent; +cc.ButtonComponent = ButtonComponent; +cc.ToggleGroupComponent = ToggleGroupComponent; +cc.ToggleComponent = ToggleComponent; +cc.ToggleContainerComponent = ToggleContainerComponent; +cc.SliderComponent = SliderComponent; +cc.ProgressBarComponent = ProgressBarComponent; +cc.WidgetComponent = WidgetComponent; +cc.EditBoxComponent = EditBoxComponent; diff --git a/playground/files.js b/playground/files.js index af6dc0f92c..9964bb6342 100644 --- a/playground/files.js +++ b/playground/files.js @@ -1,6 +1,7 @@ window.files = { "aa": [ - "simple" + "simple", + "ui" ], // "animation": [ // "spec-skeleton" diff --git a/playground/ui.html b/playground/ui.html new file mode 100644 index 0000000000..86e62588ee --- /dev/null +++ b/playground/ui.html @@ -0,0 +1,76 @@ + + + + + ui + + + + + + + + + + + + + + + From d1d87270551e202bdc21eaff67c805156f6b9856 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 18:26:13 +0800 Subject: [PATCH 232/267] complete ui render pipeline --- cocos/3d/builtin/init.ts | 10 ++- cocos/core/game.js | 14 --- cocos/core/root.ts | 3 + cocos/gfx/webgl/webgl-commands.ts | 2 + cocos/renderer/ui/ui-material.ts | 2 +- cocos/renderer/ui/ui.ts | 145 ++++++++++++++++++------------ 6 files changed, 104 insertions(+), 72 deletions(-) diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts index df370cfb56..00b3fe7c9d 100644 --- a/cocos/3d/builtin/init.ts +++ b/cocos/3d/builtin/init.ts @@ -1,10 +1,12 @@ import { Asset } from '../../assets/asset'; -import { SpriteFrame} from '../../assets/CCSpriteFrame'; +import { SpriteFrame } from '../../assets/CCSpriteFrame'; import { ImageAsset } from '../../assets/image-asset'; import { Texture2D } from '../../assets/texture-2d'; import { Rect } from '../../core/value-types'; import { GFXDevice } from '../../gfx/device'; +import { EffectAsset } from '../assets/effect-asset'; import { TextureCube } from '../assets/texture-cube'; +import effects from './effects'; class BuiltinResMgr { protected _device: GFXDevice | null = null; @@ -109,6 +111,12 @@ class BuiltinResMgr { spriteFrame.onLoaded(); resources[spriteFrame._uuid] = spriteFrame; + // builtin effects + effects.forEach((e: any) => { + const effect = Object.assign(new EffectAsset(), e); + effect.onLoaded(); + }); + // default material const defaultMtl = new cc.Material(); defaultMtl._uuid = 'default-material'; diff --git a/cocos/core/game.js b/cocos/core/game.js index d593695b04..b1cb8a09e1 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -28,8 +28,6 @@ import EventTarget from './event/event-target'; import inputManager from './platform/event-manager/CCInputManager'; import debug from './platform/CCDebug'; import { addon } from './utils/js'; -import { EffectAsset } from '../3d/assets/effect-asset'; -import { builtinResMgr, effects } from '../3d/builtin'; /** * @module cc @@ -370,8 +368,6 @@ var game = { // Init engine this._initEngine(); - this._initBuiltins(); - // Log engine version console.log('Cocos3D v' + cc.ENGINE_VERSION); @@ -457,12 +453,6 @@ var game = { return; } - // Load builtin effects - effects.map(e => { - let effect = Object.assign(new EffectAsset(), e); - effect.onLoaded(); return effect; - }); - // Load game scripts let jsList = this.config.jsList; if (jsList && jsList.length > 0) { @@ -820,10 +810,6 @@ var game = { this._rendererInitialized = true; }, - _initBuiltins: function() { - builtinResMgr.initBuiltinRes(this._gfxDevice); - }, - _initEvents: function () { var win = window, hiddenPropName; diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 95513d9f41..19183c8b92 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -1,3 +1,4 @@ +import { builtinResMgr } from '../3d/builtin'; import { GFXDevice } from '../gfx/device'; import { GFXWindow, IGFXWindowInfo } from '../gfx/window'; import { ForwardPipeline } from '../pipeline/forward/forward-pipeline'; @@ -92,6 +93,8 @@ export class Root { this._pipeline = pipeline; + builtinResMgr.initBuiltinRes(this._device); + this._ui = new UI(this); if (!this._ui.initialize()) { this.destroy(); diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index ec81e36417..f98af01e5b 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -842,6 +842,7 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLGFXDevice, gpuFrameb gpuFramebuffer.gpuDepthStencilView.baseLevel); } + /* const status = gl.checkFramebufferStatus(WebGLRenderingContext.FRAMEBUFFER); if (status !== WebGLRenderingContext.FRAMEBUFFER_COMPLETE) { switch (status) { @@ -864,6 +865,7 @@ export function WebGLCmdFuncCreateFramebuffer (device: WebGLGFXDevice, gpuFrameb default: } } + */ } } } diff --git a/cocos/renderer/ui/ui-material.ts b/cocos/renderer/ui/ui-material.ts index c9e64ad757..16ce74833c 100644 --- a/cocos/renderer/ui/ui-material.ts +++ b/cocos/renderer/ui/ui-material.ts @@ -35,7 +35,7 @@ export class UIMaterial { public initialize (info: IUIMaterialInfo): boolean { - if (!this._material) { + if (!info.material) { return false; } diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 9df0917ed7..74b2a3cda7 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -1,5 +1,6 @@ import { Material } from '../../3d/assets/material'; +import { builtinResMgr } from '../../3d/builtin'; import RecyclePool from '../../3d/memop/recycle-pool'; import { CanvasComponent } from '../../3d/ui/components/canvas-component'; import { UIRenderComponent } from '../../3d/ui/components/ui-render-component'; @@ -27,17 +28,20 @@ import { RenderScene } from '../scene/render-scene'; import { IUIMaterialInfo, UIMaterial } from './ui-material'; export interface IUIBufferBatch { + vf32: Float32Array; + vui16: Uint16Array; + vbSize: number; + ibSize: number; vb: GFXBuffer; ib: GFXBuffer; ia: GFXInputAssembler; - vf32: Float32Array; - vi16: Int16Array; } export interface IUIDrawBatch { camera: Camera; bufferBatch: IUIBufferBatch; uiMaterial: UIMaterial; + texture: GFXTexture; } export interface IUIRenderData { @@ -91,9 +95,9 @@ export class UI { public initialize () { this._attributes = [ - { name: 'a_color', format: GFXFormat.RGBA32F, binding: 0 }, - { name: 'a_position', format: GFXFormat.RGB32F, binding: 1 }, - { name: 'a_texCoord', format: GFXFormat.RG32F, binding: 2 }, + { name: 'a_color', format: GFXFormat.RGBA32F }, + { name: 'a_position', format: GFXFormat.RGB32F }, + { name: 'a_texCoord', format: GFXFormat.RG32F }, ]; this.createBufferBatch(); @@ -103,15 +107,7 @@ export class UI { type: GFXCommandBufferType.PRIMARY, }); - /* - // create ui material - const material = new Material(); - material.effectName = 'sprite-material'; - // material.setProperty('mainTexture', texture); - // material.update(); - - this._uiMaterial = this.createUIMaterial({ material }); - */ + this._uiMaterial = this.createUIMaterial({ material: builtinResMgr.get('sprite-material')}); return true; } @@ -203,67 +199,98 @@ export class UI { this._renderScreens(); - /* // Merge batch if (this._commitUIRenderDatas.length) { const first = this._commitUIRenderDatas[0]; - let curCamera: Camera = first.camera; - let curTexture: GFXTexture | null = first.texture.getGFXTexture(); - let curBufferBatch: IUIBufferBatch = this._bufferBatches[0]; - let vbOffset = 0; - let ibOffset = 0; - let ibcount = 0; - let vb = curBufferBatch.vb; - let vbBuffer = (vb.buffer as ArrayBuffer); - let lastVF32; + let curCamera: Camera | null = null; + let curTexture: GFXTexture | null = null; + let bufferBatchIdx = 0; + let curBufferBatch: IUIBufferBatch = this._bufferBatches[bufferBatchIdx++]; + let vOffset = 0; + let iOffset = 0; + let isNewBatch = false; for (const uiRenderData of this._commitUIRenderDatas) { - if (ibcount + uiRenderData.meshBuffer.iData!.length < 65535) { - const vf32: Float32Array = uiRenderData.meshBuffer.vData!; - const vbSize = vf32.length * 4 + vbOffset; - if (vbSize > vb.size) { - vb.resize(vbSize); - - vbBuffer = (vb.buffer as ArrayBuffer); - lastVF32 = curBufferBatch.vf32; - curBufferBatch.vf32 = new Float32Array(vbBuffer); - curBufferBatch.vf32.set(lastVF32, 0); + if (iOffset + uiRenderData.meshBuffer.vData!.length > 65535) { + if (bufferBatchIdx >= this._bufferBatches.length) { + this.createBufferBatch(); } - curBufferBatch.vf32.set(vf32, vbOffset); - vbOffset += vf32.length * 4; - - + curBufferBatch = this._bufferBatches[bufferBatchIdx++]; + vOffset = 0; + iOffset = 0; + isNewBatch = true; } else { - + isNewBatch = false; } + // merge vertices + const vf32: Float32Array = uiRenderData.meshBuffer.vData!; + const vbSize = (vf32.length + vOffset) * 4; + if (vbSize > curBufferBatch.vbSize) { + curBufferBatch.vbSize = vbSize; + const lastVF32 = curBufferBatch.vf32; + curBufferBatch.vf32 = new Float32Array(vf32.length + vOffset); + curBufferBatch.vf32.set(lastVF32, 0); + } + + curBufferBatch.vf32.set(vf32, vOffset); + + // merge indices + const vui16: Uint16Array = uiRenderData.meshBuffer.iData!; + const ibSize = (vui16.length + iOffset) * 2; + if (ibSize > curBufferBatch.ibSize) { + curBufferBatch.ibSize = ibSize; + const lastVUI16 = curBufferBatch.vui16; + curBufferBatch.vui16 = new Uint16Array(vui16.length + iOffset); + curBufferBatch.vui16.set(lastVUI16, 0); + } + + for (let n = 0; n < vui16.length; ++n) { + curBufferBatch.vui16[iOffset + n] = vui16[n] + vOffset; + } + + curBufferBatch.vui16.set(vui16, iOffset); + + vOffset += vf32.length; + iOffset += vui16.length; + if (curCamera !== uiRenderData.camera) { - - if (curBufferBatch) { - - if (curBufferBatch.ib!.count + uiRenderData.meshBuffer.iData!.length > 65535) { - - } - } - + isNewBatch = true; curCamera = uiRenderData.camera; + } else if (curTexture !== uiRenderData.texture.getGFXTexture()) { curTexture = uiRenderData.texture.getGFXTexture(); - curBufferBatch = this._drawBatchPool.add(); - - continue; + isNewBatch = true; } - if (curTexture !== uiRenderData.texture.getGFXTexture()) { - curTexture = uiRenderData.texture.getGFXTexture(); + if (isNewBatch) { + const batch = this._drawBatchPool.add(); + batch.camera = curCamera; + batch.bufferBatch = curBufferBatch; + batch.uiMaterial = this._uiMaterial!; + batch.texture = curTexture!; + this._batches.push(batch); } + } // for - // uiRenderData.meshBuffer.iData.length; + // update buffers + for (const bufferBatch of this._bufferBatches) { + if (bufferBatch.vbSize > bufferBatch.vb.size) { + bufferBatch.vb.resize(bufferBatch.vbSize); + } + bufferBatch.vb.update(bufferBatch.vf32); + + if (bufferBatch.ibSize > bufferBatch.ib.size) { + bufferBatch.ib.resize(bufferBatch.ibSize); + } + bufferBatch.ib.update(bufferBatch.vui16); + + bufferBatch.ia.vertexCount = bufferBatch.vf32.length; + bufferBatch.ia.indexCount = bufferBatch.vui16.length; } } - */ } public render () { @@ -354,20 +381,22 @@ export class UI { private createBufferBatch (): IUIBufferBatch { const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; + const vbCount = 128; const vb = this._device.createBuffer({ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: vbStride * 128, + size: vbStride * vbCount, stride: vbStride, }); const ibStride = Uint16Array.BYTES_PER_ELEMENT; + const ibCount = 128; const ib = this._device.createBuffer({ usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: ibStride * 128, + size: ibStride * ibCount, stride: ibStride, }); @@ -381,6 +410,10 @@ export class UI { batch.vb = vb; batch.ib = ib; batch.ia = ia; + batch.vf32 = new Float32Array(vbCount); + batch.vui16 = new Uint16Array(ibCount); + batch.vbSize = vb.size; + batch.ibSize = ib.size; this._bufferBatches.push(batch); return batch; } From e43c1a33209fb8544b52fc3f821771dda9cc224c Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 18:33:46 +0800 Subject: [PATCH 233/267] commit files --- playground/simple.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/playground/simple.html b/playground/simple.html index ed0738541c..443fce465c 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -24,7 +24,7 @@ - + From 8a5a2b9342896edc35a1c29ca62c5f503c4bee0c Mon Sep 17 00:00:00 2001 From: Leslie Date: Wed, 23 Jan 2019 15:24:47 +0800 Subject: [PATCH 234/267] skinning-model-component --- cocos/3d/assets/texture-cube.ts | 2 +- ...{model-component.js => model-component.ts} | 148 +++++----- cocos/3d/framework/renderable-component.ts | 2 +- .../3d/framework/skinning-model-component.js | 253 ------------------ .../3d/framework/skinning-model-component.ts | 238 ++++++++++++++++ cocos/assets/image-asset.ts | 2 +- cocos/assets/texture-2d.ts | 11 +- cocos/assets/texture-base.ts | 35 ++- cocos/gfx/webgl/webgl-commands.ts | 2 + cocos/renderer/index.ts | 2 +- cocos/renderer/models/model-uniforms.ts | 10 +- cocos/renderer/models/skinning-model.js | 35 --- cocos/renderer/models/skinning-model.ts | 52 ++++ 13 files changed, 413 insertions(+), 379 deletions(-) rename cocos/3d/framework/{model-component.js => model-component.ts} (66%) delete mode 100644 cocos/3d/framework/skinning-model-component.js create mode 100644 cocos/3d/framework/skinning-model-component.ts delete mode 100644 cocos/renderer/models/skinning-model.js create mode 100644 cocos/renderer/models/skinning-model.ts diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts index d3a60944bd..22073f3130 100644 --- a/cocos/3d/assets/texture-cube.ts +++ b/cocos/3d/assets/texture-cube.ts @@ -175,7 +175,7 @@ export class TextureCube extends TextureBase { protected _getTextureCreateInfo () { const result = super._getTextureCreateInfo(); result.arrayLayer = 6; - result.flags = result.flags | GFXTextureFlagBit.CUBEMAP; + result.flags = (result.flags || 0) | GFXTextureFlagBit.CUBEMAP; return result; } diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.ts similarity index 66% rename from cocos/3d/framework/model-component.js rename to cocos/3d/framework/model-component.ts index a52e2cd0a5..506c278e90 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.ts @@ -22,12 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { Model } from '../../renderer/scene/model'; -import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator'; -import { Mesh } from '../assets/mesh'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import Enum from '../../core/value-types/enum'; +import { Model } from '../../renderer/scene/model'; +import { Material } from '../assets/material'; +import { Mesh } from '../assets/mesh'; import { RenderableComponent } from './renderable-component'; -import { builtinResMgr } from '../builtin'; /** * !#en Shadow projection mode @@ -36,7 +36,7 @@ import { builtinResMgr } from '../builtin'; * @static * @enum ModelComponent.ShadowCastingMode */ -let ModelShadowCastingMode = Enum({ +const ModelShadowCastingMode = Enum({ /** * !#en * @@ -88,31 +88,20 @@ let ModelShadowCastingMode = Enum({ @executeInEditMode export class ModelComponent extends RenderableComponent { - /** - * @type {Mesh} - */ - @property({ type: Mesh }) - _mesh = null; - - @property({ type: ModelShadowCastingMode }) - _shadowCastingMode = ModelShadowCastingMode.Off; - - @property - _receiveShadows = false; - - static _builtinMaterial = null; - /** * !#en The mesh of the model * * !#ch 模型网格 * @type {Mesh} */ - @property({ type: Mesh }) - get mesh() { + @property({ + type: Mesh, + }) + get mesh () { return this._mesh; } - set mesh(val) { + + set mesh (val) { this._mesh = val; this._updateModels(true); } @@ -123,11 +112,14 @@ export class ModelComponent extends RenderableComponent { * !#ch 投射阴影方式 * @type {Number} */ - @property({ type: ModelShadowCastingMode }) - get shadowCastingMode() { + @property({ + type: ModelShadowCastingMode, + }) + get shadowCastingMode () { return this._shadowCastingMode; } - set shadowCastingMode(val) { + + set shadowCastingMode (val) { this._shadowCastingMode = val; this._updateCastShadow(); } @@ -139,86 +131,108 @@ export class ModelComponent extends RenderableComponent { * @type {Boolean} */ @property - get receiveShadows() { + get receiveShadows () { return this._receiveShadows; } - set receiveShadows(val) { + set receiveShadows (val) { this._receiveShadows = val; this._updateReceiveShadow(); } - static ShadowCastingMode = ModelShadowCastingMode; - - constructor() { - super(); - /** - * @type {Model} - */ - this._model = null; - } - - get model() { + get model () { return this._model; } - onLoad() { + public static ShadowCastingMode = ModelShadowCastingMode; + + protected _model: Model | null = null; + + @property + private _mesh: Mesh | null = null; + + @property + private _shadowCastingMode = ModelShadowCastingMode.Off; + + @property + private _receiveShadows = false; + + constructor () { + super(); + } + + public onLoad () { } - onEnable() { + public onEnable () { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); - if (this._model) { this._model.enabled = true; } + if (this._model) { + this._model.enabled = true; + } } - onDisable() { - if (this._model) { this._model.enabled = false; } + public onDisable () { + if (this._model) { + this._model.enabled = false; + } } - onDestroy() { - this._getRenderScene().destroyModel(this._model); + public onDestroy () { + if (this._model) { + this._getRenderScene().destroyModel(this._model); + } } - _updateModels(forceUpdate) { + protected _updateModels (forceUpdate: boolean = false) { if (!this.enabled || !this.node._scene || !this._mesh || (this._model && !forceUpdate)) { return; } if (this._model) { this._model.destroy(); - } else { - this._model = this._createModel(); + this._model = null; } - this._model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); + this._model = this._createModel(); + + this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._updateModelParams(); } - _createModel() { + protected _createModel () { return this._getRenderScene().createModel(Model, this.node); } - _updateModelParams() { + protected _updateModelParams () { this.node._hasChanged = true; - let meshCount = this._mesh ? this._mesh.subMeshCount : 0; + if (!this._mesh || !this._model) { + return; + } + const meshCount = this._mesh ? this._mesh.subMeshCount : 0; for (let i = 0; i < meshCount; ++i) { - let material = this.getSharedMaterial(i); - let subMeshData = this._mesh.renderingMesh.getSubmesh(i); - this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial()); + const material = this.getSharedMaterial(i); + const renderingMesh = this._mesh.renderingMesh; + if (renderingMesh) { + const subMeshData = renderingMesh.getSubmesh(i); + if (subMeshData) { + this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial()); + } + } } } - _onMaterialModified(idx, material) { + protected _onMaterialModified (idx: number, material: Material | null) { if (this._model == null) { return; } this._model.setSubModelMaterial(idx, material); } - _clearMaterials() { + protected _clearMaterials () { if (this._model == null) { return; } @@ -227,17 +241,18 @@ export class ModelComponent extends RenderableComponent { } } - _updateCastShadow() { - if (!this.enabled || !this._model) + private _updateCastShadow () { + if (!this.enabled || !this._model) { return; + } if (this._shadowCastingMode === ModelShadowCastingMode.Off) { for (let i = 0; i < this._model.subModelNum; ++i) { - let subModel = this._model.getSubModel(i); + const subModel = this._model.getSubModel(i); subModel.castShadow = false; } } else if (this._shadowCastingMode === ModelShadowCastingMode.On) { for (let i = 0; i < this._model.subModelNum; ++i) { - let subModel = this._model.getSubModel(i); + const subModel = this._model.getSubModel(i); subModel.castShadow = true; } } else { @@ -245,19 +260,20 @@ export class ModelComponent extends RenderableComponent { } } - _updateReceiveShadow() { - if (!this.enabled || !this._model) + private _updateReceiveShadow () { + if (!this.enabled || !this._model) { return; + } for (let i = 0; i < this._model.subModelNum; ++i) { - let subModel = this._model.getSubModel(i); + const subModel = this._model.getSubModel(i); // if (subModel._defines['CC_USE_SHADOW_MAP'] != undefined) { // this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); // } } } - _getBuiltinMaterial() { + private _getBuiltinMaterial () { // classic ugly pink indicating missing material - return builtinResMgr.get('default-material'); + return cc.BuiltinResMgr['default-material']; } } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 108e0ed33b..f75ddcc68a 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -103,7 +103,7 @@ export class RenderableComponent extends Component { } - private _clearMaterials () { + protected _clearMaterials () { } } diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js deleted file mode 100644 index 9e1a4cd65c..0000000000 --- a/cocos/3d/framework/skinning-model-component.js +++ /dev/null @@ -1,253 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -// @ts-check -import { mat4 } from '../../core/vmath'; -import { ModelComponent } from './model-component'; -import * as renderer from '../../renderer/index'; -import { ccclass, property, executionOrder, menu,executeInEditMode } from '../../core/data/class-decorator'; -import * as utils from '../misc/utils'; -import Skeleton from '../assets/skeleton'; -import { Node } from '../../scene-graph/node'; - -/** - * @typedef {import("../framework/skeleton-instance").default} SkeletonInstance - */ -let _m4_tmp = mat4.create(); - -/** - * !#en The Skinning Model Component - * - * !#ch 皮肤模型组件 - * @class SkinningModelComponent - * @extends ModelComponent - */ -@ccclass('cc.SkinningModelComponent') -@executionOrder(100) -@executeInEditMode -@menu('Components/SkinningModelComponent') -export default class SkinningModelComponent extends ModelComponent { - /** - * @type {Skeleton} - */ - @property(Skeleton) - _skeleton = null; - - /** - * @type {Node} - */ - @property(Node) - _skinningRoot = null; - - constructor() { - super(); - - /** - * @type {Map} - */ - this._skinningTarget = null; - - /** - * @type {import("../../renderer/gfx/texture-2d").default} - */ - this._jointsTexture = null; - - /** - * @type {Float32Array} - */ - this._jointMatricesData = null; - } - - /** - * !#en The bone nodes - * - * !#ch 骨骼节点 - * @type {Skeleton} - */ - @property({type: Skeleton}) - get skeleton() { - return this._skeleton; - } - - set skeleton(val) { - this._skeleton = val; - } - - @property({type: Node}) - get skinningRoot() { - return this._skinningRoot; - } - - set skinningRoot(value) { - this._skinningRoot = value; - this._resetTarget(); - } - - onLoad() { - this._resetTarget(); - this._reInitJointsData(); - this._updateModels(); - this._updateCastShadow(); - this._updateReceiveShadow(); - } - - update(dt) { - this._updateMatrices(); - } - - - onDestroy() { - } - - _updateMatrices() { - if (!this._mesh || !this._skeleton || !this._skinningTarget) { - return; - } - - // /** @type {import("../assets/utils/gltf-utils").GltfMeshResource} */ - // const res = this._mesh.resource; - // const gltf = res.gltfAsset.description; - - // /** @type {Node[]} */ - // const nodes = []; - // gltf.nodes.forEach((gltfNode, index) => nodes[index] = createNode(gltfNode)); - // gltf.nodes.forEach((gltfNode, index) => { - // if (gltfNode.children) { - // const node = nodes[index]; - // gltfNode.children.forEach((childIndex) => { - // nodes[childIndex].setParent(node); - // }); - // } - // }); - - const cancelThisNoTransform = this.node.getWorldMatrix(); - mat4.invert(cancelThisNoTransform, cancelThisNoTransform); - - this._skeleton.joints.forEach((joint, index) => { - // const debugNode = nodes[this._skeleton._debugjoints[index]]; - // let wm = debugNode.getWorldMatrix(); - - const targetNode = this._skinningTarget.get(joint); - if (!targetNode) { - return; - } - const bindpose = this._skeleton.bindposes[index]; - - // 1. transform mesh to joint's local space - // 2. transform from joint' local space to world space - // 3. because it has been in world space, just cancel this mesh's original local-world transform - const jointMatrix = _m4_tmp; - mat4.multiply(jointMatrix, cancelThisNoTransform, targetNode.getWorldMatrix()); - mat4.multiply(jointMatrix, jointMatrix, bindpose); - this._setJointMatrix(index, jointMatrix); - }); - - this._commitJointsData(); - } - - _createModel() { - return new renderer.SkinningModel(); - } - - _updateModelParams() { - super._updateModelParams(); - for (let i = 0; i < this._models.length; ++i) - this._updateModelJointParam(this._models[i]); - } - - _reInitJointsData() { - if (this._jointsTexture) { - this._jointsTexture.destroy(); - } - - if (!this._skeleton) { - this._jointMatricesData = null; - return; - } - - if (cc.game._gfxDevice.allowFloatTexture()) { - this._jointsTexture = utils.createJointsTexture(this._skeleton); - this._jointMatricesData = new Float32Array(this._jointsTexture._width * this._jointsTexture._height * 4); - } else { - this._jointMatricesData = new Float32Array(this._skeleton.joints.length * 16); - } - } - - _commitJointsData() { - if (this._jointsTexture != null) { - this._jointsTexture.updateImage({ - image: this._jointMatricesData, - width: this._jointsTexture._width, - height: this._jointsTexture._height, - level: 0, - flipY: false, - premultiplyAlpha: false - }); - } - } - - _updateModelJointParam(model) { - if (this._jointsTexture != null) { - model.setJointsTexture(this._jointsTexture); - } else { - model.setJointsMatrixArray(this._jointMatricesData); - } - } - - _setJointMatrix(iMatrix, matrix) { - this._jointMatricesData[16 * iMatrix + 0] = matrix.m00; - this._jointMatricesData[16 * iMatrix + 1] = matrix.m01; - this._jointMatricesData[16 * iMatrix + 2] = matrix.m02; - this._jointMatricesData[16 * iMatrix + 3] = matrix.m03; - this._jointMatricesData[16 * iMatrix + 4] = matrix.m04; - this._jointMatricesData[16 * iMatrix + 5] = matrix.m05; - this._jointMatricesData[16 * iMatrix + 6] = matrix.m06; - this._jointMatricesData[16 * iMatrix + 7] = matrix.m07; - this._jointMatricesData[16 * iMatrix + 8] = matrix.m08; - this._jointMatricesData[16 * iMatrix + 9] = matrix.m09; - this._jointMatricesData[16 * iMatrix + 10] = matrix.m10; - this._jointMatricesData[16 * iMatrix + 11] = matrix.m11; - this._jointMatricesData[16 * iMatrix + 12] = matrix.m12; - this._jointMatricesData[16 * iMatrix + 13] = matrix.m13; - this._jointMatricesData[16 * iMatrix + 14] = matrix.m14; - this._jointMatricesData[16 * iMatrix + 15] = matrix.m15; - } - - _resetTarget() { - this._skinningTarget = new Map(); - if (!this._skeleton || !this._skinningRoot) { - return; - } - const rootNode = this._skinningRoot; - this._skeleton.joints.forEach(joint => { - const targetNode = rootNode.getChildByPath(joint); - if (!targetNode) { - console.warn(`Skinning target ${joint} not found in scene graph.`); - return; - } - this._skinningTarget.set(joint, targetNode); - }); - } -} diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts new file mode 100644 index 0000000000..1f80f29aeb --- /dev/null +++ b/cocos/3d/framework/skinning-model-component.ts @@ -0,0 +1,238 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +// @ts-check +import { Texture2D } from '../../assets/texture-2d'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { mat4 } from '../../core/vmath'; +import { GFXDevice, GFXFeature } from '../../gfx/device'; +import { SkinningModel } from '../../renderer/models/skinning-model'; +import { Node } from '../../scene-graph/node'; +import Skeleton from '../assets/skeleton'; +import * as utils from '../misc/utils'; +import { ModelComponent } from './model-component'; + +const _m4_tmp = mat4.create(); + +interface IJointTextureStorage { + nativeData: Float32Array; + texture: Texture2D; +} + +interface IJointUniformsStorage { + nativeData: Float32Array; +} + +type JointStorage = IJointTextureStorage | IJointUniformsStorage; + +interface ISkinningState { + skinningTarget: Map; + storage: JointStorage; +} + +function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { + return (storage as any).texture !== undefined; +} + +/** + * !#en The Skinning Model Component + * !#ch 皮肤模型组件 + */ +@ccclass('cc.SkinningModelComponent') +@executionOrder(100) +@executeInEditMode +@menu('Components/SkinningModelComponent') +export default class SkinningModelComponent extends ModelComponent { + @property(Skeleton) + private _skeleton: Skeleton | null = null; + + @property(Node) + private _skinningRoot: Node | null = null; + + private _skinningState: ISkinningState | null = null; + + constructor () { + super(); + } + + /** + * !#en The bone nodes + * + * !#ch 骨骼节点 + */ + @property({type: Skeleton}) + get skeleton () { + return this._skeleton; + } + + set skeleton (val) { + this._skeleton = val; + this._resetSkinningState(); + } + + @property({type: Node}) + get skinningRoot () { + return this._skinningRoot; + } + + set skinningRoot (value) { + this._skinningRoot = value; + this._resetSkinningState(); + } + + public onLoad () { + this._resetSkinningState(); + } + + public update (dt) { + this._tryUpdateMatrices(); + } + + public onDestroy () { + } + + public _tryUpdateMatrices () { + if (!this._skeleton || !this._skinningState) { + return; + } + + const skinningState = this._skinningState!; + const skeleton = this._skeleton!; + + const cancelThisNodeTransform = this.node.getWorldMatrix(); + mat4.invert(cancelThisNodeTransform, cancelThisNodeTransform); + + this._skeleton.joints.forEach((joint, index) => { + // If target joint doesn't exists in scene graph, skip it. + const targetNode = skinningState.skinningTarget.get(joint); + if (!targetNode) { + return; + } + // 1. transform mesh to joint's local space + // 2. transform from joint' local space to world space + // 3. because it has been in world space, just cancel this mesh's original local-world transform + const bindpose = skeleton.bindposes[index]; + const jointMatrix = _m4_tmp; + mat4.multiply(jointMatrix, cancelThisNodeTransform, targetNode.getWorldMatrix()); + mat4.multiply(jointMatrix, jointMatrix, bindpose); + _setJointMatrix(skinningState.storage.nativeData, index, jointMatrix); + }); + + const storage = skinningState.storage; + if (isTextureStorage(storage)) { + storage.texture.directUpdate(storage.nativeData.buffer); + } + } + + public _createModel () { + return this._getRenderScene().createModel(SkinningModel, this.node); + } + + public _updateModelParams () { + super._updateModelParams(); + // Upload joint matrices. + if (this._skinningState !== null) { + const skinningState = this._skinningState; + const skinningModel = this._model as SkinningModel; + if (isTextureStorage(skinningState.storage)) { + const texture = skinningState.storage.texture; + skinningModel.setJointTexture(texture); + } else { + skinningModel.setJointMatrices(skinningState.storage.nativeData); + } + } + } + + private _resetSkinningState () { + if (this._skinningState) { + if (isTextureStorage(this._skinningState.storage)) { + this._skinningState.storage.texture.destroy(); + } + this._skinningState = null; + } + + if (!this._skeleton || !this._skinningRoot) { + return; + } + + let storage: JointStorage; + + // Allocate joint matrices storage. + const device = _getGlobalDevice(); + if (device && device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { + const jointsTexture = utils.createJointsTexture(this._skeleton); + storage = { + texture: jointsTexture, + nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), + } as IJointTextureStorage; + } else { + storage = { + nativeData: new Float32Array(this._skeleton.joints.length * 16), + } as IJointUniformsStorage; + } + + const skinningState: ISkinningState = { + skinningTarget: new Map(), + storage, + }; + + // Collect target to skin. + const rootNode = this._skinningRoot; + this._skeleton.joints.forEach((joint) => { + const targetNode = rootNode.getChildByPath(joint); + if (!targetNode) { + console.warn(`Skinning target ${joint} not found in scene graph.`); + return; + } + skinningState.skinningTarget.set(joint, targetNode); + }); + + this._skinningState = skinningState; + } +} + +function _getGlobalDevice (): GFXDevice | null { + // @ts-ignore + return cc.director.root.device; +} + +function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { + out[16 * iMatrix + 0] = matrix.m00; + out[16 * iMatrix + 1] = matrix.m01; + out[16 * iMatrix + 2] = matrix.m02; + out[16 * iMatrix + 3] = matrix.m03; + out[16 * iMatrix + 4] = matrix.m04; + out[16 * iMatrix + 5] = matrix.m05; + out[16 * iMatrix + 6] = matrix.m06; + out[16 * iMatrix + 7] = matrix.m07; + out[16 * iMatrix + 8] = matrix.m08; + out[16 * iMatrix + 9] = matrix.m09; + out[16 * iMatrix + 10] = matrix.m10; + out[16 * iMatrix + 11] = matrix.m11; + out[16 * iMatrix + 12] = matrix.m12; + out[16 * iMatrix + 13] = matrix.m13; + out[16 * iMatrix + 14] = matrix.m14; + out[16 * iMatrix + 15] = matrix.m15; +} diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts index 5cb4c4f2aa..708fc1c0ed 100644 --- a/cocos/assets/image-asset.ts +++ b/cocos/assets/image-asset.ts @@ -36,7 +36,7 @@ export interface IMemoryImageSource { format: number; } -type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource; +export type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource; /** * Class ImageAsset. diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts index 95c03611b9..d5a5afd186 100644 --- a/cocos/assets/texture-2d.ts +++ b/cocos/assets/texture-2d.ts @@ -25,7 +25,7 @@ ****************************************************************************/ // @ts-check import { ccclass, property } from '../core/data/class-decorator'; -import { ImageAsset } from './image-asset'; +import { ImageAsset, ImageSource } from './image-asset'; import { TextureBase } from './texture-base'; /** @@ -93,14 +93,13 @@ export class Texture2D extends TextureBase { /** * Updates mipmaps at specified range of levels. - * @param sources The image sources. * @param firstLevel The first level from which the sources update. * @description * If the range specified by [firstLevel, firstLevel + sources.length) exceeds * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated. * Use this method if your mipmap data are modified. */ - public updateMipmaps (firstLevel: number, count?: number) { + public updateMipmaps (firstLevel: number = 0, count?: number) { if (firstLevel >= this._mipmaps.length) { return; } @@ -111,10 +110,14 @@ export class Texture2D extends TextureBase { for (let i = 0; i < nUpdate; ++i) { const level = firstLevel + i; - this._uploadImage(this._mipmaps[level], level); + this._assignImage(this._mipmaps[level], level); } } + public directUpdate (source: HTMLImageElement | HTMLCanvasElement | ArrayBuffer, level: number = 0) { + this._uploadData(source, level); + } + /** * !#en * HTMLElement Object getter, available only on web. diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts index 87406f1567..5f8812de9e 100644 --- a/cocos/assets/texture-base.ts +++ b/cocos/assets/texture-base.ts @@ -36,7 +36,7 @@ import { GFXSampler } from '../gfx/sampler'; import { GFXTexture, IGFXTextureInfo } from '../gfx/texture'; import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view'; import { Asset } from './asset'; -import { ImageAsset } from './image-asset'; +import { ImageAsset, ImageSource } from './image-asset'; const CHAR_CODE_1 = 49; // '1' @@ -243,6 +243,7 @@ export class TextureBase extends Asset { protected constructor (flipY: boolean = false) { super(); + // @ts-ignore EventTarget.call(this); this._flipY = flipY; @@ -266,7 +267,7 @@ export class TextureBase extends Asset { this._potientialWidth = width; this._potientialHeight = height; this._format = format; - this._mipmapLevel = 1; + this._mipmapLevel = mipmapLevel; this._updateSampler(); this._recreateTexture(); } @@ -495,7 +496,18 @@ export class TextureBase extends Asset { } protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) { - const upload = () => { this._uploadImage(image, level, arrayIndex); }; + const upload = () => { + if (!image.data) { + return; + } + let source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer; + if (image.data instanceof HTMLElement) { + source = image.data; + } else { + source = image.data.buffer; + } + this._uploadData(source, level, arrayIndex); + }; // @ts-ignore if (image.loaded) { upload(); @@ -507,7 +519,8 @@ export class TextureBase extends Asset { } } - protected _uploadImage (image: ImageAsset, level: number, arrayIndex?: number) { + protected _uploadData ( + source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer, level: number, arrayIndex?: number) { if (!this._texture) { return; } @@ -516,11 +529,6 @@ export class TextureBase extends Asset { return; } - const data = image.data; - if (!data) { - return; - } - const gfxDevice = this._getGlobalDevice(); if (!gfxDevice) { return; @@ -548,10 +556,10 @@ export class TextureBase extends Asset { }, }; - if (data instanceof HTMLElement) { - gfxDevice.copyImageSourceToTexture(data, this._texture, [region]); + if (source instanceof HTMLElement) { + gfxDevice.copyImageSourceToTexture(source, this._texture, [region]); } else { - gfxDevice.copyBufferToTexture(data.buffer, this._texture, [region]); + gfxDevice.copyBufferToTexture(source, this._texture, [region]); } } @@ -621,7 +629,8 @@ export class TextureBase extends Asset { } } -cc.TextureBase = TextureBase; +/* tslint:disable:no-string-literal */ +cc['TextureBase'] = TextureBase; /** * !#zh diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index ec81e36417..2cfe05d36e 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -151,6 +151,7 @@ function GFXFormatToWebGLInternalFormat (format: GFXFormat): GLenum { case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; case GFXFormat.RGB8: return WebGLRenderingContext.RGB; case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA32F: return WebGLRenderingContext.RGBA; case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB565; case GFXFormat.RGB5A1: return WebGLRenderingContext.RGB5_A1; case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA4; @@ -191,6 +192,7 @@ function GFXFormatToWebGLFormat (format: GFXFormat): GLenum { case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; case GFXFormat.RGB8: return WebGLRenderingContext.RGB; case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA32F: return WebGLRenderingContext.RGBA; case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB; case GFXFormat.RGB5A1: return WebGLRenderingContext.RGBA; case GFXFormat.RGBA4: return WebGLRenderingContext.RGBA; diff --git a/cocos/renderer/index.ts b/cocos/renderer/index.ts index 4a5e1eac1b..b1cd8bc636 100644 --- a/cocos/renderer/index.ts +++ b/cocos/renderer/index.ts @@ -15,4 +15,4 @@ export { Model } from './scene/model'; export { default as LineBatchModel } from './models/line-batch-model'; export { default as SpriteBatchModel } from './models/sprite-batch-model'; export { default as ParticleBatchModel } from './models/particle-batch-model'; -export { default as SkinningModel } from './models/skinning-model'; +export { SkinningModel } from './models/skinning-model'; diff --git a/cocos/renderer/models/model-uniforms.ts b/cocos/renderer/models/model-uniforms.ts index b28f62485a..16ef5e976f 100644 --- a/cocos/renderer/models/model-uniforms.ts +++ b/cocos/renderer/models/model-uniforms.ts @@ -1,10 +1,10 @@ import { GFXType } from '../../gfx/define'; -import { GFXUniformBlock } from '../../gfx/shader'; +import { GFXUniformBlock, GFXUniformSampler } from '../../gfx/shader'; export class SkinningUBO { public static MAT_JOINT_OFFSET: number = 0; - public static JOINTS_TEXTURE_SIZE_OFFSET: number = SkinningUBO.MAT_JOINT_OFFSET + 128 * 4; - public static COUNT: number = SkinningUBO.MAT_JOINT_OFFSET + 4; + public static JOINTS_TEXTURE_SIZE_OFFSET: number = SkinningUBO.MAT_JOINT_OFFSET + 128 * 16; + public static COUNT: number = SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET + 4; public static SIZE: number = SkinningUBO.COUNT * 4; public static BLOCK: GFXUniformBlock = { @@ -14,5 +14,7 @@ export class SkinningUBO { ], }; - // public view: Float32Array = new Float32Array(SkinningUBO.COUNT); + public static JOINT_TEXTURE: GFXUniformSampler = { + binding: 28, name: 'CCJointTexture', type: GFXType.SAMPLER2D, count: 1, + }; } diff --git a/cocos/renderer/models/skinning-model.js b/cocos/renderer/models/skinning-model.js deleted file mode 100644 index 53a8af9c92..0000000000 --- a/cocos/renderer/models/skinning-model.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - -import { Model } from '../scene/model'; -import { SkinningUBO } from './model-uniforms'; -import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; - -export default class SkinningModel extends Model { - constructor() { - super(); - - this._type = 'skinning'; - this._jointsTexture = null; - this._jointsMatrixArray = null; - } - - setJointsTexture(texture) { - this._jointsTexture = texture; - } - - setJointsMatrixArray(a) { - this._jointsMatrixArray = a; - this._skinningUBO = this._device.createBuffer({ - usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, - memUsage: GFXMemoryUsageBit.HOST, - size: SkinningUBO.SIZE, - stride: SkinningUBO.SIZE, - }); - this._skinningUBO.update(this._jointsMatrixArray); - } - - _onCreatePSO(pso) { - super._onCreatePSO(pso); - pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); - } -} diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts new file mode 100644 index 0000000000..95a7a179d2 --- /dev/null +++ b/cocos/renderer/models/skinning-model.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + +import { Texture2D } from '../../assets/texture-2d'; +import { GFXBuffer } from '../../gfx/buffer'; +import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXPipelineState } from '../../gfx/pipeline-state'; +import { Node } from '../../scene-graph/node'; +import { Model } from '../scene/model'; +import { RenderScene } from '../scene/render-scene'; +import { SkinningUBO } from './model-uniforms'; + +const textureSizeBuffer = new Float32Array(4); + +export class SkinningModel extends Model { + private _skinningUBO: GFXBuffer; + private _jointTexture: Texture2D | null = null; + + constructor (scene: RenderScene, node: Node) { + super(scene, node); + this._type = 'skinning'; + this._skinningUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST, + size: SkinningUBO.SIZE, + stride: SkinningUBO.SIZE, + }); + } + + public setJointTexture (texture: Texture2D) { + this._jointTexture = texture; + textureSizeBuffer[0] = texture.width; + this._skinningUBO.update( + textureSizeBuffer, SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET, textureSizeBuffer.byteLength); + } + + public setJointMatrices (data: Float32Array) { + this._skinningUBO.update(data, SkinningUBO.MAT_JOINT_OFFSET); + } + + protected _onCreatePSO (pso: GFXPipelineState) { + super._onCreatePSO(pso); + pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); + if (this._jointTexture) { + const view = this._jointTexture.getGFXTextureView(); + const sampler = this._jointTexture.getGFXSampler(); + if (view && sampler) { + pso.pipelineLayout.layouts[0].bindTextureView(SkinningUBO.JOINT_TEXTURE.binding, view); + pso.pipelineLayout.layouts[0].bindSampler(SkinningUBO.JOINT_TEXTURE.binding, sampler); + } + } + } +} From dc0de128b035b63a2f79cdf5f666b93d9c33c5dc Mon Sep 17 00:00:00 2001 From: Leslie Date: Wed, 23 Jan 2019 15:26:24 +0800 Subject: [PATCH 235/267] ignore package-lock.json --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0dd9da6758..d57d13d67d 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ node_modules npm-debug.log DebugInfos.json /rollup/out +/package-lock.json From 7e6c5dc81e8b253f8ba6684fc26cf6f5905913a7 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Wed, 23 Jan 2019 18:59:48 +0800 Subject: [PATCH 236/267] commit files --- cocos/gfx/webgl/webgl-commands.ts | 14 ++++++++++---- playground/cocos2d-x.png | Bin 0 -> 20990 bytes playground/simple.html | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) create mode 100644 playground/cocos2d-x.png diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index bcca67549f..7b98f5bdb7 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -47,7 +47,7 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; case GFXFormat.R8UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.R8I: return WebGLRenderingContext.INT; - case GFXFormat.R16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.R16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; case GFXFormat.R16UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.R16I: return WebGLRenderingContext.INT; case GFXFormat.R32F: return WebGLRenderingContext.FLOAT; @@ -58,7 +58,7 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu case GFXFormat.RG8SN: return WebGLRenderingContext.BYTE; case GFXFormat.RG8UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RG8I: return WebGLRenderingContext.INT; - case GFXFormat.RG16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RG16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; case GFXFormat.RG16UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RG16I: return WebGLRenderingContext.INT; case GFXFormat.RG32F: return WebGLRenderingContext.FLOAT; @@ -70,7 +70,7 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu case GFXFormat.RGB8SN: return WebGLRenderingContext.BYTE; case GFXFormat.RGB8UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RGB8I: return WebGLRenderingContext.INT; - case GFXFormat.RGB16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGB16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; case GFXFormat.RGB16UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RGB16I: return WebGLRenderingContext.INT; case GFXFormat.RGB32F: return WebGLRenderingContext.FLOAT; @@ -82,7 +82,7 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu case GFXFormat.RGBA8SN: return WebGLRenderingContext.BYTE; case GFXFormat.RGBA8UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RGBA8I: return WebGLRenderingContext.INT; - case GFXFormat.RGBA16F: return WebGLRenderingContext.FLOAT; + case GFXFormat.RGBA16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; case GFXFormat.RGBA16UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RGBA16I: return WebGLRenderingContext.INT; case GFXFormat.RGBA32F: return WebGLRenderingContext.FLOAT; @@ -150,7 +150,10 @@ function GFXFormatToWebGLInternalFormat (format: GFXFormat): GLenum { case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; case GFXFormat.RGB8: return WebGLRenderingContext.RGB; + case GFXFormat.RGB16F: return WebGLRenderingContext.RGB; + case GFXFormat.RGB32F: return WebGLRenderingContext.RGB; case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA16F: return WebGLRenderingContext.RGBA; case GFXFormat.RGBA32F: return WebGLRenderingContext.RGBA; case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB565; case GFXFormat.RGB5A1: return WebGLRenderingContext.RGB5_A1; @@ -191,7 +194,10 @@ function GFXFormatToWebGLFormat (format: GFXFormat): GLenum { case GFXFormat.L8: return WebGLRenderingContext.LUMINANCE; case GFXFormat.LA8: return WebGLRenderingContext.LUMINANCE_ALPHA; case GFXFormat.RGB8: return WebGLRenderingContext.RGB; + case GFXFormat.RGB16F: return WebGLRenderingContext.RGB; + case GFXFormat.RGB32F: return WebGLRenderingContext.RGB; case GFXFormat.RGBA8: return WebGLRenderingContext.RGBA; + case GFXFormat.RGBA16F: return WebGLRenderingContext.RGBA; case GFXFormat.RGBA32F: return WebGLRenderingContext.RGBA; case GFXFormat.R5G6B5: return WebGLRenderingContext.RGB; case GFXFormat.RGB5A1: return WebGLRenderingContext.RGBA; diff --git a/playground/cocos2d-x.png b/playground/cocos2d-x.png new file mode 100644 index 0000000000000000000000000000000000000000..6a78452419e26f0a5f61d70758c29395665abe47 GIT binary patch literal 20990 zcmbTdV{~P~w=cS5+qP|U$5zKlC)u%W+crA3ZQJN{>`uq%*y)%5x#!&XKHPCXyfwyJ zg*8>P>Ni%^s##GgO43O1`0xM#07+IxLhUQf{JNK5p}(GOU~mjy37)H@wyU~>xvPh< zvl&3l)WO7zRMyVe!c5J~*wo8u(o7HlfN-+X(00{URNx0W*fAUbhlbhH&hd*I01y=M zbTkIpn7NXgm|0la3z1)U_mh)anF^6>aVfGYIs(lstz^8N&D6b>G(g@qAU;!a5n)n6 zPyR0fc4n@|q@H%R_AdOMLgfD?m;WpOpK2Cz(*GiHwGkr!Uq)#ws*nO5oXtqNn7Noh ztZba5JbcV-Tx^`YY>cGrtZW=CtQ;(C987HN{H%QZY+R)OeUX1@b2c^SSCf$XZ(Uy{ zA#zJsS4Vyp77q^(W)BW#2WJZwHaNH&-F@FH8Sd6YLxn75}$jdzb%q)R)UxJdGV$*qB*a?Ck#2uK%KT zaaA+>f6e$mQoCq)IhwJknYlQ)IfK6X!<^!On7@4Ye^>M$!Y^z1m7T4=I>p#l!U5!F zXJ+pzDh$2Q-YP9i-(t!jZKnUOj43poQ<7}gO{C;56C9*KfJQ`F0RJ*AhZ9`ZS|%5 zzj@jIue|&~XES402WJfj2iyM{1uB*ft`07i4vwTiAStbumA$EhhYQ_*dgy;OSi;QN z%H7OV%Gtq=^uJupZ}opr&&9#Y#m!;P%VcV9Zp_3B;{1BBnR795aqyY3vvRTXm~wKE z|2Mzs|6kX!d>O^^pKlw`EVf;myV>@OEvGMZo>q5rao%;G@HLpPz@}NrzgSlq z3B491Q35G`3dbF995u^tEJf88Ytn0aQwz*weC;8USn|n!%1VF`evLq4XT#UG#uT*{t`8?Xn&Em#~%rNQgmFYC^E!{dB<(ApYEi>n1 zUgJTnwHJ^T7*c2osj|@yR8fM+t+CqGLy4E6^o|_AA1dUJqQ`+byz)tRKDFkDO4MP};Ps$jR26H!Q zTP$Ma+*L7h<_%V3v&-SMLPup%|MVaS+oyzFKblo>{CqJ78c4iG6rrO+t-&pq1sWaW zn^j2ta7Ewpd)jUTga=A!M!B<7O~}Dc_}}kGu)ao!a1va(E{V_xaltoW6c-A?Q#}Y4 zv()$8%E1>bEvfwkTiCN+URqi*8VZH00>L(klV@x{Zn>~N6h_R1=Sshp?_wwBO#r$@ z^(QckS+2XUg+2eIX_0bsW3SZcP>@Lb;1FkM8!0Nr(E%1?3r*A3&?h=|LX)@e&%Y1X z(EMP{A+Uxg@grFK69vz@<^R~0q%zyY`2L&ZU!ch6O+xDE<$5#B#>U3sbq2Emyq19* zR?pj2_cEoiX`M=ZSQ!FUbtJbWYR zIQ-ILXIaP&!K7bx-4B|MR8)hn=XD$@liZ1)JWGBwfFG>BRye0HEdU0xkNy%CLDgN# z5-FLqIsS7-b+XUZ(Aq*If) z8#~=_z#GPCjIybt-|J~PtHX}qwuhy}$1usK=szh(t5)&K*=(*Da2W()tX4Ut@Rb!! z$L{T}YZExPyQ9N_5_RRU^ez30m%qaf5EFmx6ig*c@)q{8IV|GYh;UlRe=3U*F?XF5 z6@Z{P#^mf??@z-?P2c@xD5Av`ENJxo-Y!`$J^Di&WV^xhr5@YS^w9@YAbj6%#wncV zDamITwq@wK&mP1#ULR05S7CTQ&$L*DBb}Zgt=DNvvcREUJ$AfkXgeAT-93kqcm`te zILO@{TH<7nkchA-n}~xM!&O>H1YamI4g6o=5?DF+{?epwkDi9M@A?xk_xv3yI8MvR zP|rUo1V$7TkTy-a($mu$-5t%A?LHwBKohwfi!;2u)gMw>zPz4eU>ng8LcJY}{KG@n zM}H8v@h=$+vwQx#pO|fZ1s7di7k;?iO&0R*H(jQfC_0w_e!*+mPu?_(;{O*y{+L+U zHxt}ebPYV|yi5Vk{y~-$-iFP0xGL7lZJ!sa{!C7K5a;jo| z@>{>t*=)h(UEhPIN84&vZnewe%;}wy#o9jVMRu*{5>=BwhtUcZ7Qe|NrA05nb=#$M`hFD+V z4>-!Q5SNyYxU`{BLd+wfYO6y|j#LN-A4gIahFgcO>FzH=JR^Sba-{#cj{FeN6Cj!o zWddkK^$N`Mn`8sinvZ8%xPSkS)bI0!iAn;C0)kii{?{`G-nWZpyAZ^@7-ZO*m-G7maCw$q%vU(Q7)~sR9}&xnIe|CcmF3UqDWv1CB0_+j zY`Nj-QdSt7lBNY~_JPWt^{pS*JCC_U;NUaid+9H%IPBP$#B&k`VF@RqWay z#RJ8?QTlBfnnHi~J+p@jhpo1{HEgb!XP72wM0FjS%xoq-5l=IS^xh zcT4;6?P?pWw*E86I?i%T1+1Yz!7}ffNE-0lv+5Mlbhy3g6Xl=9^EN0!7@BXLZy?1B z(LCT<$T*3W_U5Yl3Oe0*Upe3%5C6ra5$Y2rfa*o=%`Td$d-eaVC0Eo1aQxorz-(2*c4YP1W# zr}r6J8hi#fB00@-Td#}Q1H!9VSRQ2{W_MS_Ay@nHt>ctG9_qmdu%1X_<1bLQh3Xmg zq$(`huHHzty=VmGL?55}KW1+;8zthWX=;|}v0Q%r61&(R4n8#*3^wXy38%zrMr4Jj zr@S*MrxXbmwekLB8SuI%pmtnUc9MmAR(-@jjNjb);dO+U$?jHl%GbW_FOVyZ?KeCY zmp)FUsbMOgqPWup)$!?%pXJy$i$p<0(rY};=Z8p#8`%U&1BmHMN&>@&uds9IEfM&U zpO4~!7Kp_CXUI@T73^ut1x4R=Ka6bt;}45J*iGn?E|CBO2gX5U14{A)T2b@%cA|KT zj;%JM)m-zuu74YD*ui?kE3a{qV0rrJ2K2~6@*Kv*2 z8oSZ^b3`_UF+WBbZoHi%|M}xB$jYHy_m7o)`dW0bok+Otl2wi*c^-9Md43P-UODd= zt02-PSWHkrFU+IpYPPc5_~MT10xy2f8KUlHlVcT${H3pR&Wh```btoaXp5R;(J`hmJ_dD9AN^ z3qkHBlObM2Lj$>=;_w z*$7aZBXtWg3;$@6>%QQ!n#PtJWhJ$Ur!KL0U29~WwPYafth>8=ieQDp&?#h-Z<*)T zOBb>sl!-((%}FgN?aZ>*N?D>Yc0c(Y6l^>{H`U}9*IWv9ATJMP!3$Q&PIJ*xsZLhk ziX~UKLi1A!<{9--GB}(H+Mo6Ks^~_>yKNG$LGywCnD6~1MkI!O$w zsjFEY5qGb4;uBaok~2{9h0EU za!+zeY5Hv0C!is?n`TOp{}p~+19dgBI$ht8h8RoJhg(4p75dAJs!UY8oKRRN2tF*U z|G930#p1cub4St%q#IVE3^I7KC_8l)#eO)V`F9!x|Zb15n9!Nf)^tUc;mTx#XPEmK&H(iGoVu|EH;?@^5=z%Asl z({GlIT!Q{0X_GT8v+)TJO*mt#-`&^$K*sd^F*Gy;bD*Wq+fQewvlDgu)>_*b@1{Je za>n}m7yjpq@}PUi3Fj{-3l{{;A5LY)p2|E^)4)|^bED`z2mx(h#fOFa3lhn6dZ>-4 zfs0GB?ARSnCuA^bYioGCDThvxkC~sGa+sU5JiCa>!Z(nNy0nL^b#;|(TE%Wkw zpsp0FA&%hCa<3j3g3ebEo-*{ED{FcBvU>7JA}3whW_hKu4{H5ifBIN$2{z5Hth9j@ za!+UUBRllGm`jY0bkdZUto6;wOQfig?|t|EgbLs7#?LVt;rg0H|4_7vAcy*m6|SxX z!TCYlQ&vt4-QNu?wR5js*)(?S-{k%TOrH|{~VBPCwMm? z0wx5X##QHf&d?%P!exKn_++IyZ`%Wxe6RS9BL~4(e4R2Q4_p6CSBiekkw2oUo~N$s zdmnW(c|4decA9Ap`i9M>(-%#twOx%#3JH@41%eu6yQjpIJ$M*}eqEAgzq$-&$#g?R3yccxLhYQ25ydFd0Wy_X zggB*(K;n+;DK9np9V7GJ)o`4yun4RY*#RFr?0bb*hi`cdBh+zz;Hw6@;c3A0Wsji- zmMZGK2^NF93Z(1%!@aYjn;mAx-3Ic?+TCl`SH-Ex7e zXeUX*c4+WeO+gOW`YVP_k&%PJ)B-i#hqsHjHuKpZcAE{nHY*pPgDJ5T7(Z=Bgr{vE z5`B+LH^)(rI@H!ll)~ob=@n0Z@gR@O4MmY};i_5+Bf~-3PBd!NUOW7OL>oMzp}wlP zt4%Vm>$^5@V?W`j_H4^Wm1H8@{S+xTjM*gcKJtcDKPgW75|D-t7&BV2*Hx znWGk4b>xZNgvI8w+Gdh1vdXD?D;P*_s1WVPag<499{z?8VIK;~D*S8dV`o5=cXu!v zGuxhwMsMnoL*#~3I9*l_6Hmw|o=_OegUSN;+Z|}D6wek`SBuXdu8E3NduFg5TbTwP zu*D>wzL02cCYy#vAw`IDfu;w8mfRS;`TlZ8!EXVHOVb1_Np^Pb0+UG?MdzMGkIs@f z6l$kch6ZTzX|%{FJ~y*#j2{-t)TNFS`)Q2QOQU-2c@`RF;shLo!YymzPC6}C(1#`d z?oWz_qaK}*o(UcYnlTlxu_C&WkTa@bR24@)m?+3idkSvfZw&>DV^v>Vo)Xwsug# zaO)dFWYMsCXzw`&#;8sn`Q1CaH5^Q(%%Pd^z5jhY4afZRK_hU*SJ4o_54yI=+5 zDrzKarJ!@>#yETg*5WQI27%2#^AA6X`C|oI?M)Tqq}+H(dZ5SJGo{c#SC?!0=_Cft zklU&u!atu=D&19Ycihn${sTon>}KqfP;kST%GoX!N$!21~k=dZlF zz}A9K&4tD#Pc8NxwIv2Hqhd$By4~wa*D(R{dC@%2Sh?YU3tjhd;6ls7P>P8lCMy#4 z9uZUWN;z&tbIh8pEEpft>2Zv#-G3(kw-C!OkZ0vUh`UBda!_)c=Rk0wlS$Pm-0Xx9 zPwM1Z@2{ls>FyHW(6zO#WuRZTyV}doBg5lMvOn>B-8c<`ghfiL@5crC_?hQQKtd(Mq@Iwy)Mq zs+g}7#L`C(UZ-nBc6L=hO$RYSix^9}kfLnht!jbtP=Z(|xR%z|fn#IdJO3!Yz|r#C+dtS93FG}Kkr^6QM+t5HQ^~;$ab`M)aKM^ z%IW5uFf{u>)8?7nZ>GRwUtT1-&p8KfAP)3npxC{h1krG*vSo)yojRu~oa0)W( z0W+*rx-NYJA(^uYK9VMiFxR@U*T}VPT<#lgH2`-f~4lMJe9HtF`^Wej*BO=wriih=skx z+ij#viLV#IIN&MCDM?DxCo?+%CLQj?E5n3lFP(sowQ@)w5Bnn^-3_u-$vy$*k%&HQ z_z%{-Lvwmw7F@A(eBe#7^x^~*MPfSf8jQL{9%kDg!b;WkPe1UE)YKR>;hRzc6?a@@ zB4I?uSthZX_r}DWG^Anp+X|fEBwN!jQzUP)@y`@5LH?$Tp+c`+4+81h7$Uc91x7_F zdT6s%EoaR)lLI3or$goE=Vz7GRD^hCN!EtQ>W@bh4j<`uo5t6l5a~nu*}A%xyG?#D zGnwpo=1O_w_*M|0;v4MNU+>2ImzY)6l|lYRtSW{2Vzmo1O?Jo3Yi%|>FFOR;-WaoO z!866lv054`fMU65C>7PWD3{XQ0yE zAvh%750qc;^6`dk-4Qd>olF(OgN?ZWHl%e5*#m(L(uXSg4E17%kU6{(fU-H1F)PHn zAvTLSR*1lFKQDFMeY7lKpfH4G_SIQyibUV{j~VC~VkCg{FE&6tDQ-s@=O25Y&7i<8ZY+a-MT2 z2yiroCs$7tD8wFQGU%Z+n3Lb#C&QRTpp$lvHxQ)lWB&4TPEdx`yEu=jdB8jF3l3~+ z>XPcCadT^J*ZJY1C7pw)(nCBh-iCW>AZ`fWblLqFY0kFj$hecy)jM*?IW^ZgaZSe9 zG!JW(#Rm+NyrrJ>!(vYAv`8t6Q{f=>D6H&s$jHXWggbok!911t%7V zq7?OTbJP9NoRiBii#6^UFd7ZE=@FRiyuRo+B~1wz-RvJ^QrhGOAYg)1Ve5 z!QIpxMF`tUGhrerSGGmASJU}oI)XtX|RObYOu5gYxe&4 z=RBkqav`$6I9kt6-@+Z$@$+kMQ^I|*vPikEQO8}wQoM%d(hI$ToTtN7d>UqKPZjMU z1=LUb=YgZCNfPlnd#k1F!#=sT)0x#A%6L?=jrjL4-5=a0CIYJ0ewxam3Y7#O zdM=8RW>^;jo+^*uA3eK(bL|;wLW3Ee1^1|gl@+{aUfPZAX&8yBZH$w~ri`%-Du0|t zI|4XWQIm!vgGUibjG6CRITy2cg`|_xHdf}Y0*MrieZO_YES#K?1I|Ty97$nbWMkyxL9J~e64kl9{)BF*5y_>zi-zqE|G=u2C9H`xFT5;y z=ZYWVCC*C@v6BJets|2TCw0FvZc~OlHg2E{snzwq8{ulx z+O>TNx0`=4_sm?3zAtl06RM=W^sWl`lPx7OOuT5tK>3);s3- z4ML2*`!no4YE>3035q{CX>;t)!^US?pNp&0(oab;yjUQhb5XG5uOn55#@*k_d@oqJ zm6aXlP=k;b>ey^a>JfG9^~PO)>bx0(0N3R{xtvM}PpFE}0v;-uw6(Ho%N}GSn8>{g ziqrwQcOhV0H5hz&`deal5hQbl{E0*dR4lXOC?vLS5#f@!_gfee+H=%yVL~F(;TEsH zKV+HltL&@EP1yz){F5g$%cL$WGe6ADr{;0cVyP=Jbm}x?O8X{LPht~B!Z*9dy8}Zw z@j>184SBt*DTdJd={f?5?2dgb!M<}lNSse|AmKo7TIB_~A z721Tb^d<*;sizcn_hG;4UD`Fw8s1_U>DP%tW}4oiuNU+GRhi|^>!b*bQUvrVU+QnS z+Tg^}GB=i}$e`8i^!eK~WdKd%WawBiVTvISFhZ5}O$C`%kxOtZIE{1&sHSh%q&XYtxO@MsSx!-)2bgCF<@KQBxrhJwcFj4Z8f@r(ifch08=vOqOX%WOT%6TcV!e z!93}iH-$&Wf81JGK~rJQW&Z6oGJbv>goeD~^(?s(^_xv!#Sw0Pif*b_6!e!0{76x$ ztftRAtS=Nrz5;_9`Vntr-i+mijurWM4_twss2F*95$0MZJT^1wryBt1B5C#w3sWbu z)g($Y+@awo7HF1J49YUfc?1SKy<*Mj_ZaZ86bCqzxp+9pR}caFch;dF;zt}oD3oM+ z)OHkshGbYEsKOTrY8cV4I=aXWL-xoZg{Y#<^d^pKHWyoYITrJkWg}{S+XJ)ozH~d; z?v)opG0ovchRRCISfuNRmD{yoz_WM@K@opb8iYVkNrmKt8a6s?5SN*l3{p1yUPr)S ze?cju<1048_|kTFXyXzBbsJW>{)H6s{e89ppI?mjn{9R~+A65{MnwfA(!`wM-~>|2 zmY0gR2VIbl60}n9hjc2wPYK^{C5BE^S>OBe#V?!Z#m9ZF;n)*L$}sy8F28Fe6%tNw z#RQ^Z63$l-GOMaP5m%PyBSZ1%lVtMq(L~XrM*SWW8>L7PpD&9W>S@)jU#c+{KLvpd zoWbP`8GV{9t_>?}Y(r;y1Zl~fO(!GKP^)1p4P&kZAm(KrFGZR!+oB7qWpwbfR=?@1 zYZ?!S($?+2f&;qUugeOV$T-+yHt@P^**TVK3ABlds82CNKi;pu+tAk>Z976V&{dvE z{=$`T0)ui0z7d3|L{Jz|IvOl16WjT=%khIhOK-5Y9kxatff>PglTI7b&>6#6hT9A6 zoB-bvdCO%^5W^e;H33f`{Yo*BU3oRR--gF-DK3o_giJXr@`20O{f87Nxx|-p*1puZ z#`e0r-mz%B+t*9x0W4NwYRoqd3tK^~#c!6h^%ovFI?Dd%Ne-YfDWt_9A*GH2j`Nhm zHZ0F#@DQcApdVl;DAGoqxWgy6P(n8oAd?WM-w6l_DYAld1PA?+T{9E&2g^%Xq}GoI zcxFT`B-WA(EMgiP*W_R zcYEL@+j(UaRm5qdF|KT3H3o5z`{t6+CE31aYD&(s!l6KeUiWF3hfH6pSjWCJTrKWCNuT7_Yo-)(<`w{`HI<{>>@Z2s}m*_(oCU@R727N@?w zf7La<_hU$&H9fZ)Lc8C{;e5Rn!Fy^-;drsp8tZw1=;+(bFgO;F#8gd<90@c;TyqeS z5NJt~G#iUpcdGRX(1(&7$2NLBq{*e`-p#aYiaOoH=QiXa-WYL&0G<$53TZ3|n|%tp zVAJ8reiSLAFx_WnFKt6TD2pHwH)6(4HLDmP{X!82>^UJE|2}yAMVcdMm5iFda?O!P z;(vVS6b#aL*N?d(A;gL6G{{o{a*p=l`zgI%ZTl2_vIL+VZB}PV!v@At3<zY%ZO$u!^)_uq}`BTBJ(;>dw#vSlJODr??77QV(Z%s z%4j+Su+L<(LG1iH0a>bzrByc>x`018-&f~O;mWDMH0O&g^>`(Ua?+c&_C_F!(UirV zU7%uP2a&3>Ed~qM6abDo{qL|V9VNfcv+WiW>n0J4P`4FY;`-#+) z1dtA3xyCZ;ea4X;>vbps^#xGiS?4fKD}>_l*^--1cl!1Sj07cu)+_+bVhsU-=H-aC zO@f+$-@)YzoNZ?amM(u1z@(+Xp7nmQ$qKk%g{GL#meCD`w5GSY7s(zCn`P)D&VQco zf;q}Ql0`YINIUiOTZ40L0V<)cZ zEkeoyNxKIb7`_jd_>n`vrBB zS5Z5EFpZvv@SqPSXy+?08KTEJ8B|XNKv{D045uuH9f$d|hGWSYg{}uW817wU*oL;M zvNlT9I?t{nkTfg$Ryg%Ga)^t+$wxBKSegf!xn%ifcgf?+G!|7P_PN&GH)ciQCD9#U z8-j1|5)Aew?#(v+9%0_Z$%2uj!*6mfNuN^R3zCJ%2Rt7*G?{sKKsTo`74waGfy
    ^TRTa;^}@n>lP_EjCk2Oj-ZC!<>3V`YfcT@ zU8{~o3i}~Wnf?RlVTs_NhZw|#A$hW4m`Z*#4((d4W_z3Om-YmLp&(ok!&aI4Nsm{5|AhxNg7 z(7OfFGSe>41H0Onsf_R}8+6aYe*Xx#;#r%3f`&1m=1foq(tV+VM+J z35wy_7cI-Ffk84dw^avEquYdx%s0NM{NC)&PdTnL}70%M+e^xD;+LQ#H;Kn943fpJmf zHW>-mimQbPc*iankz3IH8>6?)z_{cS5y=N95o46bw(b)7+T@{83~ka%$18)A$!rBU zUp=P{HH@4G*W-qqC||M#$YZqhf84SGGE+BHIm9m6q}|y(r@0Ys!;6f~bZXeLQZq5h znRrkXC7_-743;(B#!kz{sFP-=rl+kwB-1dqCY0&sID~|V>|ge0|9+g;g=v#77bCWw zp3jP-u^^lds``%*ZQ*KC5&@04dD=zA{E18J5RT@H$E)b8LlcXQu)Rmw6n?f??u(Nz z9-X866XQi^WrUShrYc^l9HAPRoLT>i?k88TQj&wT{1BvDn@~Q{~+5geQrx264G6}M;qdg%Mt5}Voc7wAr2X~Yj-#4xsoKMjt>eOFHj`NeKN%QTC5s1(N-3F6}7 z!Z=Hjr(?kPu$avi!%Y495rquF5@&0J`^4>h2z%DbdpG}3T# z`m@k@Q?ugVt$cBX%tZgc`YOe?LeUbDh@{G_{?@Fk(v~IMUzTFJ2Ss{;ij%E0#g&M4 zu?M?DcH7lIU;>(V&|=Z*Etm{#`F?Yh<>YcYk=HU%e$Z!=C8`5+X2hld; zEN!fjlcJKoJzkXqntytG`xF!wCTY^saYlU`ely}TFDW{yA(2XrOg$_Kw1l-r@Dnw~ zd<0)cqZ$S!CaK7G@=v-rw|j`527D^=ELrO<(H)CkZTEkJR1(-KHRE30oq3~fD{>@2&2tk3Jr?Xo!CmfeJ)s}lb4ddhE>H@^pRhF!7 z{Mzu08jjvk7m?zE)`gnrD=(AU1}QW^4-1$@+P!o7gYS_J=FhZ*So@;_$5t zGo=|gIDTppYeK3+7Vk1x*zcJRJ{iLTV|Cp1M8wv3fiY3%vgFMa|ivQ zq;;teciv!(SY7pR$(mocy2N;HEN|l{(jILOg+Rs)IYCL>_OGL%ALjpw2-R+lo*=g~ z{^P}UUP(8(Oc_kKBGApx^nG=COG185#vH7MtAqpEqeVTWAqkHReOrFb?l^UF;ruk1 zqW&vlRMlknSz_Yt1!GTUb^(*QnK*97C70hIV^(Gp1RR`MqdpG}<z{HkwsF)(0}ZwUJ^uNWU$B!XWp0?0zEa zn?N|5ENl~tW_{T&Hu7)QEL>FI3?*iQf^^M5>dn@A2Fl7TNc_vpT`5!FEwvxi zhyac+i->GaXV9Lfn?Ts z8~Eoll(R6s?8K5}_*F|DlQgfkp_2)8)iQBWSrcS)>ql3g0Xpn1=}vji25To;I5{YHg!V9 zpuR`!llPMcGUgB{tGc4o<+$bUI|^W;-DYE6Q}Mz6D5j-5gLB1UUjqaIzmb11#> zk?7X5O*(tQ^zSI`I)5Uu@q6gu2w;FFccEtQ!rxJx1+N9(ejIPfCi_m3gYr2n;D#3w zWeKQ9+eS_Y6n%{M^H#Kpag5#C?ydv%78q3HiJdm??a|}#9Kzb@C@oEsiiuM0-#rp4 zVXfD+N!Y=buD|)`iXGsB8srlgUFoB)URd6dse95}JFC)b0_7PMY%Fsb)t2dY4n!4j zkJhhHNJCXI?uUOT2-UZk0*OsQEP`^!^at|*01Vo7PVrBJh2~3x>~KAYdF#>vS~}(+ z&L-9l5j3J<%LUi<0_zSMzDb6G#MVadAPfYMy>*-~91~CjW|iR4{G)xNqZ( z(b}=Ze;7(EZ%VouDbP83-&=SbAgodg+gzqpp1oro?tSM39^Rn5~!K{8YRTS&)lG{#RJr|sUo z%Gxrk(cZi~GDBKy^yBZalL#z@N;ZA%8BLl6X7=DOGoInuUe@n!<_QI&ckQcL$O)o%8X78Xk)!+SYRP2G+|0KkAq^t2u78uR zloj9u;fI|f7p|x=r!nY%#!Ix`Mw3}B{yBX56VhLu2Oc$wS%^$#ARv9t3k5G|G$zp_ zLg6kL5v;0UN1SU19j{}OvxSPh3byD`4vs!<6@OP1ZQKKG`?W{rr2`sch754w^Q?9U zTywQ67mn%du8H~}7Mjy>+6%)SfO7Z#z66m4bAt-^u$d{ZqYKka7kl;+5{j4MnXcI7 zFWi9+K%!sJ-PJZ>8AHi6S+Fb>a;2ybB};h^q^rCBiVoM@PTRognYQ!rMOYm z$z4HeICp+a6)+-cXu}R$mkNLabSk+JZ#@8`oasm9jR&3@_Z*-?(2Z?0o)5}*R$7K- z)sA+t&EErulLS4sI+KKfnFhw>Cp#&%P@Ee7@=|W*PYn~8j)K?@-e^>-LTq=I!UCeh zpGbbQwF^JB9Zq7AR}!JdQWb*Nl2T50B54sDE>E?c^^2}u(@TuJeD$W1` z^pKtf&Y0jzaFI5EE%U^7gS5AM2BAZZPHgv=9*N3R1#C~5Yn{ceIAoa(_wgM4p~2bb zH-MkJ#YGxH{iVtld%Fj0hLETXYK*4>B0m^Hro@m|GZ8d-=gHK0HIpFuC^rSE0VzRy zT7cntfJ$Jrl~^fs>Tc$cQ|^lwJuCbon5{E*1Dr(1V+*?Vf}H&|(m9XUcBZrm=?t^% zp3FR$g)TA_;;!_-**VTYQGwbJjha#r)@=3W#-1KkHM^o4hC(W<~{n7~?a zilk~2^a=4Xu-#oG{rm{uM+r`!SOe=YKAUxkCC~v~*x{?UDH#!^qbmF;{D2XaN|YPG z)Yx!JCN5tXPvRbTDhXMn_8+YZ%WeBGOYZo-*TJ2OjKCh6{(*}-Y#Sf8m=u==L>pfP z=1gp<6ST7it7Bz6U1k1vMIt^9>l2)yKdXVtxg@|fX*W##hU97IF=gh z(CZqmF$*ol)ze{*UyD z*Vjm(_tyVl7|EB0Uw}}2l*0=Md5v;`wKqIVO<`YUM41(Z73SIqPdHpvBwlH(ap#~b z8>W7-l{8nJgkDpH8!oC^az3&F+2V=K5E7H5z)#4q@=DpCFzOT8#(_LNAIZ}9ou4{> z_*HU&<5iA1#M~0AR5aXT)Y(I!pa_p54R!3dNhjZ;wzTqaX*rdis3$@xU(9icc3Ff4 z1b(0XaVpaD@Cm=HeSm3Hax=CV@OW$?$kQnaH%g8j8BBo@hqr7)b-1#5idJl#)?a`^ zDHbj@5c~E%=8=wCB{NlxQHqnK!Mhe!+s%T~NbN2dNGMMW&eFhQ48c}hu|5*%VvO6k z#4Hog4E7C`av>5cX40d^Ro_=yM~Z$9%A4Y{;FbI|0UJAcO1Y+C4N=o!6hz9*Jr9Zf zJ(tTsyXzSo78ebYJ!cry6UZ6Vv^SilT@lh3Cpz6LbFo0zQ`oaZIphe<&As=_O9d;H z*$84uMN8_#S=Oj{Oret%hl0hmz*-tWiXK)hng}*JrAtmhpfY+#n}b=O!YQE><2sd1 z#k-u}gcpL8$qA{K38{UWNxIrtWD;mjVCY+k=$8{xC%FW}@M)P!f@(?L372S>r0Y0D z0~OhEg2*r>SM%(UmUxYmaEjCv8*gGFfM$!8LIGe@g1#PP0p&o$8i3KTMbLu^jPgCO3VBQ^A29)7 z$w~pMqGF7){O>(HU)6HZTELgJMn)lLF#(`R ztdR*gp99K)1R~G_nwO)r0?$GGm-d+Ht|19CA!5h^&h7ya^274w4H^&?EX+O)J*s=_ zlC`mVATTC*wsab(L`NkXpGuqK3{xpFCNW#a=RojXLsr>le_!MQh5>z!^kEQfYBnBn zb8E;_JAs`%R1VWn8KZjWrg26Q#aaICORr6#Eyx4-gGEwkgJ#)gj9D|I^WR#_6JegX*WlhkGD};@Q32jQXnXYuLctE&5h+3=frROEz?EB|+KnDo^ZTK{wi0@FY!P;2MH*n3#O;kY-hj(4yUfzS z2#C_sQkvCf)v8q#U{>0O4IALBv(BOmk8SDFrSO-({KZn`wIxfI!1K>PPtX1DfBy^D zUw^%&dp0#S!8zxg1KYN3qyL^WXAZ1bu>#W4(kwqn>E6mV`n`?9;#zFI`*%Ub?N_VZ_$4{2(U|@e+ObpMn#k&b??{=l|Q-~c#AvQEyMbv zi!OqTFTR*&dA8D}_VB|G!?$tS~Icily=#e$)K{_~$HMYD1(FS=?@J@r($ z=9+6P-xDe83opDN&-uj{U!=+FtX{9Y_tCVt@lzo4+9lz!B8L<5|L+gLh*^U&uD&_q z;KG(L?IcKEbgt#|EqktK&YY>L0)}N(yg|}UN@Z6TEn1|y&ZrnC=2J~ll!;leU;+I^ z_J-$5=i~jlgCrHfie}iRPoJ*3C$c}Il;c?bPio`GkEioMHe6g>EMJen=?s;}i?mjQ z%!uCFDsUtw2fq+=eZ>b7vxMS9#NK-IB z=LfG(c<@+C*eXl#5!pbxt}{rXsMgjN`8=OLKs}^m*xYWn#kq3wby(lXZ<6y1si|^& zqkDD?Lgr~dmZ9;AzuD)P=OG<~Ac8VdHsyJ8q%IjpbzD5R_s|}Q9XSphDZ%ASUvmR^ zYbq(*W;DtA>;Ts~z{rHXVrgHW*SZ#gWm=@`g5{w%8lNt9zx_yBWT{r>syt6MXT>p& z8-(2X7&|YqWa(w#!LZ1vfq1VvPYQv=akSUBF8>#_{O4~p`O5IWzXmbGM;eaULj?Ki zpWjRX+7CHPAB40^uF<~1kp~z)XrE64iuGKkesYa;9T(&}q>zE}0|4_WsEJjo$r+4g zxHO92q-vz^;dX>s;s&(jW zgSy}Ul!8mrMz!M%NI_Br2T}vWv@7+Ek}T-r4hOzNiBiWDqxo>~S|b|y9fa_@aqHoA6x`Zjc}{6PM`jj+(} zZ`KRIAWA~+eUAw_DKz5@NTmLmUlM9pU^oVEgM-Y=Eg+%*);tkYVPxBN;)Sy7|Ry6x9OuGk>g z4vd+C%3$_cBxO0?(B=)*_zDW9w5s#AWUv553Tmb>0B(DGJN$U*U67xj2e~=9)Vi;2 zm`neW-~CpOwup<1)xW**$+8U7dte82e)y6JKnPG9s;K$ERJMwc45pI)&}%^RxcLKK z01L7oKX7(1Ul?{UpL`t`%+TuBkB`sFXM-K9?OUPeDin1$AHS}yo_163Lt7gy4=9ag zMp-Busw#!vgF9^eh%jX^2rYxr`F6XZ`MKYz3RZBv-O&8(?;z)=kISjdji2uT2>B9= z3`G^pWH8B?YHNIvMcQ_~aMtF^i!3tS=2Ng%Be_IHMQr*7`J<#@5R8J6b6WrR1d+QM z1Q6sD0^j4IHIeW|Xn*rLNW1)&U=Mhpw8(*@U`FE$mi#cy6u!`A3XbQ)qL2Z(F)(M& zAg!cQKo7_998|bh*}?qATBOPK?)4u+&#sLETO^b!(d5)hlAL6GklD|({csaxrPY~rX z4>|V`|$$@bd`3Kex=CcAY>(1`M0GQ7Tz$Eudm=r9Ot4N|?atE~xrtCDgM4Mpm za%AK}%6T`b&mnV6yYzNo6Ou)0R|Y+MHxG`hNNH*J*|OvZEaO30Bp2F}ZV>yJ z+w#YSYucK1=L}3dn9^5hE1JTm@I{7j6@~Cc+LOUT`%QU;&(e+(5%_HiKWh*Q7M752 zRR+_A>zK=6abr&c#uW!K!^RQ{R$xjQT}2Zh{i>gXx1j=JN6pZmHy{90sQ#QCfO!>W z3co!w1s}GVg0p0%K--l!3?;(IOko(9=u_CDxG(?~M!=ygPl0<;7j!G2OrQV17xStbQm6DLfN z&+C_LOBzG#_19b-G=zEW`mdm-wpP$c#p`miv*Eg{uQCMMn9-wk$8j#-x%5(SI)f+K zLjx=BJPN!FdH`|cnK7cNAf{v*B>MS~F!nW7L*IdoB4r9Z-^95W8}3JRq+}VJDf;>> znK{B~yp5OMGQe=}prn$c_v(~+^MaoL#i~^lV6`>1kRt9F!p}vgEC@;w1Pi)Q;2rly zD$NMf4g7t|R#jb10oKyeqPlLu+_@p|*^3K85RJQv7N54rvRo=r^R~8j{n*X5M5YmU zF2y84?1WQ7j_JraLIK9pl79g}#f&w7-pcd1K4I6Dx3L-=Iim&yV7}J+$OG(~?c3qp zbIzi>i|n+IKl=3LBPtcdvrjku!mbiH|6_ zI8QtDAKq^Hd|Rmlva_<_oHG|gQQ<${ ztel5-!g4o#y%{!d-6~KJhXa0g_uWB%pVayZ3p`R$4xfDXIdqupopk1ogt$qk14~$$ zmF@e!+Jn%&@l9ZpG9c-!TP%T-CsfN@y%+j+f2m@lY(g5uj5(Q>mu8rwO4v?C0It0O z`VMU(_wx)4z@jbM?6xStqAd!rXgj_E#=%imREf4|GZWoV>f9fF4$(G1Z9f9+ndozf zwgGAsTWGR=3*2HCe4kP}tl=MAll8Qc@Xb-ddMGP&K!1ezH7ytx~S_p%u RMd1Jd002ovPDHLkV1m*lPuu_i literal 0 HcmV?d00001 diff --git a/playground/simple.html b/playground/simple.html index f708569163..7b6edcfc33 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -24,7 +24,7 @@ - + From 026dbd749837a9827c8eb160c042ca5d67659af7 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Wed, 23 Jan 2019 18:48:49 +0800 Subject: [PATCH 237/267] modify material instance in editor --- cocos/3d/assets/material.ts | 7 ++++-- cocos/3d/framework/model-component.ts | 4 ++++ .../particle/{particle.js => particle.ts} | 24 ++++++++++++++++++- .../renderer/particle-system-renderer.ts | 23 +++++++++++------- cocos/3d/framework/renderable-component.ts | 15 ++++++++---- 5 files changed, 57 insertions(+), 16 deletions(-) rename cocos/3d/framework/particle/{particle.js => particle.ts} (53%) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 90ad28af0e..4ae7eb2e03 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -40,7 +40,7 @@ export interface IMaterialInfo { @ccclass('cc.Material') export class Material extends Asset { - public static getInstantiatedMaterial (mat: Material, rndCom: any) { + public static getInstantiatedMaterial (mat: Material, rndCom: any, inEditor: boolean) { if (mat._owner === rndCom) { return mat; } else { @@ -48,6 +48,9 @@ export class Material extends Asset { instance.copy(mat); instance._native = mat._native + ' (Instance)'; instance._owner = rndCom; + if (inEditor) { + instance._uuid = mat._uuid; + } return instance; } } @@ -232,7 +235,7 @@ export class Material extends Asset { const comp = this._owner; const index = comp.sharedMaterials.findIndex((m) => m === this); // @ts-ignore - if (index >= 0) { comp._onMaterialModified(index, this); } + if (index >= 0) { comp._onRebuildPSO(index, this); } } } } diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index 506c278e90..1776cfc8ad 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -232,6 +232,10 @@ export class ModelComponent extends RenderableComponent { this._model.setSubModelMaterial(idx, material); } + protected _onRebuildPSO (idx, material) { + this._onMaterialModified(idx, material); + } + protected _clearMaterials () { if (this._model == null) { return; diff --git a/cocos/3d/framework/particle/particle.js b/cocos/3d/framework/particle/particle.ts similarity index 53% rename from cocos/3d/framework/particle/particle.js rename to cocos/3d/framework/particle/particle.ts index 82228dc683..291ee35ea9 100644 --- a/cocos/3d/framework/particle/particle.js +++ b/cocos/3d/framework/particle/particle.ts @@ -1,7 +1,29 @@ import { vec3, color4 } from '../../../core/vmath'; +import { Color } from '../../../core/value-types'; +import ParticleSystemComponent from './particle-system-component'; export default class Particle { - constructor(particleSystem) { + public particleSystem: ParticleSystemComponent; + public position: vec3; + public velocity: vec3; + public animatedVelocity: vec3; + public ultimateVelocity: vec3; + public angularVelocity: vec3; + public axisOfRotation: vec3; + public rotation: vec3; + public startSize: vec3; + public size: vec3; + public startColor: Color; + public startColor01: color4; + public color = cc.Color.WHITE; + public randomSeed: number; // uint + public remainingLifetime: number; + public startLifetime: number; + public emitAccumulator0: number; + public emitAccumulator1: number; + public frameIndex: number; + + constructor (particleSystem: any) { this.particleSystem = particleSystem; this.position = vec3.create(0, 0, 0); this.velocity = vec3.create(0, 0, 0); diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 66f301cfa4..c1354d4aac 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -125,9 +125,10 @@ export default class ParticleSystemRenderer extends RenderableComponent { this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent'); this._particles = new RecyclePool(() => { return new Particle(this); - }, this.particleSystem.capacity); + }, 16); if (this.sharedMaterial == null) { - this._materials[0] = new Material(); + this.setMaterial(new Material(), 0, false); + this.sharedMaterial!._owner = this; this.sharedMaterial!.effectName = 'builtin-effect-particle-add'; } this.onEnable(); @@ -162,11 +163,11 @@ export default class ParticleSystemRenderer extends RenderableComponent { return this._particles.add(); } - public _setNewParticle (p) { + public _setNewParticle (p: Particle) { } - public _updateParticles (dt) { + public _updateParticles (dt: number) { this.node.getWorldMatrix(_tempWorldTrans); if (this.particleSystem.velocityOvertimeModule.enable) { this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans); @@ -254,11 +255,17 @@ export default class ParticleSystemRenderer extends RenderableComponent { } - public _onMaterialModified (index, material) { + public _onMaterialModified (index: number, material: Material) { this._updateMaterialParams(); this._updateModel(); } + public _onRebuildPSO (index: number, material: Material) { + if (this._model) { + this._model.setSubModelMaterial(0, material); + } + } + private _updateMaterialParams () { if (!this.particleSystem) { return; @@ -294,12 +301,12 @@ export default class ParticleSystemRenderer extends RenderableComponent { } else { console.warn(`particle system renderMode ${this._renderMode} not support.`); } - this.sharedMaterial!.setDefines(this._defines); + this.getMaterial(0, CC_EDITOR)!.setDefines(this._defines); if (this.particleSystem.textureAnimationModule.enable) { - this.sharedMaterial!.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); + this.getMaterial(0, CC_EDITOR)!.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY)); } else { - this.sharedMaterial!.setProperty('frameTile', this.frameTile); + this.getMaterial(0, CC_EDITOR)!.setProperty('frameTile', this.frameTile); } } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index f75ddcc68a..23e1c98c85 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -59,14 +59,14 @@ export class RenderableComponent extends Component { * !#ch 返回相对应序号的材质 * @param {Number} idx - Look for the material list number */ - public getMaterial (idx: number): Material | null { + public getMaterial (idx: number, inEditor: boolean = false): Material | null { if (idx < 0 || idx >= this._materials.length || this._materials[idx] == null) { return null; } - const instantiated = Material.getInstantiatedMaterial(this._materials[idx]!, this); + const instantiated = Material.getInstantiatedMaterial(this._materials[idx]!, this, inEditor); if (instantiated !== this._materials[idx]) { - this.setMaterial(instantiated, idx); + this.setMaterial(instantiated, idx, !inEditor); } return this._materials[idx]; @@ -94,15 +94,20 @@ export class RenderableComponent extends Component { return this.getSharedMaterial(0); } - public setMaterial (material: Material | null, index: number) { + public setMaterial (material: Material | null, index: number, notify: boolean = true) { this._materials[index] = material; - this._onMaterialModified(index, material); + if (notify) { + this._onMaterialModified(index, material); + } } protected _onMaterialModified (index: number, material: Material | null) { } + protected _onRebuildPSO (index: number, material: Material | null) { + } + protected _clearMaterials () { } From a404510a28ed38395133cf1ce80841c8c415e6c3 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 19:00:11 +0800 Subject: [PATCH 238/267] uniform array --- cocos/3d/assets/material.ts | 12 ++--- cocos/3d/builtin/effects.js | 69 +++++++-------------------- cocos/3d/framework/model-component.ts | 7 +-- cocos/core/director.js | 2 +- cocos/core/vmath/color4.ts | 10 ++-- cocos/core/vmath/mat2.ts | 10 ++-- cocos/core/vmath/mat3.ts | 20 ++++---- cocos/core/vmath/mat4.ts | 34 ++++++------- cocos/core/vmath/vec2.ts | 6 +-- cocos/core/vmath/vec3.ts | 8 ++-- cocos/core/vmath/vec4.ts | 10 ++-- cocos/renderer/core/pass.ts | 30 ++++++------ playground/simple.html | 6 ++- 13 files changed, 97 insertions(+), 127 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 90ad28af0e..0517ad898f 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -120,14 +120,14 @@ export class Material extends Asset { * pass.setUniform should be used instead * if you need to do per-frame property update. */ - public setProperty (name: string, val: any, passIdx?: number) { + public setProperty (name: string, val: any, passIdx?: number, arrayIdx?: number) { let success = false; if (passIdx === undefined) { // set property for all applicable passes const passes = this._passes; const len = passes.length; for (let i = 0; i < len; i++) { const pass = passes[i]; - if (this._uploadProperty(pass, name, val)) { + if (this._uploadProperty(pass, name, val, arrayIdx)) { this._props[i][name] = val; success = true; } @@ -135,7 +135,7 @@ export class Material extends Asset { } else { if (passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } const pass = this._passes[passIdx]; - if (this._uploadProperty(pass, name, val)) { + if (this._uploadProperty(pass, name, val, arrayIdx)) { this._props[passIdx][name] = val; success = true; } @@ -207,17 +207,17 @@ export class Material extends Asset { this.onPassChange(); } - protected _uploadProperty (pass: Pass, name: string, val: any) { + protected _uploadProperty (pass: Pass, name: string, val: any, arrayIdx?: number) { const handle = pass.getHandle(name); if (handle === undefined) { return false; } const bindingType = Pass.getBindingTypeFromHandle(handle); if (bindingType === GFXBindingType.UNIFORM_BUFFER) { - pass.setUniform(handle, val); + pass.setUniform(handle, val, arrayIdx); } else if (bindingType === GFXBindingType.SAMPLER) { const textureView = val instanceof GFXTextureView ? val : val.getGFXTextureView(); if (!textureView) { console.warn('texture asset incomplete!'); return false; } const binding = Pass.getBindingFromHandle(handle); - pass.bindTextureView(binding, textureView); + pass.bindTextureView(binding, textureView, arrayIdx); } return true; } diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 83ef3ff9a7..0bacfd6b65 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,41 +1,12 @@ +// absolute essential effects export default [ - { - "name": "builtin-effect-unlit", - "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}], - "shaders": [ - { - "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", - "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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;\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":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, - {"name":"USE_COLOR", "type":"boolean", "defines":[]} - ], - "blocks": [ - {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ - {"name":"mainTiling", "type":14, "count":1, "size":8}, - {"name":"mainOffset", "type":14, "count":1, "size":8} - ]}, - {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [ - {"name":"color", "type":16, "count":1, "size":16} - ]} - ], - "samplers": [ - {"name":"mainTexture", "type":29, "count":1, "defines":["USE_TEXTURE"], "binding":2} - ], - "dependencies": {} - } - ] - }, { "name": "builtin-effect-skybox", "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], "shaders": [ { "name": "builtin-effect-skybox|sky-vs|sky-fs", - "vert": "\n attribute vec3 a_position;\n \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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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.xyww;\n viewDir = a_position;\n }\n", + "vert": "\n attribute vec3 a_position;\n \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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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.xyww;\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":[]} @@ -54,7 +25,7 @@ export default [ "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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": [], @@ -66,37 +37,33 @@ export default [ ] }, { - "name": "builtin-effect-particle-add", - "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":1, "blendSrcAlpha":2, "blendDstAlpha":1}]}, "program":"builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", "properties":{"mainTexture":{"type":29, "value":"grey"}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "frameTile":{"type":14, "value":[1, 1]}, "velocityScale":{"type":13, "value":[0]}, "lengthScale":{"type":13, "value":[0]}, "tintColor":{"type":17, "value":[0.5, 0.5, 0.5, 0.5]}}}]}], + "name": "builtin-effect-unlit", + "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}], "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 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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection;\n uniform vec4 cc_dirLightColor;\n uniform vec4 cc_pointLightPositionAndRange;\n uniform vec4 cc_pointLightColor;\n uniform vec4 cc_spotLightPositionAndRange;\n uniform vec4 cc_spotLightDirection;\n uniform vec4 cc_spotLightColor;\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_uv; \nattribute vec2 a_uv0; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color0; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color0.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_uv.xy - 0.5) * a_uv0.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_uv0.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\n , velocity\n , velocityScale\n , lengthScale\n , a_uv0.x\n , a_uv.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_uv.z, a_uv.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", + "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", + "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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[2];\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[0] + color[1];\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n", "defines": [ - {"name":"USE_BILLBOARD", "type":"boolean", "defines":[]}, - {"name":"USE_STRETCHED_BILLBOARD", "type":"boolean", "defines":[]}, - {"name":"USE_HORIZONTAL_BILLBOARD", "type":"boolean", "defines":[]}, - {"name":"USE_VERTICAL_BILLBOARD", "type":"boolean", "defines":[]}, - {"name":"USE_WORLD_SPACE", "type":"boolean", "defines":[]} + {"name":"USE_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"USE_COLOR", "type":"boolean", "defines":[]} ], "blocks": [ - {"name": "Constants", "size": 32, "defines": [], "binding": 0, "members": [ - {"name":"frameTile", "type":14, "count":1, "size":8}, + {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ {"name":"mainTiling", "type":14, "count":1, "size":8}, - {"name":"mainOffset", "type":14, "count":1, "size":8}, - {"name":"velocityScale", "type":13, "count":1, "size":4}, - {"name":"lengthScale", "type":13, "count":1, "size":4} + {"name":"mainOffset", "type":14, "count":1, "size":8} ]}, - {"name": "FragConstants", "size": 16, "defines": [], "binding": 1, "members": [ - {"name":"tintColor", "type":16, "count":1, "size":16} + {"name": "Constant", "size": 32, "defines": ["USE_COLOR"], "binding": 1, "members": [ + {"name":"color", "type":16, "count":2, "size":32} ]} ], "samplers": [ - {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":2} + {"name":"mainTexture", "type":29, "count":1, "defines":["USE_TEXTURE"], "binding":2} ], "dependencies": {} } ] - }, + } ]; diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index 506c278e90..adfb368fbe 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -169,9 +169,6 @@ export class ModelComponent extends RenderableComponent { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); - if (this._model) { - this._model.enabled = true; - } } public onDisable () { @@ -196,6 +193,10 @@ export class ModelComponent extends RenderableComponent { this._model = null; } + if (this._model) { + this._model.enabled = this.enabledInHierarchy; + } + this._model = this._createModel(); this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); diff --git a/cocos/core/director.js b/cocos/core/director.js index 3eec6f45d7..eb6e6e56d1 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -925,7 +925,7 @@ class Director extends EventTarget { this.emit(cc.Director.EVENT_AFTER_DRAW); eventManager.frameUpdateListeners(); - this._scene.resetHasChanged(); + if (this._scene) { this._scene.resetHasChanged(); } this._totalFrames++; } } diff --git a/cocos/core/vmath/color4.ts b/cocos/core/vmath/color4.ts index 13e1007529..e177ec8714 100644 --- a/cocos/core/vmath/color4.ts +++ b/cocos/core/vmath/color4.ts @@ -222,12 +222,12 @@ class color4 { * @param a - The color. * @return out. */ - public static array> (out: Out, a: color4) { + public static array> (out: Out, a: color4, ofs = 0) { const scale = (a instanceof cc.Color || a.a > 1) ? 1 / 255 : 1; - out[0] = a.r * scale; - out[1] = a.g * scale; - out[2] = a.b * scale; - out[3] = a.a * scale; + out[ofs + 0] = a.r * scale; + out[ofs + 1] = a.g * scale; + out[ofs + 2] = a.b * scale; + out[ofs + 3] = a.a * scale; return out; } diff --git a/cocos/core/vmath/mat2.ts b/cocos/core/vmath/mat2.ts index 1637a2d533..4df9217f45 100644 --- a/cocos/core/vmath/mat2.ts +++ b/cocos/core/vmath/mat2.ts @@ -271,11 +271,11 @@ class mat2 { * @param m - The matrix. * @return out. */ - public static array(out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; + public static array(out, m, ofs = 0) { + out[ofs + 0] = m.m00; + out[ofs + 1] = m.m01; + out[ofs + 2] = m.m02; + out[ofs + 3] = m.m03; return out; } diff --git a/cocos/core/vmath/mat3.ts b/cocos/core/vmath/mat3.ts index 20d0eb2c4f..d2934883a4 100644 --- a/cocos/core/vmath/mat3.ts +++ b/cocos/core/vmath/mat3.ts @@ -625,16 +625,16 @@ class mat3 { * @param m - The matrix. * @return out. */ - public static array (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - out[6] = m.m06; - out[7] = m.m07; - out[8] = m.m08; + public static array (out, m, ofs = 0) { + out[ofs + 0] = m.m00; + out[ofs + 1] = m.m01; + out[ofs + 2] = m.m02; + out[ofs + 3] = m.m03; + out[ofs + 4] = m.m04; + out[ofs + 5] = m.m05; + out[ofs + 6] = m.m06; + out[ofs + 7] = m.m07; + out[ofs + 8] = m.m08; return out; } diff --git a/cocos/core/vmath/mat4.ts b/cocos/core/vmath/mat4.ts index c200b7aa9e..3890527d26 100644 --- a/cocos/core/vmath/mat4.ts +++ b/cocos/core/vmath/mat4.ts @@ -1460,23 +1460,23 @@ class mat4 { * @param m - The matrix. * @return out. */ - public static array (out, m) { - out[0] = m.m00; - out[1] = m.m01; - out[2] = m.m02; - out[3] = m.m03; - out[4] = m.m04; - out[5] = m.m05; - out[6] = m.m06; - out[7] = m.m07; - out[8] = m.m08; - out[9] = m.m09; - out[10] = m.m10; - out[11] = m.m11; - out[12] = m.m12; - out[13] = m.m13; - out[14] = m.m14; - out[15] = m.m15; + public static array (out, m, ofs = 0) { + out[ofs + 0] = m.m00; + out[ofs + 1] = m.m01; + out[ofs + 2] = m.m02; + out[ofs + 3] = m.m03; + out[ofs + 4] = m.m04; + out[ofs + 5] = m.m05; + out[ofs + 6] = m.m06; + out[ofs + 7] = m.m07; + out[ofs + 8] = m.m08; + out[ofs + 9] = m.m09; + out[ofs + 10] = m.m10; + out[ofs + 11] = m.m11; + out[ofs + 12] = m.m12; + out[ofs + 13] = m.m13; + out[ofs + 14] = m.m14; + out[ofs + 15] = m.m15; return out; } diff --git a/cocos/core/vmath/vec2.ts b/cocos/core/vmath/vec2.ts index 80b54bc8e7..ffe65ac5cb 100644 --- a/cocos/core/vmath/vec2.ts +++ b/cocos/core/vmath/vec2.ts @@ -545,9 +545,9 @@ export default class vec2 { * @param v - The vector. * @return out. */ - public static array> (out: Out, v: vec2) { - out[0] = v.x; - out[1] = v.y; + public static array> (out: Out, v: vec2, ofs = 0) { + out[ofs + 0] = v.x; + out[ofs + 1] = v.y; return out; } diff --git a/cocos/core/vmath/vec3.ts b/cocos/core/vmath/vec3.ts index 310aeccad8..4e7e320504 100644 --- a/cocos/core/vmath/vec3.ts +++ b/cocos/core/vmath/vec3.ts @@ -737,10 +737,10 @@ export default class vec3 { * @param v - The vector. * @return out. */ - public static array> (out: Out, v: vec3) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; + public static array> (out: Out, v: vec3, ofs = 0) { + out[ofs + 0] = v.x; + out[ofs + 1] = v.y; + out[ofs + 2] = v.z; return out; } diff --git a/cocos/core/vmath/vec4.ts b/cocos/core/vmath/vec4.ts index 7eeb1c22f5..c941721d64 100644 --- a/cocos/core/vmath/vec4.ts +++ b/cocos/core/vmath/vec4.ts @@ -570,11 +570,11 @@ export default class vec4 { * @param v - The vector. * @return out. */ - public static array> (out: Out, v: vec4) { - out[0] = v.x; - out[1] = v.y; - out[2] = v.z; - out[3] = v.w; + public static array> (out: Out, v: vec4, ofs = 0) { + out[ofs + 0] = v.x; + out[ofs + 1] = v.y; + out[ofs + 2] = v.z; + out[ofs + 3] = v.w; return out; } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 22f284e785..e26f2fac38 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -36,18 +36,18 @@ type RecursivePartial = { export type PassOverrides = RecursivePartial; const _type2fn = { - [GFXType.INT]: (a: Float32Array, v: any) => a[0] = v, - [GFXType.INT2]: (a: Float32Array, v: any) => vec2.array(a, v), - [GFXType.INT3]: (a: Float32Array, v: any) => vec3.array(a, v), - [GFXType.INT4]: (a: Float32Array, v: any) => vec4.array(a, v), - [GFXType.FLOAT]: (a: Float32Array, v: any) => a[0] = v, - [GFXType.FLOAT2]: (a: Float32Array, v: any) => vec2.array(a, v), - [GFXType.FLOAT3]: (a: Float32Array, v: any) => vec3.array(a, v), - [GFXType.FLOAT4]: (a: Float32Array, v: any) => vec4.array(a, v), - [GFXType.COLOR4]: (a: Float32Array, v: any) => color4.array(a, v), - [GFXType.MAT2]: (a: Float32Array, v: any) => mat2.array(a, v), - [GFXType.MAT3]: (a: Float32Array, v: any) => mat3.array(a, v), - [GFXType.MAT4]: (a: Float32Array, v: any) => mat4.array(a, v), + [GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, + [GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => vec2.array(a, v, idx * 2), + [GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => vec3.array(a, v, idx * 3), + [GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => vec4.array(a, v, idx * 4), + [GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v, + [GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => vec2.array(a, v, idx * 2), + [GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => vec3.array(a, v, idx * 3), + [GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => vec4.array(a, v, idx * 4), + [GFXType.COLOR4]: (a: Float32Array, v: any, idx: number = 0) => color4.array(a, v, idx * 4), + [GFXType.MAT2]: (a: Float32Array, v: any, idx: number = 0) => mat2.array(a, v, idx * 4), + [GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => mat3.array(a, v, idx * 9), + [GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => mat4.array(a, v, idx * 16), }; const _type2default = { @@ -206,16 +206,16 @@ export class Pass { return Pass.getBindingFromHandle(this.getHandle(name)); } - public setUniform (handle: number, value: any) { + public setUniform (handle: number, value: any, arrayIdx?: number) { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const idx = Pass.getIndexFromHandle(handle); const block = this._blocks[binding]; - _type2fn[type](block.views[idx], value); + _type2fn[type](block.views[idx], value, arrayIdx); block.dirty = true; } - public bindTextureView (binding: number, value: GFXTextureView) { + public bindTextureView (binding: number, value: GFXTextureView, arrayIdx?: number) { this._textureViews[binding] = value; for (const res of this._resources) { res.bindingLayout.bindTextureView(binding, value); diff --git a/playground/simple.html b/playground/simple.html index 7b6edcfc33..aaf4842886 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -64,6 +64,8 @@ material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js material.effectName = 'builtin-effect-unlit'; + material.setProperty('color', cc.Color.RED, 0, 0); + material.setProperty('color', cc.Color.BLUE, 0, 1); const len = 50; const models = [], passes = []; @@ -115,8 +117,8 @@ const x = Math.cos(rad + t), y = Math.sin(rad + t); let z = m._lpos.z + dt; if (z > len * 2) z = 0; m.setPosition(x * 2, y * 2, z); - color.fromHSV((x + 1) * 0.5, 0.5, 1); - passes[i].setUniform(handle, color); + // color.fromHSV((x + 1) * 0.5, 0.5, 1); + // passes[i].setUniform(handle, color); }); }); From 31ad0be86ab034288c4c598fda47be3c4007d60b Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 19:19:31 +0800 Subject: [PATCH 239/267] fix uniform array --- cocos/3d/assets/material.ts | 16 ++++++++++------ cocos/3d/framework/model-component.ts | 5 ++++- cocos/renderer/core/pass.ts | 15 +++++++++++++-- playground/simple.html | 3 +-- 4 files changed, 28 insertions(+), 11 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 0517ad898f..eb53bb51ab 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -120,14 +120,14 @@ export class Material extends Asset { * pass.setUniform should be used instead * if you need to do per-frame property update. */ - public setProperty (name: string, val: any, passIdx?: number, arrayIdx?: number) { + public setProperty (name: string, val: any, passIdx?: number) { let success = false; if (passIdx === undefined) { // set property for all applicable passes const passes = this._passes; const len = passes.length; for (let i = 0; i < len; i++) { const pass = passes[i]; - if (this._uploadProperty(pass, name, val, arrayIdx)) { + if (this._uploadProperty(pass, name, val)) { this._props[i][name] = val; success = true; } @@ -135,7 +135,7 @@ export class Material extends Asset { } else { if (passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; } const pass = this._passes[passIdx]; - if (this._uploadProperty(pass, name, val, arrayIdx)) { + if (this._uploadProperty(pass, name, val)) { this._props[passIdx][name] = val; success = true; } @@ -207,17 +207,21 @@ export class Material extends Asset { this.onPassChange(); } - protected _uploadProperty (pass: Pass, name: string, val: any, arrayIdx?: number) { + protected _uploadProperty (pass: Pass, name: string, val: any) { const handle = pass.getHandle(name); if (handle === undefined) { return false; } const bindingType = Pass.getBindingTypeFromHandle(handle); if (bindingType === GFXBindingType.UNIFORM_BUFFER) { - pass.setUniform(handle, val, arrayIdx); + if (Array.isArray(val)) { + pass.setUniformArray(handle, val); + } else { + pass.setUniform(handle, val); + } } else if (bindingType === GFXBindingType.SAMPLER) { const textureView = val instanceof GFXTextureView ? val : val.getGFXTextureView(); if (!textureView) { console.warn('texture asset incomplete!'); return false; } const binding = Pass.getBindingFromHandle(handle); - pass.bindTextureView(binding, textureView, arrayIdx); + pass.bindTextureView(binding, textureView); } return true; } diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index adfb368fbe..b6fd5e939d 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -169,6 +169,9 @@ export class ModelComponent extends RenderableComponent { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); + if (this._model) { + this._model.enabled = true; + } } public onDisable () { @@ -275,6 +278,6 @@ export class ModelComponent extends RenderableComponent { private _getBuiltinMaterial () { // classic ugly pink indicating missing material - return cc.BuiltinResMgr['default-material']; + return builtinResMgr['default-material']; } } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index e26f2fac38..b553ffecf3 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -206,12 +206,23 @@ export class Pass { return Pass.getBindingFromHandle(this.getHandle(name)); } - public setUniform (handle: number, value: any, arrayIdx?: number) { + public setUniform (handle: number, value: any) { const binding = Pass.getBindingFromHandle(handle); const type = Pass.getTypeFromHandle(handle); const idx = Pass.getIndexFromHandle(handle); const block = this._blocks[binding]; - _type2fn[type](block.views[idx], value, arrayIdx); + _type2fn[type](block.views[idx], value); + block.dirty = true; + } + + public setUniformArray (handle: number, value: any[]) { + const binding = Pass.getBindingFromHandle(handle); + const type = Pass.getTypeFromHandle(handle); + const idx = Pass.getIndexFromHandle(handle); + const block = this._blocks[binding]; + for (let i = 0; i < value.length; i++) { + _type2fn[type](block.views[idx], value[i], i); + } block.dirty = true; } diff --git a/playground/simple.html b/playground/simple.html index aaf4842886..b3788fa6d6 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -64,8 +64,7 @@ material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js material.effectName = 'builtin-effect-unlit'; - material.setProperty('color', cc.Color.RED, 0, 0); - material.setProperty('color', cc.Color.BLUE, 0, 1); + material.setProperty('color', [ cc.Color.RED, cc.Color.BLUE ]); const len = 50; const models = [], passes = []; From b57a838f608f2aa9c966fb0c3da4fe106ac4a423 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 24 Jan 2019 10:25:05 +0800 Subject: [PATCH 240/267] fix bug, recursive call --- cocos/scene-graph/base-node.ts | 158 ++++++++++++++++----------------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/cocos/scene-graph/base-node.ts b/cocos/scene-graph/base-node.ts index 57df433741..e8c5d35b9d 100644 --- a/cocos/scene-graph/base-node.ts +++ b/cocos/scene-graph/base-node.ts @@ -1058,7 +1058,7 @@ export class BaseNode extends CCObject { return; } - public emit?(type: string, ...args: any[]): void; + public emit? (type: string, ...args: any[]): void; protected _onSetParent (oldParent: this | null) { if (this._parent) { @@ -1083,58 +1083,42 @@ export class BaseNode extends CCObject { } protected _onPreDestroy () { - // marked as destroying - this._objFlags |= Destroying; - - // detach self and children from editor - const parent = this._parent; - const destroyByParent: boolean = (parent !== null) && ((parent._objFlags & Destroying) !== 0); - if (!destroyByParent && (CC_EDITOR || CC_TEST)) { - this._registerIfAttached!(false); - } - - // destroy children - // destroy children - for (const child of this._children) { - // destroy immediate so its _onPreDestroy can be called - child._destroyImmediate(); - } - - // destroy self components - for (const component of this._components) { - // destroy immediate so its _onPreDestroy can be called - // TO DO - // @ts-ignore - component._destroyImmediate(); - } - - for (const eventTarget of this.__eventTargets) { - if (eventTarget) { - eventTarget.targetOff(this); - } - } - this.__eventTargets.length = 0; - - // remove from persist - if (this._persistNode) { - cc.game.removePersistRootNode(this); - } - - if (!destroyByParent) { - // remove from parent - if (parent) { - const childIndex = parent._children.indexOf(this); - parent._children.splice(childIndex, 1); - if (parent.emit) { - parent.emit('child-removed', this); - } - } - } - - return destroyByParent; + this._onPreDestroyBase(); } protected _onHierarchyChanged (oldParent: this | null) { + return this._onHierarchyChangedBase(oldParent); + } + + protected _instantiate (cloned) { + if (!cloned) { + cloned = cc.instantiate._clone(this, this); + } + + const thisPrefabInfo = this._prefab; + if (CC_EDITOR && thisPrefabInfo) { + if (this !== thisPrefabInfo.root) { + // var PrefabUtils = Editor.require('scene://utils/prefab'); + // PrefabUtils.initClonedChildOfPrefab(cloned); + } + } + const syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; + if (syncing) { + // if (thisPrefabInfo._synced) { + // return clone; + // } + } else if (CC_EDITOR && cc.engine._isPlaying) { + cloned._name += ' (Clone)'; + } + + // reset and init + cloned._parent = null; + cloned._onBatchRestored(); + + return cloned; + } + + private _onHierarchyChangedBase (oldParent: this | null) { const newParent = this._parent; if (this._persistNode && !(newParent instanceof cc.Scene)) { cc.game.removePersistRootNode(this); @@ -1187,36 +1171,56 @@ export class BaseNode extends CCObject { } } - protected _onHierarchyChangedBase (oldParent: this) { - return this._onHierarchyChanged(oldParent); - } + private _onPreDestroyBase () { + // marked as destroying + this._objFlags |= Destroying; - protected _instantiate (cloned) { - if (!cloned) { - cloned = cc.instantiate._clone(this, this); + // detach self and children from editor + const parent = this._parent; + const destroyByParent: boolean = (parent !== null) && ((parent._objFlags & Destroying) !== 0); + if (!destroyByParent && (CC_EDITOR || CC_TEST)) { + this._registerIfAttached!(false); } - const thisPrefabInfo = this._prefab; - if (CC_EDITOR && thisPrefabInfo) { - if (this !== thisPrefabInfo.root) { - // var PrefabUtils = Editor.require('scene://utils/prefab'); - // PrefabUtils.initClonedChildOfPrefab(cloned); + // destroy children + // destroy children + for (const child of this._children) { + // destroy immediate so its _onPreDestroy can be called + child._destroyImmediate(); + } + + // destroy self components + for (const component of this._components) { + // destroy immediate so its _onPreDestroy can be called + // TO DO + // @ts-ignore + component._destroyImmediate(); + } + + for (const eventTarget of this.__eventTargets) { + if (eventTarget) { + eventTarget.targetOff(this); } } - const syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; - if (syncing) { - // if (thisPrefabInfo._synced) { - // return clone; - // } - } else if (CC_EDITOR && cc.engine._isPlaying) { - cloned._name += ' (Clone)'; + this.__eventTargets.length = 0; + + // remove from persist + if (this._persistNode) { + cc.game.removePersistRootNode(this); } - // reset and init - cloned._parent = null; - cloned._onBatchRestored(); + if (!destroyByParent) { + // remove from parent + if (parent) { + const childIndex = parent._children.indexOf(this); + parent._children.splice(childIndex, 1); + if (parent.emit) { + parent.emit('child-removed', this); + } + } + } - return cloned; + return destroyByParent; } // do remove component, only used internally @@ -1254,15 +1258,11 @@ export class BaseNode extends CCObject { } } - private _onSiblingIndexChanged?(siblingIndex: number): void; + private _onSiblingIndexChanged? (siblingIndex: number): void; - private _registerIfAttached?(attached: boolean): void; + private _registerIfAttached? (attached: boolean): void; - private _checkMultipleComp?(constructor: Function): boolean; - - private _onPreDestroyBase () { - return this._onPreDestroy(); - } + private _checkMultipleComp? (constructor: Function): boolean; } baseNodePolyfill(BaseNode); From fa00f10178a04f443c87531c3553f37e6372c215 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 11:37:53 +0800 Subject: [PATCH 241/267] fix gfx format type bug --- cocos/gfx/webgl/webgl-commands.ts | 144 ++++++++++--------- cocos/renderer/core/pass.ts | 9 +- cocos/renderer/ui/ui.ts | 224 +++++++++++++++++++----------- 3 files changed, 230 insertions(+), 147 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 7b98f5bdb7..2da1214f35 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -45,22 +45,22 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu switch (format) { case GFXFormat.R8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.R8SN: return WebGLRenderingContext.BYTE; - case GFXFormat.R8UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.R8I: return WebGLRenderingContext.INT; + case GFXFormat.R8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.R8I: return WebGLRenderingContext.BYTE; case GFXFormat.R16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; - case GFXFormat.R16UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.R16I: return WebGLRenderingContext.INT; + case GFXFormat.R16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.R16I: return WebGLRenderingContext.SHORT; case GFXFormat.R32F: return WebGLRenderingContext.FLOAT; case GFXFormat.R32UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.R32I: return WebGLRenderingContext.INT; case GFXFormat.RG8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.RG8SN: return WebGLRenderingContext.BYTE; - case GFXFormat.RG8UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.RG8I: return WebGLRenderingContext.INT; + case GFXFormat.RG8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RG8I: return WebGLRenderingContext.BYTE; case GFXFormat.RG16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; - case GFXFormat.RG16UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.RG16I: return WebGLRenderingContext.INT; + case GFXFormat.RG16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.RG16I: return WebGLRenderingContext.SHORT; case GFXFormat.RG32F: return WebGLRenderingContext.FLOAT; case GFXFormat.RG32UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RG32I: return WebGLRenderingContext.INT; @@ -68,11 +68,11 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu case GFXFormat.RGB8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.SRGB8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.RGB8SN: return WebGLRenderingContext.BYTE; - case GFXFormat.RGB8UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.RGB8I: return WebGLRenderingContext.INT; + case GFXFormat.RGB8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGB8I: return WebGLRenderingContext.BYTE; case GFXFormat.RGB16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; - case GFXFormat.RGB16UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.RGB16I: return WebGLRenderingContext.INT; + case GFXFormat.RGB16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.RGB16I: return WebGLRenderingContext.SHORT; case GFXFormat.RGB32F: return WebGLRenderingContext.FLOAT; case GFXFormat.RGB32UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RGB32I: return WebGLRenderingContext.INT; @@ -80,11 +80,11 @@ function GFXFormatToWebGLType (format: GFXFormat, device: WebGLGFXDevice): GLenu case GFXFormat.RGBA8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.SRGB8_A8: return WebGLRenderingContext.UNSIGNED_BYTE; case GFXFormat.RGBA8SN: return WebGLRenderingContext.BYTE; - case GFXFormat.RGBA8UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.RGBA8I: return WebGLRenderingContext.INT; + case GFXFormat.RGBA8UI: return WebGLRenderingContext.UNSIGNED_BYTE; + case GFXFormat.RGBA8I: return WebGLRenderingContext.BYTE; case GFXFormat.RGBA16F: return device.OES_texture_half_float ? device.OES_texture_half_float.HALF_FLOAT_OES : WebGLRenderingContext.FLOAT; - case GFXFormat.RGBA16UI: return WebGLRenderingContext.UNSIGNED_INT; - case GFXFormat.RGBA16I: return WebGLRenderingContext.INT; + case GFXFormat.RGBA16UI: return WebGLRenderingContext.UNSIGNED_SHORT; + case GFXFormat.RGBA16I: return WebGLRenderingContext.SHORT; case GFXFormat.RGBA32F: return WebGLRenderingContext.FLOAT; case GFXFormat.RGBA32UI: return WebGLRenderingContext.UNSIGNED_INT; case GFXFormat.RGBA32I: return WebGLRenderingContext.INT; @@ -1673,8 +1673,10 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { for (let u = 0; u < glUniform.count; ++u) { - if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2] !== glUniform.vi32![u * 2] || - gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2 + 1] !== glUniform.vi32![u * 2 + 1]) { + const idx = u * 2; + const uidx = glUniform.begin + idx; + if (gpuBinding.gpuBuffer.vf32[uidx] !== glUniform.vi32![idx] || + gpuBinding.gpuBuffer.vf32[uidx + 1] !== glUniform.vi32![idx + 1]) { _uniformValues.length = glUniform.count * 2; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1691,9 +1693,11 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { for (let u = 0; u < glUniform.count; ++u) { - if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3] !== glUniform.vi32![u * 3] || - gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 1] !== glUniform.vi32![u * 3 + 1] || - gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 2] !== glUniform.vi32![u * 3 + 2]) { + const idx = u * 3; + const uidx = glUniform.begin + idx; + if (gpuBinding.gpuBuffer.vf32[uidx] !== glUniform.vi32![idx] || + gpuBinding.gpuBuffer.vf32[uidx + 1] !== glUniform.vi32![idx + 1] || + gpuBinding.gpuBuffer.vf32[uidx + 2] !== glUniform.vi32![idx + 2]) { _uniformValues.length = glUniform.count * 3; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1710,10 +1714,12 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web case WebGLRenderingContext.BOOL_VEC4: case WebGLRenderingContext.INT_VEC4: { for (let u = 0; u < glUniform.count; ++u) { - if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4] !== glUniform.vi32![u * 4] || - gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 1] !== glUniform.vi32![u * 4 + 1] || - gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 2] !== glUniform.vi32![u * 4 + 2] || - gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 3] !== glUniform.vi32![u * 4 + 3]) { + const idx = u * 4; + const uidx = glUniform.begin + idx; + if (gpuBinding.gpuBuffer.vf32[uidx] !== glUniform.vi32![idx] || + gpuBinding.gpuBuffer.vf32[uidx + 1] !== glUniform.vi32![idx + 1] || + gpuBinding.gpuBuffer.vf32[uidx + 2] !== glUniform.vi32![idx + 2] || + gpuBinding.gpuBuffer.vf32[uidx + 3] !== glUniform.vi32![idx + 3]) { _uniformValues.length = glUniform.count * 4; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1745,8 +1751,10 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.FLOAT_VEC2: { for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2], glUniform.vf32![u * 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 2 + 1], glUniform.vf32![u * 2 + 1])) { + const idx = u * 2; + const uidx = glUniform.begin + idx; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1])) { _uniformValues.length = glUniform.count * 2; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1762,9 +1770,11 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.FLOAT_VEC3: { for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3], glUniform.vf32![u * 3]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 1], glUniform.vf32![u * 3 + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 3 + 2], glUniform.vf32![u * 3 + 2])) { + const idx = u * 3; + const uidx = glUniform.begin + idx; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2])) { _uniformValues.length = glUniform.count * 3; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1780,10 +1790,12 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.FLOAT_VEC4: { for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4], glUniform.vf32![u * 4]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 1], glUniform.vf32![u * 4 + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 2], glUniform.vf32![u * 4 + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 3], glUniform.vf32![u * 4 + 3])) { + const idx = u * 4; + const uidx = glUniform.begin + idx; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3])) { _uniformValues.length = glUniform.count * 4; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1799,10 +1811,12 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.FLOAT_MAT2: { for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4], glUniform.vf32![u * 4]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 1], glUniform.vf32![u * 4 + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 2], glUniform.vf32![u * 4 + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 4 + 3], glUniform.vf32![u * 4 + 3])) { + const idx = u * 4; + const uidx = glUniform.begin + idx; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3])) { _uniformValues.length = glUniform.count * 4; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1818,15 +1832,17 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.FLOAT_MAT3: { for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9], glUniform.vf32![u * 9]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 1], glUniform.vf32![u * 9 + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 2], glUniform.vf32![u * 9 + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 3], glUniform.vf32![u * 9 + 3]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 4], glUniform.vf32![u * 9 + 4]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 5], glUniform.vf32![u * 9 + 5]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 6], glUniform.vf32![u * 9 + 6]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 7], glUniform.vf32![u * 9 + 7]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 9 + 8], glUniform.vf32![u * 9 + 8])) { + const idx = u * 9; + const uidx = glUniform.begin + idx; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 4], glUniform.vf32![idx + 4]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 5], glUniform.vf32![idx + 5]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 6], glUniform.vf32![idx + 6]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 7], glUniform.vf32![idx + 7]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 8], glUniform.vf32![idx + 8])) { _uniformValues.length = glUniform.count * 9; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { @@ -1842,22 +1858,24 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.FLOAT_MAT4: { for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16], glUniform.vf32![u * 16]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 1], glUniform.vf32![u * 16 + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 2], glUniform.vf32![u * 16 + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 3], glUniform.vf32![u * 16 + 3]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 4], glUniform.vf32![u * 16 + 4]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 5], glUniform.vf32![u * 16 + 5]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 6], glUniform.vf32![u * 16 + 6]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 7], glUniform.vf32![u * 16 + 7]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 8], glUniform.vf32![u * 16 + 8]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 9], glUniform.vf32![u * 16 + 9]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 10], glUniform.vf32![u * 16 + 10]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 11], glUniform.vf32![u * 16 + 11]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 12], glUniform.vf32![u * 16 + 12]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 13], glUniform.vf32![u * 16 + 13]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 14], glUniform.vf32![u * 16 + 14]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u * 16 + 15], glUniform.vf32![u * 16 + 15])) { + const idx = u * 16; + const uidx = glUniform.begin + idx; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 4], glUniform.vf32![idx + 4]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 5], glUniform.vf32![idx + 5]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 6], glUniform.vf32![idx + 6]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 7], glUniform.vf32![idx + 7]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 8], glUniform.vf32![idx + 8]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 9], glUniform.vf32![idx + 9]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 10], glUniform.vf32![idx + 10]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 11], glUniform.vf32![idx + 11]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 12], glUniform.vf32![idx + 12]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 13], glUniform.vf32![idx + 13]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 14], glUniform.vf32![idx + 14]) || + CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 15], glUniform.vf32![idx + 15])) { _uniformValues.length = glUniform.count * 16; for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index b553ffecf3..8b2f5d27fb 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -226,7 +226,14 @@ export class Pass { block.dirty = true; } - public bindTextureView (binding: number, value: GFXTextureView, arrayIdx?: number) { + public bindBuffer (binding: number, value: GFXBuffer) { + this._buffers[binding] = value; + for (const res of this._resources) { + res.bindingLayout.bindBuffer(binding, value); + } + } + + public bindTextureView (binding: number, value: GFXTextureView) { this._textureViews[binding] = value; for (const res of this._resources) { res.bindingLayout.bindTextureView(binding, value); diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 74b2a3cda7..faa3f92d41 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -8,6 +8,7 @@ import { IMeshBufferInitData, MeshBuffer } from '../../3d/ui/mesh-buffer'; import { SpriteFrame } from '../../assets/CCSpriteFrame'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; +import { mat4 } from '../../core/vmath'; import { GFXBindingLayout } from '../../gfx/binding-layout'; import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; @@ -16,17 +17,35 @@ import { GFXCommandBufferType, GFXFormat, GFXMemoryUsageBit, + GFXType, IGFXRect, } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; -import { GFXTexture } from '../../gfx/texture'; +import { GFXUniformBlock } from '../../gfx/shader'; +import { GFXTextureView } from '../../gfx/texture-view'; import { vfmt } from '../../gfx/vertex-format-sample'; import { BaseNode } from '../../scene-graph/base-node'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; import { IUIMaterialInfo, UIMaterial } from './ui-material'; +export class UBOUI { + public static MAT_VIEW_PROJ_OFFSET: number = 0; + public static COUNT: number = UBOUI.MAT_VIEW_PROJ_OFFSET + 16; + public static SIZE: number = UBOUI.COUNT * 4; + + public static BLOCK: GFXUniformBlock = { + binding: 30, name: 'CCUI', members: [ + { name: 'cc_matViewProj', type: GFXType.MAT4, count: 1 }, + ], + }; + + public view: Float32Array = new Float32Array(UBOUI.COUNT); +} + +const _mat4Array = new Float32Array(16); + export interface IUIBufferBatch { vf32: Float32Array; vui16: Uint16Array; @@ -41,7 +60,7 @@ export interface IUIDrawBatch { camera: Camera; bufferBatch: IUIBufferBatch; uiMaterial: UIMaterial; - texture: GFXTexture; + texView: GFXTextureView; } export interface IUIRenderData { @@ -74,6 +93,8 @@ export class UI { private _bufferBatches: IUIBufferBatch[] = []; private _uiMaterial: UIMaterial | null = null; private _uiMaterials: UIMaterial[] = []; + private _uboUI: UBOUI = new UBOUI(); + private _uiUBO: GFXBuffer | null = null; private _batches: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; @@ -109,18 +130,29 @@ export class UI { this._uiMaterial = this.createUIMaterial({ material: builtinResMgr.get('sprite-material')}); + this._uiUBO = this._device.createBuffer({ + usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: UBOUI.SIZE, + }); + return true; } public destroy () { this.destroyUIMaterials(); + if (this._uiUBO) { + this._uiUBO.destroy(); + this._uiUBO = null; + } + for (const buffBatch of this._bufferBatches) { buffBatch.vb!.destroy(); buffBatch.ib!.destroy(); buffBatch.ia!.destroy(); } - this._bufferBatches = []; + this._bufferBatches.splice(0); if (this._cmdBuff) { this._cmdBuff.destroy(); @@ -201,79 +233,7 @@ export class UI { // Merge batch if (this._commitUIRenderDatas.length) { - const first = this._commitUIRenderDatas[0]; - - let curCamera: Camera | null = null; - let curTexture: GFXTexture | null = null; - let bufferBatchIdx = 0; - let curBufferBatch: IUIBufferBatch = this._bufferBatches[bufferBatchIdx++]; - let vOffset = 0; - let iOffset = 0; - let isNewBatch = false; - - for (const uiRenderData of this._commitUIRenderDatas) { - - if (iOffset + uiRenderData.meshBuffer.vData!.length > 65535) { - if (bufferBatchIdx >= this._bufferBatches.length) { - this.createBufferBatch(); - } - - curBufferBatch = this._bufferBatches[bufferBatchIdx++]; - vOffset = 0; - iOffset = 0; - isNewBatch = true; - } else { - isNewBatch = false; - } - - // merge vertices - const vf32: Float32Array = uiRenderData.meshBuffer.vData!; - const vbSize = (vf32.length + vOffset) * 4; - if (vbSize > curBufferBatch.vbSize) { - curBufferBatch.vbSize = vbSize; - const lastVF32 = curBufferBatch.vf32; - curBufferBatch.vf32 = new Float32Array(vf32.length + vOffset); - curBufferBatch.vf32.set(lastVF32, 0); - } - - curBufferBatch.vf32.set(vf32, vOffset); - - // merge indices - const vui16: Uint16Array = uiRenderData.meshBuffer.iData!; - const ibSize = (vui16.length + iOffset) * 2; - if (ibSize > curBufferBatch.ibSize) { - curBufferBatch.ibSize = ibSize; - const lastVUI16 = curBufferBatch.vui16; - curBufferBatch.vui16 = new Uint16Array(vui16.length + iOffset); - curBufferBatch.vui16.set(lastVUI16, 0); - } - - for (let n = 0; n < vui16.length; ++n) { - curBufferBatch.vui16[iOffset + n] = vui16[n] + vOffset; - } - - curBufferBatch.vui16.set(vui16, iOffset); - - vOffset += vf32.length; - iOffset += vui16.length; - - if (curCamera !== uiRenderData.camera) { - isNewBatch = true; - curCamera = uiRenderData.camera; - } else if (curTexture !== uiRenderData.texture.getGFXTexture()) { - curTexture = uiRenderData.texture.getGFXTexture(); - isNewBatch = true; - } - - if (isNewBatch) { - const batch = this._drawBatchPool.add(); - batch.camera = curCamera; - batch.bufferBatch = curBufferBatch; - batch.uiMaterial = this._uiMaterial!; - batch.texture = curTexture!; - this._batches.push(batch); - } - } // for + this.mergeBatches(); // update buffers for (const bufferBatch of this._bufferBatches) { @@ -303,22 +263,42 @@ export class UI { cmdBuff.begin(); + let curCamera: Camera | null = null; + for (let i = 0; i < this._batches.length; ++i) { const batch = this._batches.array[i]; const camera = batch.camera!; - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; + if (curCamera !== camera) { + if (curCamera) { + cmdBuff.endRenderPass(); + } + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; + + cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); + curCamera = camera; + + camera.update(); + + // update ubo + mat4.array(_mat4Array, camera.matViewProj); + this._uboUI.view.set(_mat4Array, UBOUI.MAT_VIEW_PROJ_OFFSET); + + this._uiUBO!.update(this._uboUI.view); + } + + material.bindingLayout.bindBuffer(0, this._uiUBO!); + material.bindingLayout.bindTextureView(5, batch.texView); + material.bindingLayout.update(); - cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); cmdBuff.bindPipelineState(material.pipelineState); cmdBuff.bindBindingLayout(material.bindingLayout); - cmdBuff.bindInputAssembler(batch.bufferBatch!.ia!); - cmdBuff.draw(batch.bufferBatch!.ia!); - - cmdBuff.endRenderPass(); + cmdBuff.bindInputAssembler(batch.bufferBatch.ia); + cmdBuff.draw(batch.bufferBatch.ia); } + cmdBuff.endRenderPass(); cmdBuff.end(); this._device.queue.submit([cmdBuff]); @@ -378,6 +358,84 @@ export class UI { comp.postUpdateAssembler(); } + private mergeBatches () { + let curCamera: Camera | null = null; + let curTexView: GFXTextureView | null = null; + let bufferBatchIdx = 0; + let curBufferBatch: IUIBufferBatch = this._bufferBatches[bufferBatchIdx++]; + let vOffset = 0; + let iOffset = 0; + let vf32: Float32Array; + let vui16: Uint16Array; + let vbSize = 0; + let ibSize = 0; + let isNewBatch = false; + + for (const uiRenderData of this._commitUIRenderDatas) { + + if (iOffset + uiRenderData.meshBuffer.vData!.length > 65535) { + if (bufferBatchIdx >= this._bufferBatches.length) { + this.createBufferBatch(); + } + + curBufferBatch = this._bufferBatches[bufferBatchIdx++]; + vOffset = 0; + iOffset = 0; + isNewBatch = true; + } else { + isNewBatch = false; + } + + // merge vertices + vf32 = uiRenderData.meshBuffer.vData!; + vbSize = (vf32.length + vOffset) * 4; + if (vbSize > curBufferBatch.vbSize) { + curBufferBatch.vbSize = vbSize; + const lastVF32 = curBufferBatch.vf32; + curBufferBatch.vf32 = new Float32Array(vf32.length + vOffset); + curBufferBatch.vf32.set(lastVF32, 0); + } + + curBufferBatch.vf32.set(vf32, vOffset); + + // merge indices + vui16 = uiRenderData.meshBuffer.iData!; + ibSize = (vui16.length + iOffset) * 2; + if (ibSize > curBufferBatch.ibSize) { + curBufferBatch.ibSize = ibSize; + const lastVUI16 = curBufferBatch.vui16; + curBufferBatch.vui16 = new Uint16Array(vui16.length + iOffset); + curBufferBatch.vui16.set(lastVUI16, 0); + } + + for (let n = 0; n < vui16.length; ++n) { + curBufferBatch.vui16[iOffset + n] = vui16[n] + vOffset; + } + + curBufferBatch.vui16.set(vui16, iOffset); + + vOffset += vf32.length; + iOffset += vui16.length; + + if (curCamera !== uiRenderData.camera) { + isNewBatch = true; + curCamera = uiRenderData.camera; + } else if (curTexView !== uiRenderData.texture.getGFXTextureView()) { + curTexView = uiRenderData.texture.getGFXTextureView(); + isNewBatch = true; + } + + if (isNewBatch) { + const batch = this._drawBatchPool.add(); + batch.camera = curCamera; + batch.bufferBatch = curBufferBatch; + batch.uiMaterial = this._uiMaterial!; + batch.texView = curTexView!; + this._batches.push(batch); + } + } // for + } + private createBufferBatch (): IUIBufferBatch { const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; From de4449490ff9cc58189bb61931ed77ab09d92555 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 23 Jan 2019 19:27:35 +0800 Subject: [PATCH 242/267] back to default unlit --- cocos/3d/builtin/effects.js | 6 +++--- cocos/3d/framework/model-component.ts | 1 + playground/simple.html | 5 ++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 0bacfd6b65..3917e19e58 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -43,7 +43,7 @@ export default [ { "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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[2];\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[0] + color[1];\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\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":[]}, @@ -55,8 +55,8 @@ export default [ {"name":"mainTiling", "type":14, "count":1, "size":8}, {"name":"mainOffset", "type":14, "count":1, "size":8} ]}, - {"name": "Constant", "size": 32, "defines": ["USE_COLOR"], "binding": 1, "members": [ - {"name":"color", "type":16, "count":2, "size":32} + {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [ + {"name":"color", "type":16, "count":1, "size":16} ]} ], "samplers": [ diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index fbdf94f85e..a16437731f 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +import { builtinResMgr } from '../../3d/builtin'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import Enum from '../../core/value-types/enum'; import { Model } from '../../renderer/scene/model'; diff --git a/playground/simple.html b/playground/simple.html index b3788fa6d6..7b6edcfc33 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -64,7 +64,6 @@ material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js material.effectName = 'builtin-effect-unlit'; - material.setProperty('color', [ cc.Color.RED, cc.Color.BLUE ]); const len = 50; const models = [], passes = []; @@ -116,8 +115,8 @@ const x = Math.cos(rad + t), y = Math.sin(rad + t); let z = m._lpos.z + dt; if (z > len * 2) z = 0; m.setPosition(x * 2, y * 2, z); - // color.fromHSV((x + 1) * 0.5, 0.5, 1); - // passes[i].setUniform(handle, color); + color.fromHSV((x + 1) * 0.5, 0.5, 1); + passes[i].setUniform(handle, color); }); }); From 5a0f92243d20f5296d377405b2dcaa43c5e8dcb8 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 24 Jan 2019 14:11:08 +0800 Subject: [PATCH 243/267] light component --- cocos/3d/builtin/effects.js | 64 ++- cocos/3d/framework/light-component.js | 458 ---------------------- cocos/3d/framework/light-component.ts | 301 ++++++++++++++ cocos/3d/framework/model-component.ts | 8 +- cocos/pipeline/render-pipeline.ts | 37 +- cocos/renderer/core/effect.ts | 14 +- cocos/renderer/core/pass.ts | 4 +- cocos/renderer/scene/directional-light.ts | 20 + cocos/renderer/scene/light.ts | 33 +- cocos/renderer/scene/point-light.ts | 24 ++ cocos/renderer/scene/render-scene.ts | 72 +++- cocos/renderer/scene/spot-light.ts | 34 ++ playground/simple.html | 9 +- tslint.json | 3 +- 14 files changed, 589 insertions(+), 492 deletions(-) delete mode 100644 cocos/3d/framework/light-component.js create mode 100644 cocos/3d/framework/light-component.ts create mode 100644 cocos/renderer/scene/directional-light.ts create mode 100644 cocos/renderer/scene/point-light.ts create mode 100644 cocos/renderer/scene/spot-light.ts diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 3917e19e58..5a34563427 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,12 +1,70 @@ // absolute essential effects export default [ + { + "name": "builtin-effect-phong", + "techniques": [{"passes":[{"program":"builtin-effect-phong|phong-vs:vert|phong-fs:frag", "properties":{"diffuseColor":{"type":17, "value":[0.3, 0.3, 0.3, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "diffuse_texture":{"type":29, "value":"grey"}, "specularColor":{"type":17, "value":[0, 0, 0, 0]}, "specular_texture":{"type":29, "value":"grey"}, "emissiveColor":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "glossiness":{"type":13, "value":[10]}, "normal_texture":{"type":29, "value":"normal"}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], + "shaders": [ + { + "name": "builtin-effect-phong|phong-vs:vert|phong-fs:frag", + "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\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 vec3 normal_w;\nvarying vec3 pos_w;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\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\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n #if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\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 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;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\n}\nstruct Lighting {\n vec3 diffuse;\n vec3 specular;\n};\nLighting brdf(LightInfo info, vec3 N, vec3 V, float glossiness) {\n Lighting res;\n res.diffuse = info.radiance * max(0.0, dot(N, info.lightDir));\n vec3 H = normalize(V + info.lightDir);\n float NdotH = max(0.0, dot(N, H));\n NdotH = pow(NdotH, max(1.0, glossiness * 128.0));\n res.specular = info.radiance * NdotH;\n return res;\n}\nLighting getPhongLighting(vec3 pos_w, vec3 N, vec3 V, float glossiness) {\n Lighting result;\n result.diffuse = vec3(0, 0, 0);\n result.specular = vec3(0, 0, 0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n Lighting info = brdf(computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n Lighting info = brdf(computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n Lighting info = brdf(computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n return result;\n}\n#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 normal_w;\nvarying vec3 pos_w;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\nstruct phongMaterial\n{\n vec3 diffuse;\n vec3 emissive;\n vec3 specular;\n float glossiness;\n float opacity;\n};\n uniform vec4 diffuseColor;\n uniform vec4 emissiveColor;\n uniform vec4 specularColor;\n uniform float glossiness;\n uniform float alphaTestThreshold;\n#if USE_DIFFUSE_TEXTURE\n uniform sampler2D diffuse_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_SPECULAR && USE_SPECULAR_TEXTURE\n uniform sampler2D specular_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( uv0.st );\n vec2 st1 = dFdy( uv0.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nphongMaterial getPhongMaterial() {\n phongMaterial result;\n #if USE_DIFFUSE_TEXTURE\n vec4 baseColor = diffuseColor * gammaToLinearSpaceRGBA(texture2D(diffuse_texture, uv0));\n result.diffuse = baseColor.rgb;\n result.opacity = baseColor.a;\n #else\n result.diffuse = diffuseColor.rgb;\n result.opacity = diffuseColor.a;\n #endif\n #if USE_EMISSIVE\n result.emissive = emissiveColor.rgb;\n #if USE_EMISSIVE_TEXTURE\n result.emissive *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n #endif\n #if USE_SPECULAR\n result.specular = specularColor.rgb;\n #if USE_SPECULAR_TEXTURE\n result.specular = gammaToLinearSpaceRGB(texture2D(specular_texture, uv0).rgb);\n #endif\n result.glossiness = glossiness;\n #endif\n return result;\n}\nvec4 composePhongShading(Lighting lighting, phongMaterial mtl, float shadow) {\n vec4 o = vec4(0.0, 0.0, 0.0, 1.0);\n \n o.xyz = lighting.diffuse * mtl.diffuse;\n #if USE_EMISSIVE\n o.xyz += mtl.emissive;\n #endif\n #if USE_SPECULAR\n o.xyz += lighting.specular * mtl.specular;\n #endif\n o.xyz *= shadow;\n o.w = mtl.opacity;\n return o;\n}\nvec4 frag () {\n Lighting phongLighting;\n vec3 viewDirection = normalize(cc_cameraPos.xyz - pos_w);\n phongMaterial mtl = getPhongMaterial();\n #if USE_ALPHA_TEST\n if(mtl.opacity < alphaTestThreshold) discard;\n #endif\n vec3 normal = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n normal = getNormal(pos_w, normal);\n #endif\n phongLighting = getPhongLighting(pos_w, normal, viewDirection, mtl.glossiness);\n phongLighting.diffuse += vec3(0.5); \n #if CC_USE_SHADOW_MAP\n vec4 finalColor = composePhongShading(phongLighting, mtl, computeShadow());\n #else\n vec4 finalColor = composePhongShading(phongLighting, mtl, 1.0);\n #endif\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"USE_DIFFUSE_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, + {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, + {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, + {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, + {"name":"USE_SPECULAR", "type":"boolean", "defines":[]}, + {"name":"USE_SPECULAR_TEXTURE", "type":"boolean", "defines":["USE_SPECULAR"]}, + {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8} + ]}, + {"name": "Constants", "size": 56, "defines": [], "binding": 1, "members": [ + {"name":"diffuseColor", "type":16, "count":1, "size":16}, + {"name":"emissiveColor", "type":16, "count":1, "size":16}, + {"name":"specularColor", "type":16, "count":1, "size":16}, + {"name":"glossiness", "type":13, "count":1, "size":4}, + {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} + ]} + ], + "samplers": [ + {"name":"diffuse_texture", "type":29, "count":1, "defines":["USE_DIFFUSE_TEXTURE"], "binding":2}, + {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":3}, + {"name":"specular_texture", "type":29, "count":1, "defines":["USE_SPECULAR", "USE_SPECULAR_TEXTURE"], "binding":4}, + {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":5} + ], + "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives"} + }, + { + "name": "builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag", + "vert": "\nattribute vec3 a_position;\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 float vDepth;\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 mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} + ], + "blocks": [], + "samplers": [], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-skybox", "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], "shaders": [ { "name": "builtin-effect-skybox|sky-vs|sky-fs", - "vert": "\n attribute vec3 a_position;\n \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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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.xyww;\n viewDir = a_position;\n }\n", + "vert": "\n attribute vec3 a_position;\n \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.xyww;\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":[]} @@ -25,7 +83,7 @@ export default [ "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * pos;\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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": [], @@ -42,7 +100,7 @@ export default [ "shaders": [ { "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", - "vert": "\nattribute vec3 a_position;\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_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform vec4 cc_cameraSize;\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", + "vert": "\nattribute vec3 a_position;\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":[]}, diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js deleted file mode 100644 index 1822c7e15a..0000000000 --- a/cocos/3d/framework/light-component.js +++ /dev/null @@ -1,458 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -import { Color, Enum } from '../../core/value-types'; -import { toRadian } from '../../core/vmath'; -import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator"; -import { Component } from '../../components/component'; - -/** - * !#en The light source type - * - * !#ch 光源类型 - * @static - * @enum LightComponent.Type - */ -const LightType = Enum({ - /** - * !#en The direction of light - * - * !#ch 平行光 - * @property Directional - * @readonly - * @type {Number} - */ - Directional: 0, - /** - * !#en The point of light - * - * !#ch 点光源 - * @property Point - * @readonly - * @type {Number} - */ - Point: 1, - /** - * !#en The spot of light - * - * !#ch 聚光灯 - * @property Spot - * @readonly - * @type {Number} - */ - Spot: 2, -}); - -/** - * !#en The shadow type - * - * !#ch 阴影类型 - * @static - * @enum LightComponent.ShadowType - */ -const LightShadowType = Enum({ - /** - * !#en No shadows - * - * !#ch 阴影关闭 - * @property None - * @readonly - * @type {Number} - */ - None: 0, - /** - * !#en Soft shadows - * - * !#ch 软阴影 - * @property Soft - * @readonly - * @type {Number} - */ - Soft: 1, - /** - * !#en Hard shadows - * - * !#ch 阴硬影 - * @property Hard - * @readonly - * @type {Number} - */ - Hard: 2, -}); - -/** - * !#en The Light Component - * - * !#ch 光源组件 - * @class LightComponent - * @extends Component - */ -@ccclass('cc.LightComponent') -@menu('Components/LightComponent') -@executeInEditMode -export default class LightComponent extends Component { - @property - _type = LightType.Directional; - - @property - _color = Color.WHITE; - - @property - _intensity = 1; - - @property - _range = 1; - - @property - _spotAngle = 60; - - @property - _spotExp = 1; - - @property - _shadowType = LightShadowType.None; - - @property - _shadowResolution = 1024; - - @property - _shadowDarkness = 0.5; - - @property - _shadowMinDepth = 1; - - @property - _shadowMaxDepth = 1000; - - @property - _shadowDepthScale = 250; - - @property - _shadowFrustumSize = 50; - - @property - _shadowBias = 0.0005; - - /** - * !#en The light source type - * - * !#ch 光源类型 - * - * @type {Number} - */ - @property({ - type: LightType - }) - get type() { - return this._type; - } - - set type(val) { - this._type = val; - - let type = renderer.LIGHT_DIRECTIONAL; - if (this._type === LightType.Point) { - type = renderer.LIGHT_POINT; - } else if (this._type === LightType.Spot) { - type = renderer.LIGHT_SPOT; - } - if (this._light) - this._light.setType(type); - } - - /** - * !#en The light source color - * - * !#ch 光源颜色 - * @type {Color} - */ - @property - get color() { - return this._color; - } - - set color(val) { - this._color = val; - if (this._light) - this._light.setColor(val.r / 255, val.g / 255, val.b / 255); - } - - /** - * !#en The light source intensity - * - * !#ch 光源强度 - * @type {Number} - */ - @property - get intensity() { - return this._intensity; - } - - set intensity(val) { - this._intensity = val; - if (this._light) - this._light.setIntensity(val); - } - - /** - * !#en The light range, used for spot and point light - * - * !#ch 针对聚光灯和点光源设置光源范围 - * @type {Number} - */ - @property - get range() { - return this._range; - } - - set range(val) { - this._range = val; - if (this._light) - this._light.setRange(val); - } - - /** - * !#en The spot light cone angle - * - * !#ch 聚光灯锥角 - * @type {Number} - */ - @property - get spotAngle() { - return this._spotAngle; - } - - set spotAngle(val) { - this._spotAngle = val; - if (this._light) - this._light.setSpotAngle(toRadian(val)); - } - - /** - * !#en The spot light exponential - * - * !#ch 聚光灯指数 - * @type {Number} - */ - @property - get spotExp() { - return this._spotExp; - } - - set spotExp(val) { - this._spotExp = val; - if (this._light) - this._light.setSpotExp(val); - } - - /** - * !#en The shadow type - * - * !#ch 阴影类型 - * @type {Number} shadowType - */ - @property({ - type: LightShadowType - }) - get shadowType() { - return this._shadowType; - } - - set shadowType(val) { - this._shadowType = val; - - let type = renderer.SHADOW_NONE; - if (val === LightShadowType.Hard) { - type = renderer.SHADOW_HARD; - } else if (val === LightShadowType.Soft) { - type = renderer.SHADOW_SOFT; - } - if (this._light) - this._light.setShadowType(type); - } - - /** - * !#en The shadow resolution - * - * !#ch 阴影分辨率 - * - * @type {Number} - */ - @property - get shadowResolution() { - return this._shadowResolution; - } - - set shadowResolution(val) { - this._shadowResolution = val; - if (this._light) - this._light.setShadowResolution(val); - } - - /** - * !#en The shadow darkness - * - * !#ch 阴影灰度值 - * - * @type {Number} - */ - @property - get shadowDarkness() { - return this._shadowDarkness; - } - - set shadowDarkness(val) { - this._shadowDarkness = val; - if (this._light) - this._light.setShadowDarkness(val); - } - - /** - * !#en The shadow min depth - * - * !#ch 阴影最小深度 - * - * @type {Number} - */ - @property - get shadowMinDepth() { - return this._shadowMinDepth; - } - - set shadowMinDepth(val) { - this._shadowMinDepth = val; - if (this._light) - this._light.setShadowMinDepth(val); - } - - /** - * !#en The shadow max depth - * - * !#ch 阴影最大深度 - * - * @type {Number} - */ - @property - get shadowMaxDepth() { - return this._shadowMaxDepth; - } - - set shadowMaxDepth(val) { - this._shadowMaxDepth = val; - if (this._light) - this._light.setShadowMaxDepth(val); - } - - /** - * !#en The shadow depth scale - * - * !#ch 阴影深度比例 - * - * @type {Number} - */ - @property - get shadowDepthScale() { - return this._shadowDepthScale; - } - - set shadowDepthScale(val) { - this._shadowDepthScale = val; - if (this._light) - this._light.setShadowDepthScale(val); - } - - /** - * !#en The shadow frustum size - * - * !#ch 阴影截锥体大小 - * - * @type {Number} - */ - @property - get shadowFrustumSize() { - return this._shadowFrustumSize; - } - - set shadowFrustumSize(val) { - this._shadowFrustumSize = val; - if (this._light) - this._light.setShadowFrustumSize(val); - } - - /** - * !#en The shadow bias - * - * !#ch 阴影偏移量 - * - * @type {Number} - */ - @property - get shadowBias() { - return this._shadowBias; - } - - set shadowBias(val) { - this._shadowBias = val; - if (this._light) - this._light.setShadowBias(val); - } - - static Type = LightType; - - static ShadowType = LightShadowType; - - constructor() { - super(); - } - - onLoad() { - - } - - onEnable() { - // this._light = this._getRenderScene().createLight(this.name); - // this._light.setNode(this.node); - this.type = this._type; - this.color = this._color; - this.intensity = this._intensity; - this.range = this._range; - this.spotAngle = this._spotAngle; - this.spotExp = this._spotExp; - this.shadowType = this._shadowType; - this.shadowResolution = this._shadowResolution; - this.shadowDarkness = this._shadowDarkness; - this.shadowMaxDepth = this._shadowMaxDepth; - this.shadowDepthScale = this._shadowDepthScale; - this.shadowFrustumSize = this._shadowFrustumSize; - this.shadowBias = this._shadowBias; - } - - onDisable() { - // this._getRenderScene().destroyLight(this._light); - } - - onDestroy() { - - } -} diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts new file mode 100644 index 0000000000..a15be397b5 --- /dev/null +++ b/cocos/3d/framework/light-component.ts @@ -0,0 +1,301 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator'; +import { Color, Enum } from '../../core/value-types'; +import { toRadian } from '../../core/vmath'; +import { Light, LightType } from '../../renderer/scene/light'; +import { PointLight } from '../../renderer/scene/point-light'; +import { SpotLight } from '../../renderer/scene/spot-light'; + +/** + * !#en The light source type + * + * !#ch 光源类型 + * @static + * @enum LightComponent.Type + */ +const Type = Enum({ + /** + * !#en The direction of light + * + * !#ch 平行光 + * @property Directional + * @readonly + * @type {Number} + */ + DIRECTIONAL: LightType.DIRECTIONAL, + /** + * !#en The point of light + * + * !#ch 点光源 + * @property Point + * @readonly + * @type {Number} + */ + POINT: LightType.POINT, + /** + * !#en The spot of light + * + * !#ch 聚光灯 + * @property Spot + * @readonly + * @type {Number} + */ + SPOT: LightType.SPOT, +}); + +/** + * !#en The shadow type + * + * !#ch 阴影类型 + * @static + * @enum LightComponent.ShadowType + */ +const LightShadowType = Enum({ + /** + * !#en No shadows + * + * !#ch 阴影关闭 + * @property None + * @readonly + * @type {Number} + */ + None: 0, + /** + * !#en Soft shadows + * + * !#ch 软阴影 + * @property Soft + * @readonly + * @type {Number} + */ + Soft: 1, + /** + * !#en Hard shadows + * + * !#ch 阴硬影 + * @property Hard + * @readonly + * @type {Number} + */ + Hard: 2, +}); + +/** + * !#en The Light Component + * + * !#ch 光源组件 + * @class LightComponent + * @extends Component + */ +@ccclass('cc.LightComponent') +@menu('Components/LightComponent') +@executeInEditMode +export default class LightComponent extends Component { + + public static Type = Type; + public static ShadowType = LightShadowType; + + @property + protected _type = Type.DIRECTIONAL; + @property + protected _color = Color.WHITE; + @property + protected _intensity = 1; + @property + protected _range = 10; + @property + protected _spotAngle = 60; + + // @property + // protected _shadowType = LightShadowType.None; + // @property + // protected _shadowResolution = 1024; + // @property + // protected _shadowDarkness = 0.5; + // @property + // protected _shadowMinDepth = 1; + // @property + // protected _shadowMaxDepth = 1000; + // @property + // protected _shadowDepthScale = 250; + // @property + // protected _shadowFrustumSize = 50; + // @property + // protected _shadowBias = 0.0005; + + protected _light: Light | null = null; + protected _colorData = [1, 1, 1]; + + /** + * !#en The light source type + * + * !#ch 光源类型 + * + * @type {Number} + */ + @property({ + type: Type, + }) + get type () { + return this._type; + } + + set type (val) { + this._type = val; + this._destroyLight(); + this._createLight(); + } + + /** + * !#en The light source color + * + * !#ch 光源颜色 + * @type {Color} + */ + @property + get color () { + return this._color; + } + + set color (val) { + this._color = val; + this._colorData[0] = val.r * this._intensity; + this._colorData[1] = val.g * this._intensity; + this._colorData[2] = val.b * this._intensity; + if (this._light) { + this._light.color = this._colorData; + } + } + + /** + * !#en The light source intensity + * + * !#ch 光源强度 + * @type {Number} + */ + @property + get intensity () { + return this._intensity; + } + + set intensity (val) { + this._intensity = val; + this._colorData[0] = this._color.r * val; + this._colorData[1] = this._color.g * val; + this._colorData[2] = this._color.b * val; + if (this._light) { + this._light.color = this._colorData; + } + } + + /** + * !#en The light range, used for spot and point light + * + * !#ch 针对聚光灯和点光源设置光源范围 + * @type {Number} + */ + @property + get range () { + return this._range; + } + + set range (val) { + this._range = val; + if (this._light && this._light instanceof PointLight || this._light instanceof SpotLight) { + this._light.range = val; + } + } + + /** + * !#en The spot light cone angle + * + * !#ch 聚光灯锥角 + * @type {Number} + */ + @property + get spotAngle () { + return this._spotAngle; + } + + set spotAngle (val) { + this._spotAngle = val; + if (this._light && this._light instanceof SpotLight) { + this._light.spotAngle = toRadian(val); + } + } + + public onEnable () { + if (this._light) { this._light.enabled = true; return; } + this._createLight(); + } + + public onDisable () { + if (this._light) { this._light.enabled = false; } + } + + public onDestroy () { + this._destroyLight(); + } + + protected _createLight () { + if (!this.node._scene || this._light) { return; } + const scene = this._getRenderScene(); + switch (this._type) { + case Type.DIRECTIONAL: + this._light = scene.createDirectionalLight(this.name); + break; + case Type.POINT: + this._light = scene.createPointLight(this.name); + this.range = this._range; + break; + case Type.SPOT: + this._light = scene.createSpotLight(this.name); + this.range = this._range; + this.spotAngle = this._spotAngle; + break; + } + if (!this._light) { console.warn('we don\'t support this many lights in forward pipeline.'); } + this.color = this._color; + } + + protected _destroyLight () { + if (!this.node._scene || !this._light) { return; } + const scene = this._getRenderScene(); + switch (this._type) { + case Type.DIRECTIONAL: + scene.destroyDirectionalLight(this._light); + break; + case Type.POINT: + scene.destroyPointLight(this._light); + break; + case Type.SPOT: + scene.destroySpotLight(this._light); + break; + } + this._light = null; + } +} diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index a16437731f..3436895072 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -197,15 +197,15 @@ export class ModelComponent extends RenderableComponent { this._model = null; } - if (this._model) { - this._model.enabled = this.enabledInHierarchy; - } - this._model = this._createModel(); this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._updateModelParams(); + + if (this._model) { + this._model.enabled = this.enabledInHierarchy; + } } protected _createModel () { diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 52bcc31cd6..fc3c6c12d7 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -25,14 +25,23 @@ 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 COUNT: number = UBOGlobal.CAMERA_POS_OFFSET + 4; + public static DIR_LIGHT_DIR_OFFSET: number = UBOGlobal.CAMERA_POS_OFFSET + 4; + public static DIR_LIGHT_COLOR_OFFSET: number = UBOGlobal.DIR_LIGHT_DIR_OFFSET + 16; + public static POINT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 16; + public static POINT_LIGHT_COLOR_OFFSET: number = UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + 16; + public static SPOT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 16; + public static SPOT_LIGHT_DIR_OFFSET: number = UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + 16; + public static SPOT_LIGHT_COLOR_OFFSET: number = UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 16; + public static COUNT: number = UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 16; public static SIZE: number = UBOGlobal.COUNT * 4; public static BLOCK: GFXUniformBlock = { binding: 30, name: 'CCGlobal', members: [ + // constants { name: 'cc_time', type: GFXType.FLOAT4, count: 1 }, { name: 'cc_screenSize', type: GFXType.FLOAT4, count: 1 }, { name: 'cc_screenScale', type: GFXType.FLOAT4, count: 1 }, + // transform { name: 'cc_matView', type: GFXType.MAT4, count: 1 }, { name: 'cc_matViewInv', type: GFXType.MAT4, count: 1 }, { name: 'cc_matProj', type: GFXType.MAT4, count: 1 }, @@ -40,6 +49,14 @@ 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: 4 }, + { name: 'cc_dirLightColor', type: GFXType.FLOAT4, count: 4 }, + { name: 'cc_pointLightPositionAndRange', type: GFXType.FLOAT4, count: 4 }, + { name: 'cc_pointLightColor', type: GFXType.FLOAT4, count: 4 }, + { name: 'cc_spotLightPositionAndRange', type: GFXType.FLOAT4, count: 4 }, + { name: 'cc_spotLightDirection', type: GFXType.FLOAT4, count: 4 }, + { name: 'cc_spotLightColor', type: GFXType.FLOAT4, count: 4 }, ], }; @@ -335,6 +352,24 @@ 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 < dLights.length; i++) { + this._uboGlobal.view.set(dLights[i].directionArray, UBOGlobal.DIR_LIGHT_DIR_OFFSET + 4 * i); + this._uboGlobal.view.set(dLights[i].colorData, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 4 * i); + } + const pLights = scene.pointLights; + for (let i = 0; i < pLights.length; i++) { + this._uboGlobal.view.set(pLights[i].positionAndRange, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + 4 * i); + this._uboGlobal.view.set(pLights[i].colorData, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 4 * i); + } + const sLights = scene.spotLights; + for (let i = 0; i < sLights.length; i++) { + this._uboGlobal.view.set(sLights[i].positionAndRange, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + 4 * i); + this._uboGlobal.view.set(sLights[i].directionArray, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 4 * i); + this._uboGlobal.view.set(sLights[i].colorData, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 4 * i); + } + // update ubos this._globalUBO!.update(this._uboGlobal.view); } diff --git a/cocos/renderer/core/effect.ts b/cocos/renderer/core/effect.ts index 461477c87a..125ae93f1d 100644 --- a/cocos/renderer/core/effect.ts +++ b/cocos/renderer/core/effect.ts @@ -24,13 +24,17 @@ export class Effect { const passes: Pass[] = new Array(passNum); for (let k = 0; k < passNum; ++k) { const passInfo = tech.passes[k] as IPassInfoFull; + const shader = programLib.getGFXShader(cc.game._gfxDevice, + passInfo.program, defines && defines[k] || {}); + const renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); const prog = programLib.getTemplate(passInfo.program); - passInfo.shader = programLib.getGFXShader(cc.game._gfxDevice, - passInfo.program, defines && defines[k] || {})!; - passInfo.renderPass = cc.director.root.pipeline.getRenderPass(passInfo.stage || RenderPassStage.DEFAULT); + passInfo.blocks = prog.blocks; + passInfo.samplers = prog.samplers; passInfo.globals = cc.director.root.pipeline.globalUBO; - passInfo.blocks = prog!.blocks; - passInfo.samplers = prog!.samplers; + if (shader) { passInfo.shader = shader; } + else { console.warn(`create shader ${passInfo.program} failed`); } + if (renderPass) { passInfo.renderPass = renderPass; } + else { console.warn(`illegal pass stage in ${effect.name}`); } const pass = new Pass(cc.game._gfxDevice); pass.initialize(passInfo); passes[k] = pass; diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 8b2f5d27fb..3b5e0c3bec 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -199,7 +199,9 @@ export class Pass { } public getHandle (name: string) { - return this._handleMap[name]; + const handle = this._handleMap[name]; + if (!handle) { console.warn(`illegal property name ${name}`); } + return handle; } public getBinding (name: string) { diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/renderer/scene/directional-light.ts new file mode 100644 index 0000000000..cde70935a4 --- /dev/null +++ b/cocos/renderer/scene/directional-light.ts @@ -0,0 +1,20 @@ +import { Vec3 } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { Light, LightType } from './light'; +import { RenderScene } from './render-scene'; + +export class DirectionalLight extends Light { + protected _direction = new Float32Array(4); + + set direction (val: Vec3) { + vec3.array(this._direction, val); + } + get directionArray () { + return this._direction; + } + + constructor (scene: RenderScene, name: string) { + super(scene, name); + this._type = LightType.DIRECTIONAL; + } +} diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts index 6ff69abc81..45379330e2 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/renderer/scene/light.ts @@ -1,27 +1,44 @@ import { RenderScene } from './render-scene'; export enum LightType { + UNKNOWN, DIRECTIONAL, POINT, + SPOT, } export class Light { + protected _color = new Float32Array(4); + protected _enabled = false; - public get type (): LightType { - return this._type; + set enabled (val) { + this._enabled = val; + } + get enabled () { + return this._enabled; } - public get name (): string { + set color (val: number[]) { + this._color.set(val); + } + get colorData () { + return this._color; + } + + get type (): LightType { + return this._type; + } + get name (): string { return this._name; } - private _scene: RenderScene; - private _type: LightType; - private _name: string; + protected _scene: RenderScene; + protected _type: LightType; + protected _name: string; - constructor (scene: RenderScene, type: LightType, name: string) { + constructor (scene: RenderScene, name: string) { this._scene = scene; - this._type = type; this._name = name; + this._type = LightType.UNKNOWN; } } diff --git a/cocos/renderer/scene/point-light.ts b/cocos/renderer/scene/point-light.ts new file mode 100644 index 0000000000..68af391dc0 --- /dev/null +++ b/cocos/renderer/scene/point-light.ts @@ -0,0 +1,24 @@ +import { Vec3 } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { Light, LightType } from './light'; +import { RenderScene } from './render-scene'; + +export class PointLight extends Light { + protected _positionAndRange = new Float32Array(4); + + set position (val: Vec3) { + vec3.array(this._positionAndRange, val); + } + set range (val: number) { + this._positionAndRange[3] = val; + } + + get positionAndRange () { + return this._positionAndRange; + } + + constructor (scene: RenderScene, name: string) { + super(scene, name); + this._type = LightType.POINT; + } +} diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 73e16820a5..9be39b8f7c 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -8,8 +8,11 @@ import { GFXPrimitiveMode } from '../../gfx/define'; import { Node } from '../../scene-graph'; import { Layers } from '../../scene-graph/layers'; import { Camera, ICameraInfo } from './camera'; -import { Light, LightType } from './light'; +import { DirectionalLight } from './directional-light'; +import { Light } from './light'; import { Model } from './model'; +import { PointLight } from './point-light'; +import { SpotLight } from './spot-light'; export interface IRenderSceneInfo { name: string; @@ -28,23 +31,31 @@ export interface IRaycastResult { export class RenderScene { - public get root (): Root { + get root (): Root { return this._root; } - public get name (): string { + get name (): string { return this._name; } - public get cameras (): Camera[] { + get cameras (): Camera[] { return this._cameras; } - public get pointLights (): Light[] { + get directionalLights (): DirectionalLight[] { + return this._directionalLights; + } + + get pointLights (): PointLight[] { return this._pointLights; } - public get models (): Model[] { + get spotLights (): SpotLight[] { + return this._spotLights; + } + + get models (): Model[] { return this._models; } @@ -55,7 +66,9 @@ export class RenderScene { private _root: Root; private _name: string = ''; private _cameras: Camera[] = []; - private _pointLights: Light[] = []; + private _pointLights: PointLight[] = []; + private _directionalLights: DirectionalLight[] = []; + private _spotLights: SpotLight[] = []; private _models: Model[] = []; private _modelId: number = 0; @@ -104,8 +117,9 @@ export class RenderScene { return null; } - public createPointLight (name: string): Light { - const light = new Light(this, LightType.POINT, name); + public createPointLight (name: string): Light | null { + if (this._pointLights.length >= 4) { return null; } + const light = new PointLight(this, name); this._pointLights.push(light); return light; } @@ -119,10 +133,50 @@ export class RenderScene { } } + public createDirectionalLight (name: string): Light | null { + if (this._directionalLights.length >= 4) { return null; } + const light = new DirectionalLight(this, name); + this._directionalLights.push(light); + return light; + } + + public destroyDirectionalLight (light: Light) { + for (let i = 0; i < this._directionalLights.length; ++i) { + if (this._directionalLights[i] === light) { + this._directionalLights.slice(i); + return; + } + } + } + + public createSpotLight (name: string): Light | null { + if (this._spotLights.length >= 4) { return null; } + const light = new SpotLight(this, name); + this._spotLights.push(light); + return light; + } + + public destroySpotLight (light: Light) { + for (let i = 0; i < this._spotLights.length; ++i) { + if (this._spotLights[i] === light) { + this._spotLights.slice(i); + return; + } + } + } + public destroyPointLights () { this._pointLights = []; } + public destroyDirectionalLights () { + this._directionalLights = []; + } + + public destroySpotLights () { + this._spotLights = []; + } + public createModel (clazz: new (scene: RenderScene, node: Node) => T, node: Node): T { const model = new clazz(this, node); this._models.push(model); diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts new file mode 100644 index 0000000000..30ce89a366 --- /dev/null +++ b/cocos/renderer/scene/spot-light.ts @@ -0,0 +1,34 @@ +import { Vec3 } from '../../core/value-types'; +import { vec3 } from '../../core/vmath'; +import { Light, LightType } from './light'; +import { RenderScene } from './render-scene'; + +export class SpotLight extends Light { + protected _direction = new Float32Array(4); + protected _positionAndRange = new Float32Array(4); + + set position (val: Vec3) { + vec3.array(this._positionAndRange, val); + } + set range (val: number) { + this._positionAndRange[3] = val; + } + set direction (val: Vec3) { + vec3.array(this._direction, val); + } + set spotAngle (val: number) { + this._direction[3] = val; + } + + get positionAndRange () { + return this._positionAndRange; + } + get directionArray () { + return this._direction; + } + + constructor (scene: RenderScene, name: string) { + super(scene, name); + this._type = LightType.DIRECTIONAL; + } +} diff --git a/playground/simple.html b/playground/simple.html index 7b6edcfc33..aef133da14 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -58,12 +58,17 @@ cameraNode.addComponent(FirstPersonCamera); const camComp = cameraNode.addComponent(cc.CameraComponent); + const lightNode = new cc.Node('Light'); + lightNode.parent = scene; + lightNode.setRotationFromEuler(70, 0, 0); + const lightComp = lightNode.addComponent(cc.LightComponent); + const texture = createTexture(cc.game.canvas.getElementsByTagName('img')); const material = new cc.Material(); material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js - material.effectName = 'builtin-effect-unlit'; + material.effectName = 'builtin-effect-phong'; const len = 50; const models = [], passes = []; @@ -79,7 +84,7 @@ // material instance initialized here passes.push(modelCom.material.passes[0]); } - const handle = passes[0].getHandle('color'); + const handle = passes[0].getHandle('diffuseColor'); { const material = new cc.Material(); diff --git a/tslint.json b/tslint.json index fcac35efac..8f4d116805 100644 --- a/tslint.json +++ b/tslint.json @@ -17,7 +17,8 @@ "ban-types": false, "no-bitwise": false, "no-empty": false, - "radix": false + "radix": false, + "one-line": false, }, "rulesDirectory": [] } From 7b524c90d2da9fa1a3e058964fc29914fe246d69 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Thu, 24 Jan 2019 14:23:19 +0800 Subject: [PATCH 244/267] fix particle bug --- cocos/3d/builtin/effects.js | 30 ------------------- .../particle/emitter/shape-module.js | 10 +++++-- .../particle/particle-system-component.js | 5 ++++ .../renderer/particle-system-renderer.ts | 1 + 4 files changed, 13 insertions(+), 33 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 5a34563427..91ae02b51f 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -93,35 +93,5 @@ export default [ "dependencies": {} } ] - }, - { - "name": "builtin-effect-unlit", - "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}], - "shaders": [ - { - "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", - "vert": "\nattribute vec3 a_position;\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":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, - {"name":"USE_COLOR", "type":"boolean", "defines":[]} - ], - "blocks": [ - {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ - {"name":"mainTiling", "type":14, "count":1, "size":8}, - {"name":"mainOffset", "type":14, "count":1, "size":8} - ]}, - {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [ - {"name":"color", "type":16, "count":1, "size":16} - ]} - ], - "samplers": [ - {"name":"mainTexture", "type":29, "count":1, "defines":["USE_TEXTURE"], "binding":2} - ], - "dependencies": {} - } - ] } ]; diff --git a/cocos/3d/framework/particle/emitter/shape-module.js b/cocos/3d/framework/particle/emitter/shape-module.js index 2b7877a368..a5bdd4af3f 100644 --- a/cocos/3d/framework/particle/emitter/shape-module.js +++ b/cocos/3d/framework/particle/emitter/shape-module.js @@ -36,11 +36,15 @@ export default class ShapeModule { @property enable = false; - @property + @property({ + type: ShapeType + }) shapeType = ShapeType.Box; - @property - emitFrom = EmitLocation.Base; + @property({ + type: EmitLocation + }) + emitFrom = EmitLocation.Volume; @property _position = new Vec3(0, 0, 0); diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.js index 4e9168dc92..936c8494b5 100644 --- a/cocos/3d/framework/particle/particle-system-component.js +++ b/cocos/3d/framework/particle/particle-system-component.js @@ -179,6 +179,11 @@ export default class ParticleSystemComponent extends Component { constructor() { super(); + this.rateOverTime.constant = 10; + this.startLifetime.constant = 5; + this.startSize.constant = 1; + this.startSpeed.constant = 1; + // internal status this._isPlaying = false; this._isPaused = false; diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index c1354d4aac..030ff60024 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -145,6 +145,7 @@ export default class ParticleSystemRenderer extends RenderableComponent { this._model.setCapacity(this.particleSystem.capacity); this._model.setVertexAttributes(this._vertAttrs); this._model.node = this.node; + this._model.enabled = this.enabledInHierarchy; } } From 317eda43935af8c1bfda0363e27a92a11686c7eb Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 24 Jan 2019 14:47:13 +0800 Subject: [PATCH 245/267] bugfix --- cocos/3d/assets/material.ts | 2 +- cocos/3d/framework/model-component.ts | 2 +- cocos/3d/framework/renderable-component.ts | 9 +++------ cocos/renderer/scene/model.ts | 6 ++++-- 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index 7c9ceece5f..e84b52fcee 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -40,7 +40,7 @@ export interface IMaterialInfo { @ccclass('cc.Material') export class Material extends Asset { - public static getInstantiatedMaterial (mat: Material, rndCom: any, inEditor: boolean) { + public static getInstantiatedMaterial (mat: Material, rndCom: RenderableComponent, inEditor: boolean) { if (mat._owner === rndCom) { return mat; } else { diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index 3436895072..201b134e1a 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -283,6 +283,6 @@ export class ModelComponent extends RenderableComponent { private _getBuiltinMaterial () { // classic ugly pink indicating missing material - return builtinResMgr['default-material']; + return builtinResMgr.get('default-material'); } } diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 23e1c98c85..2389fe921a 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -60,15 +60,12 @@ export class RenderableComponent extends Component { * @param {Number} idx - Look for the material list number */ public getMaterial (idx: number, inEditor: boolean = false): Material | null { - if (idx < 0 || idx >= this._materials.length || this._materials[idx] == null) { - return null; - } - - const instantiated = Material.getInstantiatedMaterial(this._materials[idx]!, this, inEditor); + const mat = this._materials[idx]; + if (!mat) { return null; } + const instantiated = Material.getInstantiatedMaterial(mat, this, inEditor); if (instantiated !== this._materials[idx]) { this.setMaterial(instantiated, idx, !inEditor); } - return this._materials[idx]; } diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index af070d7b04..6dec210677 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -200,8 +200,10 @@ export class Model { return; } if (this._subModels[idx].material === mat) { - this.destroyPipelineState(mat!, this._matPSORecord.get(mat!)!); - this._matPSORecord.set(mat!, this.createPipelineState(mat!)); + if (mat) { + this.destroyPipelineState(mat!, this._matPSORecord.get(mat!)!); + this._matPSORecord.set(mat!, this.createPipelineState(mat!)); + } } else { if (this._subModels[idx].material) { this.releasePSO(this._subModels[idx].material!); From 366a55f4a2ff95ff21d81b52bdc962accf028207 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 15:04:06 +0800 Subject: [PATCH 246/267] fix command buffer bug --- cocos/3d/builtin/effects.js | 14 +++++++++----- cocos/3d/builtin/init.ts | 2 +- cocos/3d/ui/components/label-component.ts | 2 +- cocos/3d/ui/components/sprite-component.ts | 4 ++-- cocos/core/root.ts | 1 + cocos/gfx/webgl/webgl-command-buffer.ts | 11 +++++++++++ cocos/gfx/webgl/webgl-commands.ts | 2 +- cocos/renderer/ui/ui.ts | 13 ++++++++----- 8 files changed, 34 insertions(+), 15 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 5a34563427..1e1da78f28 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -79,16 +79,20 @@ export default [ }, { "name": "builtin-effect-sprite", - "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":"default"}}}]}], + "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":{"u_texSampler":{"type":29, "value":"default"}}}]}], "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matViewProj;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 vert () {\n vec4 pos = cc_matViewProj * vec4(a_position, 1);\n v_uv0 = a_texCoord;\n v_color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n return texture2D(u_texSampler, v_uv0) * v_color;\n}\nvoid main() { gl_FragColor = frag(); }\n", "defines": [], - "blocks": [], + "blocks": [ + {"name": "UI", "size": 64, "defines": [], "binding": 0, "members": [ + {"name":"cc_matViewProj", "type":26, "count":1, "size":64} + ]} + ], "samplers": [ - {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":0} + {"name":"u_texSampler", "type":29, "count":1, "defines":[], "binding":1} ], "dependencies": {} } diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts index b2f4938d81..4ff4440c16 100644 --- a/cocos/3d/builtin/init.ts +++ b/cocos/3d/builtin/init.ts @@ -125,7 +125,7 @@ class BuiltinResMgr { const spriteMtl = new cc.Material(); spriteMtl._uuid = 'sprite-material'; spriteMtl.effectName = 'builtin-effect-sprite'; - spriteMtl.setProperty('mainTexture', defaultTexture); + spriteMtl.setProperty('u_texSampler', defaultTexture); resources[spriteMtl._uuid] = spriteMtl; } diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index d5f44ba06f..2d1dbe2943 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -614,7 +614,7 @@ export class LabelComponent extends UIRenderComponent { } else { this._srcBlendFactor = cc.macro.BlendFactor.SRC_ALPHA; } - material!.setProperty('mainTexture', this._texture); + material!.setProperty('u_texSampler', this._texture); // For batch rendering, do not use uniform color. // material!.useColor = false; // this._updateMaterial(material); diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 6e999caec0..88ad58b727 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -458,9 +458,9 @@ export class SpriteComponent extends UIRenderComponent { // TODO: // else { // if (spriteFrame && spriteFrame.textureLoaded()) { - // const matTexture = material && material.getProperty('mainTexture'); + // const matTexture = material && material.getProperty('u_texSampler'); // if (matTexture !== spriteFrame) { - // material.setProperty('mainTexture', spriteFrame); + // material.setProperty('u_texSampler', spriteFrame); // this.markForUpdateRenderData(true); // } // } diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 19183c8b92..84147d7e31 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -156,6 +156,7 @@ export class Root { } this._ui!.update(deltaTime); + this._ui!.render(); this._device.present(); } diff --git a/cocos/gfx/webgl/webgl-command-buffer.ts b/cocos/gfx/webgl/webgl-command-buffer.ts index 3f6d77f9e4..4843dd2bca 100644 --- a/cocos/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/gfx/webgl/webgl-command-buffer.ts @@ -105,6 +105,17 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer { public begin () { this._webGLAllocator!.clearCmds(this.cmdPackage); + this._curGPUPipelineState = null; + this._curGPUBindingLayout = null; + this._curGPUInputAssembler = null; + this._curViewport = null; + this._curScissor = null; + this._curLineWidth = null; + this._curDepthBias = null; + this._curBlendConstants = []; + this._curDepthBounds = null; + this._curStencilWriteMask = null; + this._curStencilCompareMask = null; } public end () { diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 2da1214f35..0c42b0d202 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1258,7 +1258,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web const invalidateAttachments: GLenum[] = [0, 0, 0, 0]; let numInvalidAttach = 0; - if (curGPURenderPass.colorAttachments.length > 0) { + if (curGPURenderPass.colorAttachments.length > 0 && cmd0.clearColors.length) { const colorAttachment = curGPURenderPass.colorAttachments[0]; if (colorAttachment.format !== GFXFormat.UNKNOWN) { diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index faa3f92d41..1927ce3b97 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -228,6 +228,7 @@ export class UI { public update (dt: number) { this._batches.clear(); + this._commitUIRenderDatas = []; this._renderScreens(); @@ -276,9 +277,6 @@ export class UI { this._renderArea.width = camera.width; this._renderArea.height = camera.height; - cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); - curCamera = camera; - camera.update(); // update ubo @@ -286,10 +284,14 @@ export class UI { this._uboUI.view.set(_mat4Array, UBOUI.MAT_VIEW_PROJ_OFFSET); this._uiUBO!.update(this._uboUI.view); + + curCamera = camera; + + cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); } material.bindingLayout.bindBuffer(0, this._uiUBO!); - material.bindingLayout.bindTextureView(5, batch.texView); + material.bindingLayout.bindTextureView(1, batch.texView); material.bindingLayout.update(); cmdBuff.bindPipelineState(material.pipelineState); @@ -440,6 +442,7 @@ export class UI { const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; const vbCount = 128; + const varrCount = 128 * 9; const vb = this._device.createBuffer({ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST, @@ -468,7 +471,7 @@ export class UI { batch.vb = vb; batch.ib = ib; batch.ia = ia; - batch.vf32 = new Float32Array(vbCount); + batch.vf32 = new Float32Array(varrCount); batch.vui16 = new Uint16Array(ibCount); batch.vbSize = vb.size; batch.ibSize = ib.size; From 626ebe2b9db1f5290f33d003cb85745d8e804309 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 24 Jan 2019 15:36:00 +0800 Subject: [PATCH 247/267] add animation support/add webgl debug support --- cocos/3d/assets/animation-clip.js | 398 -------------- cocos/3d/assets/animation-clip.ts | 319 +++++++++++ cocos/3d/framework/animation-component.js | 495 ------------------ cocos/3d/framework/animation-component.ts | 426 +++++++++++++++ cocos/3d/framework/animation-system.js | 63 --- cocos/3d/framework/renderable-component.ts | 4 + cocos/3d/framework/skeleton-instance.js | 176 ------- .../3d/framework/skinning-model-component.ts | 151 ++---- cocos/3d/framework/skinning-model-system.js | 76 --- cocos/core/director.js | 1 - cocos/core/game.js | 1 + cocos/gfx/device.ts | 1 + cocos/gfx/webgl/webgl-device.ts | 8 + cocos/renderer/models/skinning-model.ts | 99 +++- globals.d.ts | 11 +- package.json | 1 + 16 files changed, 904 insertions(+), 1326 deletions(-) delete mode 100644 cocos/3d/assets/animation-clip.js create mode 100644 cocos/3d/assets/animation-clip.ts delete mode 100644 cocos/3d/framework/animation-component.js create mode 100644 cocos/3d/framework/animation-component.ts delete mode 100644 cocos/3d/framework/animation-system.js delete mode 100644 cocos/3d/framework/skeleton-instance.js delete mode 100644 cocos/3d/framework/skinning-model-system.js diff --git a/cocos/3d/assets/animation-clip.js b/cocos/3d/assets/animation-clip.js deleted file mode 100644 index 432d15bbe2..0000000000 --- a/cocos/3d/assets/animation-clip.js +++ /dev/null @@ -1,398 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -// @ts-check -import { _decorator } from "../../core/data/index"; -const { ccclass, property } = _decorator; -import { Asset } from "../../assets/asset"; -import vec3 from "../../core/vmath/vec3"; -import quat from "../../core/vmath/quat"; -import { clamp } from "../../core/vmath/utils"; - -/** - * @typedef {import("../framework/skeleton-instance").SkeletonMask} SkeletonMask - * @typedef {import("../../scene-graph/node").default} Node - */ - -let tmpvec3 = vec3.create(0, 0, 0); -let tmpquat = quat.create(); - -function _binaryIndexOf(array, key) { - let lo = 0; - let hi = array.length - 1; - let mid; - - while (lo <= hi) { - mid = ((lo + hi) >> 1); - let val = array[mid]; - - if (val < key) { - lo = mid + 1; - } else if (val > key) { - hi = mid - 1; - } else { - return mid; - } - } - - return lo; -} - -@ccclass('cc.AnimationChannel') -export class AnimationChannel { - /** - * Target node's path into virtual hierarchy. - * @type {string} - */ - @property - target = ""; - - /** - * Target node's position animation curve. - * @type {cc.Vec3[]} - */ - @property - positionCurve = []; - - /** - * Target node's scale animation curve. - * @type {cc.Vec3[]} - */ - @property - scaleCurve = []; - - /** - * Target node's rotation animation curve. - * @type {cc.Quat[]} - */ - @property - rotationCurve = []; -} -cc.AnimationChannel = AnimationChannel; - -@ccclass('cc.AnimationFrame') -export class AnimationFrame { - @property - _name = ""; - - /** - * @type {AnimationChannel[]} - */ - @property - _channels = []; - - /** - * @type {number[]} - */ - @property - _times = []; - - get channels() { - return this._channels; - } - - get times() { - return this._times; - } -} -cc.AnimationFrame = AnimationFrame; - -@ccclass('cc.AnimationClip') -export default class AnimationClip extends Asset { - /** - * @type {AnimationFrame[]} - */ - @property - _frames = []; - - /** - * @type {number} - */ - @property - _length = 0.0; - - get frames() { - return this._frames; - } - - get length() { - return this._length; - } -} -cc.AnimationClip = AnimationClip; - -export class AnimationTarget { - constructor() { - /** - * @type {Node[]} - */ - this._nodes = []; - - /** - * @type {Map} - */ - this._pathMap = new Map(); - } - - add(path, node) { - if (this._pathMap.has(path)) { - return; - } - const index = this._nodes.length; - this._nodes.push(node); - this._pathMap.set(path, index); - } - - get(path) { - return this._pathMap.get(path); - } - - get nodes() { - return this._nodes; - } - - getDefaultPosition(nodeIndex) { - return this._nodes[nodeIndex].getPosition(); - //return this._defaultPositions[nodeIndex]; - } - - getDefaultScale(nodeIndex) { - return this._nodes[nodeIndex].getScale(); - //return this._defaultScales[nodeIndex]; - } - - getDefaultRotation(nodeIndex) { - return this._nodes[nodeIndex].getRotation(); - //return this._defaultRotations[nodeIndex]; - } - - // _saveDefaultTRS() { - // this._defaultPositions = new Array(this._nodes.length); - // this._defaultScales = new Array(this._nodes.length); - // this._defaultRotations = new Array(this._nodes.length); - // this._nodes.forEach((node, index) => { - // this._defaultPositions[index] = node.getPosition(); - // this._defaultScales[index] = node.getScale(); - // this._defaultRotations[index] = node.getRotation(); - // }); - // } -} - -/** - * The AnimationTarget class represents the progress of blended sampling. - */ -export class AnimationSampler { - /** - * - * @param {AnimationTarget} animationTarget - */ - constructor(animationTarget) { - /** - * @type {AnimationTarget} - */ - this._animationTarget = animationTarget; - - const targetNodes = this._animationTarget.nodes; - /** - * @type {NodeSamplingState[]} - */ - this._nodeSamplingStates = new Array(targetNodes.length); - this._animationTarget.nodes.forEach((targetNode, index) => { - this._nodeSamplingStates[index] = new NodeSamplingState( - targetNode, - this._animationTarget.getDefaultPosition(index), - this._animationTarget.getDefaultScale(index), - this._animationTarget.getDefaultRotation(index)); - }); - } - - /** - * Resets this state to get sampling start. - */ - reset() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.reset()); - } - - /** - * Updates the sampling result. - */ - apply() { - this._nodeSamplingStates.forEach( - nodeSamlingState => nodeSamlingState.apply()); - } - - /** Sample data of this animation clip in a specific time and blend that data - * with a weight together with previous data(if exist, or blank if not exists) sampled before. - * - * @param {AnimationClip} clip - * @param {Number} t The time. - * @param {Number} weight The weight. - * @param {SkeletonMask} [mask] The skeleton mask. - */ - sample(clip, t, weight, mask) { - t = clamp(t, 0, clip.length); - - const getState = /** @param {AnimationChannel} [channel] */(channel) => { - return this._nodeSamplingStates[this._animationTarget.get(channel.target)]; - }; - - clip.frames.forEach((frame) => { - let idx = 0; - if (frame.times.length != 1) - idx = _binaryIndexOf(frame.times, t); - if (idx == 0) { - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - nodeSamlingState.blendPosition(channel.positionCurve[0], weight); - } - if (channel.rotationCurve.length != 0) { - nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); - } - if (channel.scaleCurve.length != 0) { - nodeSamlingState.blendScale(channel.scaleCurve[0], weight); - } - }); - } - else { - let loIdx = Math.max(idx - 1, 0); - let hiIdx = Math.min(idx, frame.times.length); - let ratio = (t - frame.times[loIdx]) / (frame.times[hiIdx] - frame.times[loIdx]); - - frame.channels.forEach((channel) => { - const nodeSamlingState = getState(channel); - if (!nodeSamlingState) { - return; - } - if (channel.positionCurve.length != 0) { - let a = channel.positionCurve[loIdx]; - let b = channel.positionCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendPosition(tmpvec3, weight); - } - if (channel.rotationCurve.length != 0) { - let a = channel.rotationCurve[loIdx]; - let b = channel.rotationCurve[hiIdx]; - quat.slerp(tmpquat, a, b, ratio); - nodeSamlingState.blendRotation(tmpquat, weight); - } - if (channel.scaleCurve.length != 0) { - let a = channel.scaleCurve[loIdx]; - let b = channel.scaleCurve[hiIdx]; - vec3.lerp(tmpvec3, a, b, ratio); - nodeSamlingState.blendScale(tmpvec3, weight); - } - }); - } - }); - } -} - -class NodeSamplingState { - /** - * - * @param {Node} target - * @param {cc.Vec3} defaultPosition - * @param {cc.Vec3} defaultScale - * @param {cc.Quat} defaultRotation - */ - constructor(target, defaultPosition, defaultScale, defaultRotation) { - /** - * @type {Node} - */ - this._target = target; - - /** - * @type {cc.Vec3} - */ - this._defaultPosition = defaultPosition; - - /** - * @type {cc.Vec3} - */ - this._defaultScale = defaultScale; - - /** - * @type {cc.Quat} - */ - this._defaultRotation = defaultRotation; - } - - reset() { - /** - * @type {Number} - */ - this._sumPosWeight = 0.0; - - /** - * @type {Number} - */ - this._sumScaleWeight = 0.0; - - /** - * @type {Number} - */ - this._sumRotWeight = 0.0; - this._target.setPosition(0, 0, 0); - this._target.setScale(0, 0, 0); - this._target.setRotation(0, 0, 0, 1); - } - - blendPosition(pos, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lpos, pos, weight); - this._target.setPosition(tmpvec3); - this._sumPosWeight += weight; - } - - blendScale(scale, weight) { - vec3.scaleAndAdd(tmpvec3, this._target._lscale, scale, weight); - this._target.setScale(tmpvec3); - this._sumScaleWeight += weight; - } - - /** - * Inspired by: - * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions - */ - blendRotation(rot, weight) { - let t = weight / (this._sumRotWeight + weight); - quat.slerp(tmpquat, this._target._lrot, rot, t); - this._target.setRotation(tmpquat); - this._sumRotWeight += weight; - } - - apply() { - if (this._sumPosWeight < 1.0) - this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); - if (this._sumScaleWeight < 1.0) - this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); - if (this._sumRotWeight < 1.0) - this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); - } -} diff --git a/cocos/3d/assets/animation-clip.ts b/cocos/3d/assets/animation-clip.ts new file mode 100644 index 0000000000..321ff63aaf --- /dev/null +++ b/cocos/3d/assets/animation-clip.ts @@ -0,0 +1,319 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +// @ts-check +import { _decorator } from '../../core/data/index'; +const { ccclass, property } = _decorator; +import { Asset } from '../../assets/asset'; +import { Quat, Vec3 } from '../../core/value-types'; +import quat from '../../core/vmath/quat'; +import { clamp } from '../../core/vmath/utils'; +import vec3 from '../../core/vmath/vec3'; +import { Node } from '../../scene-graph/node'; + +const tmpvec3 = new Vec3(); +const tmpquat = new Quat(); + +function _binaryIndexOf (array: number[], key: number) { + let lo = 0; + let hi = array.length - 1; + while (lo <= hi) { + const mid = ((lo + hi) >> 1); + const val = array[mid]; + if (val < key) { + lo = mid + 1; + } else if (val > key) { + hi = mid - 1; + } else { + return mid; + } + } + return lo; +} + +export interface IAnimationChannel { + /** + * Target node's path in scene graph. + */ + target: string; + + /** + * Target node's position animation curve. + */ + positionCurve: Vec3[]; + + /** + * Target node's scale animation curve. + */ + scaleCurve: Vec3[]; + + /** + * Target node's rotation animation curve. + */ + rotationCurve: Quat[]; +} + +@ccclass('cc.AnimationClip') +export default class AnimationClip extends Asset { + @property + private _channels: IAnimationChannel[] = []; + + @property + private _times: number[] = []; + + @property + private _length: number = 0.0; + + get times () { + return this._times; + } + + get channels () { + return this._channels; + } + + get length () { + return this._length; + } +} +cc.AnimationClip = AnimationClip; + +export class AnimationTarget { + private _nodes: Node[] = []; + private _pathMap: Map = new Map(); + + public add (path: string, node: Node) { + if (this._pathMap.has(path)) { + return; + } + const index = this._nodes.length; + this._nodes.push(node); + this._pathMap.set(path, index); + } + + public get (path: string) { + return this._pathMap.get(path); + } + + get nodes () { + return this._nodes; + } + + public getDefaultPosition (nodeIndex: number) { + return this._nodes[nodeIndex].getPosition(); + // return this._defaultPositions[nodeIndex]; + } + + public getDefaultScale (nodeIndex: number) { + return this._nodes[nodeIndex].getScale(); + // return this._defaultScales[nodeIndex]; + } + + public getDefaultRotation (nodeIndex: number) { + return this._nodes[nodeIndex].getRotation(); + // return this._defaultRotations[nodeIndex]; + } + + // _saveDefaultTRS() { + // this._defaultPositions = new Array(this._nodes.length); + // this._defaultScales = new Array(this._nodes.length); + // this._defaultRotations = new Array(this._nodes.length); + // this._nodes.forEach((node, index) => { + // this._defaultPositions[index] = node.getPosition(); + // this._defaultScales[index] = node.getScale(); + // this._defaultRotations[index] = node.getRotation(); + // }); + // } +} + +/** + * The AnimationTarget class represents the progress of blended sampling. + */ +export class AnimationSampler { + private _animationTarget: AnimationTarget; + private _nodeSamplingStates: NodeSamplingState[]; + + constructor (animationTarget: AnimationTarget) { + this._animationTarget = animationTarget; + + const targetNodes = this._animationTarget.nodes; + this._nodeSamplingStates = new Array(targetNodes.length); + this._animationTarget.nodes.forEach((targetNode, index) => { + this._nodeSamplingStates[index] = new NodeSamplingState( + targetNode, + this._animationTarget.getDefaultPosition(index), + this._animationTarget.getDefaultScale(index), + this._animationTarget.getDefaultRotation(index)); + }); + } + + /** + * Resets this state to get sampling start. + */ + public reset () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.reset()); + } + + /** + * Updates the sampling result. + */ + public apply () { + this._nodeSamplingStates.forEach( + (nodeSamlingState) => nodeSamlingState.apply()); + } + + /** Sample data of this animation clip in a specific time and blend that data + * with a weight together with previous data(if exist, or blank if not exists) sampled before. + * + * @param clip + * @param t The time. + * @param weight The weight. + * @param [mask] The skeleton mask. + */ + public sample (clip: AnimationClip, t: number, weight: number, mask?: any) { + t = clamp(t, 0, clip.length); + + const getState = (channel: IAnimationChannel) => { + const iNode = this._animationTarget.get(channel.target); + if (!iNode) { + return null; + } + return this._nodeSamplingStates[iNode]; + }; + + let idx = 0; + if (clip.times.length !== 1) { + idx = _binaryIndexOf(clip.times, t); + } + if (idx === 0) { + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + nodeSamlingState.blendPosition(channel.positionCurve[0], weight); + } + if (channel.rotationCurve.length !== 0) { + nodeSamlingState.blendRotation(channel.rotationCurve[0], weight); + } + if (channel.scaleCurve.length !== 0) { + nodeSamlingState.blendScale(channel.scaleCurve[0], weight); + } + }); + } else { + const loIdx = Math.max(idx - 1, 0); + const hiIdx = Math.min(idx, clip.times.length); + const ratio = (t - clip.times[loIdx]) / (clip.times[hiIdx] - clip.times[loIdx]); + + clip.channels.forEach((channel) => { + const nodeSamlingState = getState(channel); + if (!nodeSamlingState) { + return; + } + if (channel.positionCurve.length !== 0) { + const a = channel.positionCurve[loIdx]; + const b = channel.positionCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendPosition(tmpvec3, weight); + } + if (channel.rotationCurve.length !== 0) { + const a = channel.rotationCurve[loIdx]; + const b = channel.rotationCurve[hiIdx]; + quat.slerp(tmpquat, a, b, ratio); + nodeSamlingState.blendRotation(tmpquat, weight); + } + if (channel.scaleCurve.length !== 0) { + const a = channel.scaleCurve[loIdx]; + const b = channel.scaleCurve[hiIdx]; + vec3.lerp(tmpvec3, a, b, ratio); + nodeSamlingState.blendScale(tmpvec3, weight); + } + }); + } + } +} + +class NodeSamplingState { + private _target: Node; + private _defaultPosition: Vec3; + private _defaultScale: Vec3; + private _defaultRotation: Quat; + private _sumPosWeight = 0; + private _sumScaleWeight = 0; + private _sumRotWeight = 0; + + constructor (target: Node, defaultPosition: Vec3, defaultScale: Vec3, defaultRotation: Quat) { + this._target = target; + this._defaultPosition = defaultPosition; + this._defaultScale = defaultScale; + this._defaultRotation = defaultRotation; + } + + public reset () { + this._sumPosWeight = 0.0; + this._sumScaleWeight = 0.0; + this._sumRotWeight = 0.0; + this._target.setPosition(0, 0, 0); + this._target.setScale(0, 0, 0); + this._target.setRotation(0, 0, 0, 1); + } + + public blendPosition (position: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getPosition(), position, weight); + this._target.setPosition(tmpvec3); + this._sumPosWeight += weight; + } + + public blendScale (scale: Vec3, weight: number) { + vec3.scaleAndAdd(tmpvec3, this._target.getScale(), scale, weight); + this._target.setScale(tmpvec3); + this._sumScaleWeight += weight; + } + + /** + * Inspired by: + * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions + */ + public blendRotation (rotation: Quat, weight: number) { + const t = weight / (this._sumRotWeight + weight); + quat.slerp(tmpquat, this._target.getRotation(), rotation, t); + this._target.setRotation(tmpquat); + this._sumRotWeight += weight; + } + + public apply () { + if (this._sumPosWeight < 1.0) { + this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight); + } + if (this._sumScaleWeight < 1.0) { + this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight); + } + if (this._sumRotWeight < 1.0) { + this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight); + } + } +} diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js deleted file mode 100644 index 0e9d1c8e4b..0000000000 --- a/cocos/3d/framework/animation-component.js +++ /dev/null @@ -1,495 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { Component } from '../../components/component'; -import { ccclass, property, executionOrder, menu, executeInEditMode } from '../../core/data/class-decorator'; -import Enum from '../../core/value-types/enum'; -import AnimationClip, { AnimationTarget, AnimationSampler } from '../assets/animation-clip'; - -/** - * !#en Animation State Class - * - * !#ch 动画状态类 - * @class AnimationState - */ -class AnimationState { - constructor(clip) { - /** - * !#en An animation clip that is played through this state - * - * !#ch 通过此状态播放的动画剪辑 - * @property clip - * @type {AnimationClip} - */ - this.clip = clip; - - /** - * !#en Blend mode - * - * !#ch 混合模式 - * @property blendMode - * @type {String} - */ - this.blendMode = AnimationState.BlendMode.Blend; - - /** - * !#en Wrapping mode - * - * !#ch 循环模式 - * @property wrapMode - * @type {String} - */ - this.wrapMode = AnimationState.WrapMode.Loop; - - /** - * !#en The playback speed - * - * !#ch 播放速度 - * @property speed - * @type {Number} - */ - this.speed = 1.0; - - /** - * !#en The current time of the animation. - * - * !#ch 当前动画播放时间 - * @property time - * @type {Number} - */ - this.time = 0.0; - - /** - * !#en The weight of animation. - * - * !#ch 动画权重 - * @property weight - * @type {Number} - */ - this.weight = 1.0; - } - - /** - * !#en The blend mode of animation state - * - * !#ch 动画状态的混合模式 - * @static - * @enum AnimationState.BlendMode - */ - static BlendMode = Enum({ - /** - * !#en Animations will be blended. - * - * !#ch 动画将被混合 - * @property Blend - * @readonly - * @type {String} - */ - Blend: 'blend', - /** - * !#en Animations will be added. - * - * !#ch 动画将被附加 - * @property Additive - * @readonly - * @type {String} - */ - Additive: 'additive' - }); - - /** - * !#en Wrapping mode of the animation. - * - * !#ch 动画状态的循环模式 - * @static - * @enum AnimationState.WrapMode - */ - static WrapMode = Enum({ - /** - * !#en Only once - * - * !#ch 只播放一次 - * @property Once - * @readonly - * @type {String} - */ - Once: 'once', - /** - * !#en Loop - * - * !#ch 循环播放 - * @property Additive - * @readonly - * @type {String} - */ - Loop: 'loop', - /** - * !#en Ping Pong - * - * !#ch 乒乓模式播放 - * @property PinpPong - * @readonly - * @type {String} - */ - PinpPong: 'ping-pong', - /** - * !#en Plays back the animation. The last frame is played until the end. - * - * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 - * @property Clamp - * @readonly - * @type {String} - */ - Clamp: 'clamp' - }); -} - -/** - * !#en Animation Controller - * - * !#ch 动画控制器 - * @class AnimationCtrl - */ -class AnimationCtrl { - constructor() { - /** - * @type {AnimationTarget} - */ - this._animationTarget = null; - - /** - * @type {AnimationSampler} - */ - this._animationSampler = null; - - this._current = null; - - this._next = null; - - this._blendTime = 0.0; - - this._blendDuration = 0.3; - } - - /** - * !#en Set up the animation target - * - * !#ch 设置动画目标 - * @param {AnimationTarget} animationTarget - */ - setAnimationTarget(animationTarget) { - this._animationTarget = animationTarget; - if (this._animationTarget) { - this._animationSampler = new AnimationSampler(this._animationTarget); - } - this._nodeIndexers = new Map(); - } - - /** - * !#en Animation fades in and out - * - * !#ch 动画的淡入淡出功能 - * @param {AnimationState} to - * @param {Number} duration - */ - crossFade(to, duration) { - if (this._current && duration > 0.0) { - this._next = to; - this._blendTime = 0.0; - this._blendDuration = duration; - } else { - this._current = to; - this._next = null; - } - } - - tick(dt) { - if (!this._animationSampler) { - return; - } - - this._animationSampler.reset(); - - // handle blend - if (this._current && this._next) { - let t0 = this._getTime(this._current); - let t1 = this._getTime(this._next); - - let alpha = this._blendTime / this._blendDuration; - - this._current.time += dt; - this._next.time += dt; - this._blendTime += dt; - - if (alpha > 1.0) { - this._current = this._next; - this._next = null; - this._animationSampler.sample(this._current.clip, t1, 1.0); - } else { - this._animationSampler.sample(this._current.clip, t0, alpha); - this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); - } - } - - // handle playing - if (this._current) { - let t0 = this._getTime(this._current); - this._animationSampler.sample(this._current.clip, t0, 1.0); - this._current.time += dt; - } - - this._animationSampler.apply(); - } - - /** - * !#en Get the play time of an animation clip in current animation state - * - * !#ch 返回当前动画状态下的动画剪辑播放时间 - * @param {AnimationState} state - Specify animation status - */ - _getTime(state) { - let t = state.time; - let length = state.clip.length; - t *= state.speed; - - if (state.wrapMode === 'once') { - if (t > length) { - t = 0.0; - } - } else if (state.wrapMode === 'loop') { - t %= length; - } else if (state.wrapMode === 'ping-pong') { - let order = Math.floor(t / length); - if (order % 2 === 1) { - t = length - t % length; - } - } - - return t; - } -} - -/** - * !#en - * Basic animation component for playing animation - * - * !#ch - * 基础动画组件用于动画播放 - * @class AnimationComponent - * @extends Component - */ -@ccclass('cc.AnimationComponent') -@executionOrder(99) -@executeInEditMode -@menu('Components/AnimationComponent') -export default class AnimationComponent extends Component { - /** - * @type {AnimationClip[]} - */ - @property({ type: [AnimationClip] }) - _clips = []; - - /** - * !#en Current clip - * - * !#ch 当前动画剪辑 - * @property currentClip - * @type {AnimationClip} - */ - @property({ type:AnimationClip }) - currentClip = null; - - /** - * !#en Whether to start the animation automatically - * - * !#ch 是否启动时自动播放动画 - * @property playAutomatically - * @type {Boolean} - */ - @property - playAutomatically = false; - - _preview = false; - - @property({ type: Boolean }) - get preview() { - return this._preview; - } - - set preview(value) { - this._preview = value; - if (value) { - if (this.currentClip) { - cc.engine.animatingInEditMode = true; - this.play(this.currentClip.name); - } - } else { - cc.engine.animatingInEditMode = false; - this._animCtrl.crossFade(null, 0); - } - } - - /** - * !#en Animation state - * - * !#ch 动画状态列表 - * @type {Object} - */ - _name2states = {}; - - constructor() { - super(); - - /** - * @type {AnimationTarget} - */ - this._target = null; - - /** - * !#en Animation controller - * - * !#ch 动画控制器 - * @type {AnimationCtrl} - */ - this._animCtrl = new AnimationCtrl(); - } - - /** - * !#en Clip required for animation playback - * - * !#ch 动画剪辑列表 - * @property clips - * @type {AnimationClip[]} - */ - @property({ type: [AnimationClip] }) - get clips() { - return this._clips; - } - - set clips(val) { - this._clips = val; - } - - onLoad() { - this._clips.forEach(clip => { - this._name2states[clip.name] = new AnimationState(clip); - }); - - this._resetTarget(); - - if (this.playAutomatically != undefined && - this.playAutomatically && - this.currentClip != undefined && - this.currentClip) { - this.play(this.currentClip.name); - } - } - - update(dt) { - this._animCtrl.tick(dt); - } - - onDestroy() { - } - - onEnable() { - } - - onDisable() { - this._target = null; - this._animCtrl.setAnimationTarget(null); - } - - /** - * !#en Add an animation clip to the animation status list - * - * !#ch 添加动画剪辑到动画状态列表 - * @param {String} name - The name of animation clip - * @param {AnimationClip} animClip - Animation clip - */ - addClip(name, animClip) { - if (this._name2states[name]) { - console.warn(`Failed to add clip ${name}, the name already exsits.`); - return; - } - - this._clips.push(animClip); - this._name2states[name] = new AnimationState(animClip); - } - - /** - * !#en Get the animation state through the animation clip name - * - * !#ch 返回动画剪辑相对应的动画状态 - * @param {String} name - The name of animation clip - */ - getState(name) { - return this._name2states[name]; - } - - /** - * !#en Play the name of the animation clip - * - * !#ch 播放相对应名字的动画剪辑 - * @param {String} name - The name of animation clip - * @param {Number} fadeDuration - Fade duration - */ - play(name, fadeDuration = 0.3) { - if (!this._target) { - return; - } - - if (!this._name2states[name]) { - console.warn(`Failed to play animation ${name}, not found.`); - return; - } - - let animState = this._name2states[name]; - animState.time = 0.0; - - this._animCtrl.crossFade(animState, fadeDuration); - } - - _resetTarget() { - this._target = new AnimationTarget(); - this._clips.forEach(clip => { - clip.frames.forEach(frame => { - frame.channels.forEach(channel => { - const targetPath = channel.target; - if (this._target.get(targetPath)) { - return; - } - const targetNode = this.node.getChildByPath(targetPath); - if (!targetNode) { - console.warn(`Animation target ${targetPath} not found in scene graph.`); - return; - } - this._target.add(targetPath, targetNode); - }); - }); - }); - this._animCtrl.setAnimationTarget(this._target); - } -} diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts new file mode 100644 index 0000000000..c308fb1f82 --- /dev/null +++ b/cocos/3d/framework/animation-component.ts @@ -0,0 +1,426 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +// @ts-check +import { Component } from '../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; +import { ccenum } from '../../core/value-types/enum'; +import AnimationClip, { AnimationSampler, AnimationTarget } from '../assets/animation-clip'; + +enum BlendMode { + /** + * !#en Animations will be blended. + * + * !#ch 动画将被混合 + */ + Blend = 'blend', + /** + * !#en Animations will be added. + * + * !#ch 动画将被附加 + */ + Additive = 'additive', +} + +ccenum(BlendMode); + +enum WrapMode { + /** + * !#en Only once + * + * !#ch 只播放一次 + */ + Once = 'once', + + /** + * !#en Loop + * + * !#ch 循环播放 + */ + Loop = 'loop', + + /** + * !#en Ping Pong + * + * !#ch 乒乓模式播放 + */ + PinpPong = 'ping-pong', + + /** + * !#en Plays back the animation. The last frame is played until the end. + * + * !#ch 回放动画。当到结尾时,会持续播放最后一帧。 + */ + Clamp = 'clamp', +} + +ccenum(WrapMode); + +/** + * !#en Animation State Class + * + * !#ch 动画状态类 + */ +class AnimationState { + /** + * !#en The blend mode of animation state. + * + * !#ch 动画状态的混合模式 + */ + public static BlendMode = BlendMode; + + /** + * !#en Wrapping mode of the animation. + * + * !#ch 动画状态的循环模式 + */ + public static WrapMode = WrapMode; + + /** + * !#en An animation clip that is played through this state + * + * !#ch 通过此状态播放的动画剪辑 + */ + public clip: AnimationClip; + + /** + * !#en Blend mode + * + * !#ch 混合模式 + */ + public blendMode: BlendMode = BlendMode.Blend; + + /** + * !#en Wrapping mode + * + * !#ch 循环模式 + */ + public wrapMode: WrapMode = WrapMode.Loop; + + /** + * !#en The playback speed + * + * !#ch 播放速度 + */ + public speed = 1.0; + + /** + * !#en The current time of the animation. + * + * !#ch 当前动画播放时间 + */ + public time: number = 0.0; + + /** + * !#en The weight of animation. + * + * !#ch 动画权重 + */ + public weight: number = 1.0; + + constructor (clip: AnimationClip) { + this.clip = clip; + } +} + +/** + * !#en Animation Controller + * + * !#ch 动画控制器 + */ +class AnimationCtrl { + private _animationTarget: AnimationTarget | null = null; + private _animationSampler: AnimationSampler | null = null; + private _current: AnimationState | null = null; + private _next: AnimationState | null = null; + private _blendTime = 0.0; + private _blendDuration = 0.3; + + /** + * !#en Set up the animation target + * + * !#ch 设置动画目标 + */ + public setAnimationTarget (animationTarget: AnimationTarget | null) { + this._animationTarget = animationTarget; + if (this._animationTarget) { + this._animationSampler = new AnimationSampler(this._animationTarget); + } + } + + /** + * !#en Animation fades in and out + * + * !#ch 动画的淡入淡出功能 + * @param to + * @param duration + */ + public crossFade (to: AnimationState | null, duration: number) { + if (this._current && duration > 0.0) { + this._next = to; + this._blendTime = 0.0; + this._blendDuration = duration; + } else { + this._current = to; + this._next = null; + } + } + + public tick (deltaTime: number) { + if (!this._animationSampler) { + return; + } + + this._animationSampler.reset(); + + // handle blend + if (this._current && this._next) { + const t0 = this._getTime(this._current); + const t1 = this._getTime(this._next); + + const alpha = this._blendTime / this._blendDuration; + + this._current.time += deltaTime; + this._next.time += deltaTime; + this._blendTime += deltaTime; + + if (alpha > 1.0) { + this._current = this._next; + this._next = null; + this._animationSampler.sample(this._current.clip, t1, 1.0); + } else { + this._animationSampler.sample(this._current.clip, t0, alpha); + this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha); + } + } + + // handle playing + if (this._current) { + const t0 = this._getTime(this._current); + this._animationSampler.sample(this._current.clip, t0, 1.0); + this._current.time += deltaTime; + } + + this._animationSampler.apply(); + } + + /** + * !#en Get the play time of an animation clip in current animation state + * + * !#ch 返回当前动画状态下的动画剪辑播放时间 + * @param state - Specify animation status + */ + private _getTime (state: AnimationState) { + let t = state.time; + const length = state.clip.length; + t *= state.speed; + + if (state.wrapMode === 'once') { + if (t > length) { + t = 0.0; + } + } else if (state.wrapMode === 'loop') { + t %= length; + } else if (state.wrapMode === 'ping-pong') { + const order = Math.floor(t / length); + if (order % 2 === 1) { + t = length - t % length; + } + } + + return t; + } +} + +/** + * !#en + * Basic animation component for playing animation + * + * !#ch + * 基础动画组件用于动画播放 + */ +@ccclass('cc.AnimationComponent') +@executionOrder(99) +@executeInEditMode +@menu('Components/AnimationComponent') +export default class AnimationComponent extends Component { + @property({ type: [AnimationClip] }) + public _clips: AnimationClip[] = []; + + /** + * !#en Current clip + * + * !#ch 当前动画剪辑 + */ + @property({ type: AnimationClip }) + public currentClip: AnimationClip | null = null; + + /** + * !#en Whether to start the animation automatically + * + * !#ch 是否启动时自动播放动画 + */ + @property + public playAutomatically: boolean = false; + + private _preview = false; + + private _animationController: AnimationCtrl = new AnimationCtrl(); + + private _name2states: { [x: string]: AnimationState | undefined; } = {}; + + private _animationTarget: AnimationTarget | null = null; + + @property({ type: Boolean }) + get preview () { + return this._preview; + } + + set preview (value) { + this._preview = value; + if (value) { + if (this.currentClip) { + cc.engine.animatingInEditMode = true; + this.play(this.currentClip.name); + } + } else { + cc.engine.animatingInEditMode = false; + this._animationController.crossFade(null, 0); + } + } + + constructor () { + super(); + } + + /** + * !#en Clip required for animation playback + * + * !#ch 动画剪辑列表 + */ + @property({ type: [AnimationClip] }) + get clips () { + return this._clips; + } + + set clips (val) { + this._clips = val; + } + + public onLoad () { + this._clips.forEach((clip) => { + this._name2states[clip.name] = new AnimationState(clip); + }); + + this._resetTarget(); + + if (!CC_EDITOR && this.playAutomatically && this.currentClip) { + this.play(this.currentClip.name); + } + } + + public update (deltaTime: number) { + this._animationController.tick(deltaTime); + } + + public onDestroy () { + } + + public onEnable () { + } + + public onDisable () { + this._animationTarget = null; + this._animationController.setAnimationTarget(null); + } + + /** + * !#en Add an animation clip to the animation status list + * + * !#ch 添加动画剪辑到动画状态列表 + * @param name - The name of animation clip + * @param animationClip - Animation clip + */ + public addClip (name: string, animationClip: AnimationClip) { + if (this._name2states[name]) { + console.warn(`Failed to add clip ${name}, the name already exsits.`); + return; + } + + this._clips.push(animationClip); + this._name2states[name] = new AnimationState(animationClip); + } + + /** + * !#en Get the animation state through the animation clip name + * + * !#ch 返回动画剪辑相对应的动画状态 + * @param name - The name of animation clip + */ + public getState (name: string) { + return this._name2states[name]; + } + + /** + * !#en Play the name of the animation clip + * + * !#ch 播放相对应名字的动画剪辑 + * @param name - The name of animation clip + * @param fadeDuration - Fade duration + */ + public play (name: string, fadeDuration = 0.3) { + if (!this._animationTarget) { + return; + } + + const state = this._name2states[name]; + if (!state) { + console.warn(`Failed to play animation ${name}, not found.`); + return; + } + + state.time = 0.0; + this._animationController.crossFade(state, fadeDuration); + } + + public _resetTarget () { + const animationTarget = new AnimationTarget(); + this._clips.forEach((clip) => { + clip.channels.forEach((channel) => { + const targetPath = channel.target; + if (animationTarget.get(targetPath)) { + return; + } + const targetNode = this.node.getChildByPath(targetPath); + if (!targetNode) { + console.warn(`Animation target ${targetPath} not found in scene graph.`); + return; + } + animationTarget.add(targetPath, targetNode); + }); + }); + this._animationTarget = animationTarget; + this._animationController.setAnimationTarget(this._animationTarget); + } +} diff --git a/cocos/3d/framework/animation-system.js b/cocos/3d/framework/animation-system.js deleted file mode 100644 index c68d3b8165..0000000000 --- a/cocos/3d/framework/animation-system.js +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import System from '../ecs/system'; -import { FixedArray } from '../memop'; -/** - * @typedef {import('./animation-component').default} AnimationComponent - */ - -export default class AnimationSystem extends System { - constructor() { - super(); - - this._anims = new FixedArray(200); - } - - add(comp) { - this._anims.push(comp); - } - - remove(comp) { - this._anims.fastRemove(this._anims.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._anims.length; ++i) { -// let anim = this._anims.data[i]; -// if (!anim.enabled) { -// continue; -// } -// if (!anim.skeleton) { -// // console.error(`Animation component depends on skinning model component.`); -// let skeleton = findSkeleton(anim._entity); -// anim.skeleton = skeleton; -// } -// if (anim.skeleton) { -// anim._animCtrl.tick(this._app.deltaTime); -// } -// } -// } -} diff --git a/cocos/3d/framework/renderable-component.ts b/cocos/3d/framework/renderable-component.ts index 2389fe921a..bbf38ac38c 100644 --- a/cocos/3d/framework/renderable-component.ts +++ b/cocos/3d/framework/renderable-component.ts @@ -13,6 +13,10 @@ export class RenderableComponent extends Component { super(); } + public onLoad () { + this.sharedMaterials = this._materials.concat(); + } + @property({ type: [Material], displayName: 'Materials', diff --git a/cocos/3d/framework/skeleton-instance.js b/cocos/3d/framework/skeleton-instance.js deleted file mode 100644 index 92ac204819..0000000000 --- a/cocos/3d/framework/skeleton-instance.js +++ /dev/null @@ -1,176 +0,0 @@ -// @ts-check -import { vec3, quat, mat4 } from '../../core/vmath'; -import { Node } from '../../scene-graph'; - -let _v3_tmp = vec3.create(); -let _qt_tmp = quat.create(); - -/** - * - * @param {cc.Node} node - * @param {(node: cc.Node)=>void} fx - */ -function _walk(node, fx) { - fx(node); - for (let i = 0; i < node.childrenCount; ++i) { - _walk(node.children[i], fx); - } -} - -export default class SkeletonInstance { - /** - * - * @param {import("../assets/skeleton").default} skeleton - */ - constructor(skeleton) { - this._skeleton = skeleton; - - /** - * @type {cc.Node[]} - */ - this._nodes = this._copyNodesForest(skeleton._nodes); - - /** - * @type {mat4[]} - */ - this._matrices = new Array(this._nodes.length); - for (let i = 0; i < this._nodes.length; ++i) { - this._matrices[i] = mat4.create(); - } - - this.updateMatrices(); - } - - /** - * - * @param {cc.Node[]} nodes - */ - _copyNodesForest(nodes) { - /** @type {cc.Node[]} */ - const newNodes = new Array(nodes.length); - nodes.forEach((node, index) => { - newNodes[index] = this._copyNode(node); - }); - nodes.forEach((node, index) => { - const newNode = newNodes[index]; - node.children.forEach(childNode => { - const childIndex = nodes.indexOf(childNode); - newNode.addChild(newNodes[childIndex]); - }); - }); - return newNodes; - } - - /** - * - * @param {cc.Node} node - */ - _copyNode(node) { - const newNode = new Node(node.name); - newNode.setPosition(node.getPosition()); - newNode.setScale(node.getScale()); - newNode.setRotation(node.getRotation()); - return newNode; - } - - blend(fromSkel, toSkel, alpha) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - let jointFrom = fromSkel._nodes[i]; - let jointTo = toSkel._nodes[i]; - - vec3.lerp(_v3_tmp, jointFrom._lpos, jointTo._lpos, alpha); - joint.setPosition(_v3_tmp); - - vec3.lerp(_v3_tmp, jointFrom._lscale, jointTo._lscale, alpha); - joint.setScale(_v3_tmp); - - quat.lerp(_qt_tmp, jointFrom._lrot, jointTo._lrot, alpha); - joint.setRotation(_qt_tmp); - } - } - - updateMatrices() { - for (let i = 0; i < this._nodes.length; ++i) { - this._nodes[i].getWorldMatrix(this._matrices[i]); - } - } - - /** - * - * @param {number} i Index of the node. - */ - getWorldMatrix(i) { - return this._matrices[i]; - } - - getJointIndex(jointName) { - for (let i = 0; i < this._nodes.length; ++i) { - let joint = this._nodes[i]; - if (joint.name == jointName) { - return i; - } - } - return -1; - } - - getJointIndexFromOrignalNodeIndex(index) { - return index; - } - - clone() { - return new SkeletonInstance(this._skeleton); - } - - createMask() { - return new SkeletonMask(this); - } -} - -export class SkeletonMask { - /** - * - * @param {SkeletonInstance} skeleton - */ - constructor(skeleton) { - /** - * @type {SkeletonInstance} - * */ - this._skeleton = skeleton; - - this._isMaskedArray = new Array(skeleton._nodes.length); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - this._isMaskedArray[i] = false; - } - } - - setMasked(jointIndex, masked = true) { - this._isMaskedArray[jointIndex] = masked; - } - - setMaskedRecursive(jointIndex, masked = true) { - if (jointIndex < 0 || jointIndex >= this._skeleton._nodes.length) { - return; - } - - this._isMaskedArray[jointIndex] = masked; - _walk(this._skeleton._nodes[0], joint => { - let idx = this._skeleton._nodes.indexOf(joint); - if (idx >= 0) { - this._isMaskedArray[idx] = masked; - } - }); - } - - isMasked(jointIndex) { - return this._isMaskedArray[jointIndex]; - } - - complement() { - let ret = new SkeletonMask(this._skeleton); - for (let i = 0; i < this._isMaskedArray.length; ++i) { - ret._isMaskedArray[i] = !this._isMaskedArray[i]; - } - return ret; - } -} \ No newline at end of file diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts index 1f80f29aeb..ee0737bb9c 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/3d/framework/skinning-model-component.ts @@ -24,37 +24,18 @@ ****************************************************************************/ // @ts-check -import { Texture2D } from '../../assets/texture-2d'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { mat4 } from '../../core/vmath'; import { GFXDevice, GFXFeature } from '../../gfx/device'; import { SkinningModel } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; +import { Material } from '../assets/material'; import Skeleton from '../assets/skeleton'; -import * as utils from '../misc/utils'; import { ModelComponent } from './model-component'; const _m4_tmp = mat4.create(); -interface IJointTextureStorage { - nativeData: Float32Array; - texture: Texture2D; -} - -interface IJointUniformsStorage { - nativeData: Float32Array; -} - -type JointStorage = IJointTextureStorage | IJointUniformsStorage; - -interface ISkinningState { - skinningTarget: Map; - storage: JointStorage; -} - -function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { - return (storage as any).texture !== undefined; -} +type SkinningTarget = Map; /** * !#en The Skinning Model Component @@ -65,17 +46,6 @@ function isTextureStorage (storage: JointStorage): storage is IJointTextureStora @executeInEditMode @menu('Components/SkinningModelComponent') export default class SkinningModelComponent extends ModelComponent { - @property(Skeleton) - private _skeleton: Skeleton | null = null; - - @property(Node) - private _skinningRoot: Node | null = null; - - private _skinningState: ISkinningState | null = null; - - constructor () { - super(); - } /** * !#en The bone nodes @@ -89,7 +59,8 @@ export default class SkinningModelComponent extends ModelComponent { set skeleton (val) { this._skeleton = val; - this._resetSkinningState(); + this._resetSkinningTarget(); + this._bindSkeleton(); } @property({type: Node}) @@ -99,11 +70,23 @@ export default class SkinningModelComponent extends ModelComponent { set skinningRoot (value) { this._skinningRoot = value; - this._resetSkinningState(); + this._resetSkinningTarget(); + } + @property(Skeleton) + private _skeleton: Skeleton | null = null; + + @property(Node) + private _skinningRoot: Node | null = null; + + private _skinningTarget: SkinningTarget | null = null; + + constructor () { + super(); } public onLoad () { - this._resetSkinningState(); + super.onLoad(); + this._resetSkinningTarget(); } public update (dt) { @@ -114,19 +97,19 @@ export default class SkinningModelComponent extends ModelComponent { } public _tryUpdateMatrices () { - if (!this._skeleton || !this._skinningState) { + if (!this._skeleton || !this._skinningTarget || !this._model) { return; } - const skinningState = this._skinningState!; - const skeleton = this._skeleton!; + const skinningModel = this._model as SkinningModel; + const skeleton = this._skeleton; + const skinningTarget = this._skinningTarget; const cancelThisNodeTransform = this.node.getWorldMatrix(); mat4.invert(cancelThisNodeTransform, cancelThisNodeTransform); - this._skeleton.joints.forEach((joint, index) => { // If target joint doesn't exists in scene graph, skip it. - const targetNode = skinningState.skinningTarget.get(joint); + const targetNode = skinningTarget.get(joint); if (!targetNode) { return; } @@ -137,13 +120,10 @@ export default class SkinningModelComponent extends ModelComponent { const jointMatrix = _m4_tmp; mat4.multiply(jointMatrix, cancelThisNodeTransform, targetNode.getWorldMatrix()); mat4.multiply(jointMatrix, jointMatrix, bindpose); - _setJointMatrix(skinningState.storage.nativeData, index, jointMatrix); + skinningModel.updateJointMatrix(index, jointMatrix); }); - const storage = skinningState.storage; - if (isTextureStorage(storage)) { - storage.texture.directUpdate(storage.nativeData.buffer); - } + skinningModel.commitJointMatrices(); } public _createModel () { @@ -152,53 +132,33 @@ export default class SkinningModelComponent extends ModelComponent { public _updateModelParams () { super._updateModelParams(); - // Upload joint matrices. - if (this._skinningState !== null) { - const skinningState = this._skinningState; - const skinningModel = this._model as SkinningModel; - if (isTextureStorage(skinningState.storage)) { - const texture = skinningState.storage.texture; - skinningModel.setJointTexture(texture); - } else { - skinningModel.setJointMatrices(skinningState.storage.nativeData); - } + this._bindSkeleton(); + } + + protected _onMaterialModified (index: number, material: Material) { + super._onMaterialModified(index, material); + + const device = _getGlobalDevice(); + const useJointTexture = device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false; + this.getMaterial(0, CC_EDITOR)!.setDefines({ + CC_USE_SKINNING: true, + CC_USE_JOINTS_TEXTURE: useJointTexture, + }); + } + + private _bindSkeleton () { + if (this._model && this._skeleton) { + (this._model as SkinningModel).bindSkeleton(this._skeleton); } } - private _resetSkinningState () { - if (this._skinningState) { - if (isTextureStorage(this._skinningState.storage)) { - this._skinningState.storage.texture.destroy(); - } - this._skinningState = null; - } - + private _resetSkinningTarget () { if (!this._skeleton || !this._skinningRoot) { return; } - let storage: JointStorage; - - // Allocate joint matrices storage. - const device = _getGlobalDevice(); - if (device && device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { - const jointsTexture = utils.createJointsTexture(this._skeleton); - storage = { - texture: jointsTexture, - nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), - } as IJointTextureStorage; - } else { - storage = { - nativeData: new Float32Array(this._skeleton.joints.length * 16), - } as IJointUniformsStorage; - } - - const skinningState: ISkinningState = { - skinningTarget: new Map(), - storage, - }; - // Collect target to skin. + this._skinningTarget = new Map(); const rootNode = this._skinningRoot; this._skeleton.joints.forEach((joint) => { const targetNode = rootNode.getChildByPath(joint); @@ -206,10 +166,8 @@ export default class SkinningModelComponent extends ModelComponent { console.warn(`Skinning target ${joint} not found in scene graph.`); return; } - skinningState.skinningTarget.set(joint, targetNode); + this._skinningTarget!.set(joint, targetNode); }); - - this._skinningState = skinningState; } } @@ -217,22 +175,3 @@ function _getGlobalDevice (): GFXDevice | null { // @ts-ignore return cc.director.root.device; } - -function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { - out[16 * iMatrix + 0] = matrix.m00; - out[16 * iMatrix + 1] = matrix.m01; - out[16 * iMatrix + 2] = matrix.m02; - out[16 * iMatrix + 3] = matrix.m03; - out[16 * iMatrix + 4] = matrix.m04; - out[16 * iMatrix + 5] = matrix.m05; - out[16 * iMatrix + 6] = matrix.m06; - out[16 * iMatrix + 7] = matrix.m07; - out[16 * iMatrix + 8] = matrix.m08; - out[16 * iMatrix + 9] = matrix.m09; - out[16 * iMatrix + 10] = matrix.m10; - out[16 * iMatrix + 11] = matrix.m11; - out[16 * iMatrix + 12] = matrix.m12; - out[16 * iMatrix + 13] = matrix.m13; - out[16 * iMatrix + 14] = matrix.m14; - out[16 * iMatrix + 15] = matrix.m15; -} diff --git a/cocos/3d/framework/skinning-model-system.js b/cocos/3d/framework/skinning-model-system.js deleted file mode 100644 index 25d4542bf1..0000000000 --- a/cocos/3d/framework/skinning-model-system.js +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -// @ts-check -import { System } from '../ecs'; -import { FixedArray } from '../memop'; -import { _decorator } from '../../core/data/index'; -const { ccclass, property } = _decorator; - -/** - * !#en Skinning Model Component Management System - * - * !#ch 皮肤模型管理系统 - * @class SkinningModelSystem - * @extends System - */ -@ccclass('cc.SkinningModelSystem') -export default class SkinningModelSystem extends System { - constructor() { - super(); - - this._comps = new FixedArray(200); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - add(comp) { - this._comps.push(comp); - } - - /** - * !# Add skinning model component - * - * !#ch 添加需要统一管理的皮肤模型 - * @param {SkinningModelComponent} comp - */ - remove(comp) { - this._comps.fastRemove(this._comps.indexOf(comp)); - } - -// update() { -// for (let i = 0; i < this._comps.length; ++i) { -// let comp = this._comps.data[i]; -// if (comp.enabled === false) { -// continue; -// } - -// comp._updateMatrices(); -// } -// } -} diff --git a/cocos/core/director.js b/cocos/core/director.js index eb6e6e56d1..d701c45a1c 100644 --- a/cocos/core/director.js +++ b/cocos/core/director.js @@ -33,7 +33,6 @@ import Scheduler from './scheduler'; import { autoRelease } from '../load-pipeline/auto-release-utils'; import ComponentScheduler from '../scene-graph/component-scheduler'; import NodeActivator from '../scene-graph/node-activator'; -// import AnimationSystem from '../3d/framework/animation-system'; // import SkinningModelSystem from '../3d/framework/skinning-model-system'; import { PhysicsSystem } from '../3d/framework/physics/physics-system'; import { getClassByName } from './utils/js'; diff --git a/cocos/core/game.js b/cocos/core/game.js index b1cb8a09e1..df7594afa4 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -771,6 +771,7 @@ var game = { this._gfxDevice = new cc.WebGLGFXDevice; this._gfxDevice.initialize({ canvasElm : localCanvas, + debug: true, }); //let device = this._renderContext = new gfx.Device(localCanvas, {}); diff --git a/cocos/gfx/device.ts b/cocos/gfx/device.ts index e9d17c6ba7..b4d36fc1c3 100644 --- a/cocos/gfx/device.ts +++ b/cocos/gfx/device.ts @@ -25,6 +25,7 @@ export interface IGFXDeviceInfo { canvasElm: HTMLElement; isAntialias?: boolean; isPremultipliedAlpha?: boolean; + debug?: boolean; } // tslint:disable: max-line-length diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index 07d0e3df5b..ae5a1230c4 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,3 +1,4 @@ +import * as WebGLDeveloperTools from 'webgl-debug'; import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -253,6 +254,9 @@ export class WebGLGFXDevice extends GFXDevice { }; this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); + if (this._webGLRC && info.debug) { + this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); + } } catch (err) { console.error(err); return false; @@ -1076,4 +1080,8 @@ export class WebGLGFXDevice extends GFXDevice { gl.colorMask(true, true, true, true); gl.blendColor(0.0, 0.0, 0.0, 0.0); } + + private _onWebGLError (error: GLenum, functionName: string, ...args: any[]) { + throw new Error(`${WebGLDeveloperTools.glEnumToString(error)} was caused by call to ${functionName}`); + } } diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index 95a7a179d2..e734f8f7d6 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -1,8 +1,12 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. +import Skeleton from '../../3d/assets/skeleton'; +import { createJointsTexture } from '../../3d/misc/utils'; import { Texture2D } from '../../assets/texture-2d'; +import { mat4 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define'; +import { GFXFeature } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Node } from '../../scene-graph/node'; import { Model } from '../scene/model'; @@ -11,9 +15,28 @@ import { SkinningUBO } from './model-uniforms'; const textureSizeBuffer = new Float32Array(4); +interface IJointTextureStorage { + nativeData: Float32Array; + texture: Texture2D; +} + +interface IJointUniformsStorage { + nativeData: Float32Array; +} + +type JointStorage = IJointTextureStorage | IJointUniformsStorage; + +function isTextureStorage (storage: JointStorage): storage is IJointTextureStorage { + return 'texture' in storage; +} + +function isUniformStorage (storage: JointStorage): storage is IJointUniformsStorage { + return !('texture' in storage); +} + export class SkinningModel extends Model { + private _jointStorage: JointStorage | null = null; private _skinningUBO: GFXBuffer; - private _jointTexture: Texture2D | null = null; constructor (scene: RenderScene, node: Node) { super(scene, node); @@ -26,27 +49,83 @@ export class SkinningModel extends Model { }); } - public setJointTexture (texture: Texture2D) { - this._jointTexture = texture; - textureSizeBuffer[0] = texture.width; - this._skinningUBO.update( + public bindSkeleton (skeleton: Skeleton) { + this._destroyJointStorage(); + + if (this._device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false) { + const jointsTexture = createJointsTexture(skeleton); + textureSizeBuffer[0] = jointsTexture.width; + this._skinningUBO.update( textureSizeBuffer, SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET, textureSizeBuffer.byteLength); + this._jointStorage = { + texture: jointsTexture, + nativeData: new Float32Array(jointsTexture.width * jointsTexture.height * 4), + } as IJointTextureStorage; + } else { + this._jointStorage = { + nativeData: new Float32Array(skeleton.joints.length * 16), + } as IJointUniformsStorage; + } } - public setJointMatrices (data: Float32Array) { - this._skinningUBO.update(data, SkinningUBO.MAT_JOINT_OFFSET); + public updateJointMatrix (iMatrix: number, matrix: mat4) { + if (!this._jointStorage) { + return; + } + _setJointMatrix(this._jointStorage.nativeData, iMatrix, matrix); + } + + public commitJointMatrices () { + if (!this._jointStorage) { + return; + } + if (isUniformStorage(this._jointStorage)) { + this._skinningUBO.update(this._jointStorage.nativeData, SkinningUBO.MAT_JOINT_OFFSET); + } else if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.directUpdate(this._jointStorage.nativeData.buffer); + } } protected _onCreatePSO (pso: GFXPipelineState) { super._onCreatePSO(pso); pso.pipelineLayout.layouts[0].bindBuffer(SkinningUBO.BLOCK.binding, this._skinningUBO); - if (this._jointTexture) { - const view = this._jointTexture.getGFXTextureView(); - const sampler = this._jointTexture.getGFXSampler(); + if (this._jointStorage && isTextureStorage(this._jointStorage)) { + const jointTexture = this._jointStorage.texture; + const view = jointTexture.getGFXTextureView(); + const sampler = jointTexture.getGFXSampler(); if (view && sampler) { pso.pipelineLayout.layouts[0].bindTextureView(SkinningUBO.JOINT_TEXTURE.binding, view); pso.pipelineLayout.layouts[0].bindSampler(SkinningUBO.JOINT_TEXTURE.binding, sampler); } } } + + private _destroyJointStorage () { + if (!this._jointStorage) { + return; + } + if (isTextureStorage(this._jointStorage)) { + this._jointStorage.texture.destroy(); + } + this._jointStorage = null; + } +} + +function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { + out[16 * iMatrix + 0] = matrix.m00; + out[16 * iMatrix + 1] = matrix.m01; + out[16 * iMatrix + 2] = matrix.m02; + out[16 * iMatrix + 3] = matrix.m03; + out[16 * iMatrix + 4] = matrix.m04; + out[16 * iMatrix + 5] = matrix.m05; + out[16 * iMatrix + 6] = matrix.m06; + out[16 * iMatrix + 7] = matrix.m07; + out[16 * iMatrix + 8] = matrix.m08; + out[16 * iMatrix + 9] = matrix.m09; + out[16 * iMatrix + 10] = matrix.m10; + out[16 * iMatrix + 11] = matrix.m11; + out[16 * iMatrix + 12] = matrix.m12; + out[16 * iMatrix + 13] = matrix.m13; + out[16 * iMatrix + 14] = matrix.m14; + out[16 * iMatrix + 15] = matrix.m15; } diff --git a/globals.d.ts b/globals.d.ts index 163998848c..8c476a4668 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -45,4 +45,13 @@ type RecursivePartial = { [P in keyof T]?: T[P] extends Array ? Array> : T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial; -}; \ No newline at end of file +}; + +declare module "webgl-debug" { + export function makeDebugContext( + webGLRenderingContext: WebGLRenderingContext, + throwOnGLError: (err: GLenum, funcName: string, ...args: any[]) => void + ): WebGLRenderingContext; + + export function glEnumToString(glEnum: GLenum): string; +} \ No newline at end of file diff --git a/package.json b/package.json index a4635ad24b..665a556c2d 100644 --- a/package.json +++ b/package.json @@ -77,6 +77,7 @@ "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0", + "webgl-debug": "^2.0.1", "yargs": "^12.0.5" } } From 1d6e4804ecc72a5d1bbd3f408f65bf9fa2c4c59b Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 24 Jan 2019 16:02:37 +0800 Subject: [PATCH 248/267] fix effects --- cocos/3d/builtin/effects.js | 72 +++++++++++++++++++++++ cocos/3d/framework/light-component.ts | 14 +++-- cocos/renderer/core/pass.ts | 19 +++--- cocos/renderer/core/program-lib.ts | 1 + cocos/renderer/scene/directional-light.ts | 2 +- cocos/renderer/scene/light.ts | 2 +- cocos/renderer/scene/point-light.ts | 2 +- cocos/renderer/scene/spot-light.ts | 4 +- playground/simple.html | 4 +- 9 files changed, 95 insertions(+), 25 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index b8c14cddfd..60a303441e 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,5 +1,77 @@ // absolute essential effects export default [ + { + "name": "builtin-effect-pbr", + "techniques": [{"passes":[{"program":"builtin-effect-pbr|pbr-vs:vert|pbr-fs:frag", "properties":{"albedo":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "albedo_texture":{"type":29, "value":"grey"}, "metallic":{"type":13, "value":[0.5]}, "metallic_texture":{"type":29, "value":"grey"}, "roughness":{"type":13, "value":[0.7]}, "roughness_texture":{"type":29, "value":"grey"}, "ao":{"type":13, "value":[0.2]}, "ao_texture":{"type":29, "value":"grey"}, "mra_texture":{"type":29, "value":"grey"}, "emissive":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "normal_texture":{"type":29, "value":"normal"}, "diffuseEnvTexture":{"type":32, "value":"white-cube"}, "specularEnvTexture":{"type":32, "value":"white-cube"}, "brdfLUT":{"type":29, "value":"grey"}, "maxReflectionLod":{"type":13, "value":[9]}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-pbr|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], + "shaders": [ + { + "name": "builtin-effect-pbr|pbr-vs:vert|pbr-fs:frag", + "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\nvarying vec3 pos_w;\nvarying vec3 normal_w;\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 uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_MRA_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\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\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_MRA_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#if USE_TEX_LOD\n#extension GL_EXT_shader_texture_lod: enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\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 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;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\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#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 pos_w;\nvarying vec3 normal_w;\n#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\n#if USE_IBL\n uniform samplerCube diffuseEnvTexture;\n uniform samplerCube specularEnvTexture;\n uniform sampler2D brdfLUT;\n#endif\n uniform vec4 albedo;\n uniform float metallic;\n uniform float roughness;\n uniform float ao;\n uniform float maxReflectionLod;\n uniform vec4 emissive;\n uniform float alphaTestThreshold;\n#if USE_ALBEDO_TEXTURE\n uniform sampler2D albedo_texture;\n#endif\n#if USE_MRA_TEXTURE\n uniform sampler2D mra_texture;\n#endif\n#if USE_METALLIC_TEXTURE\n uniform sampler2D metallic_texture;\n#endif\n#if USE_ROUGHNESS_TEXTURE\n uniform sampler2D roughness_texture;\n#endif\n#if USE_AO_TEXTURE\n uniform sampler2D ao_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n \n vec3 getNormalFromTexture() {\n vec3 tangentNormal = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n vec3 q1 = dFdx(pos_w);\n vec3 q2 = dFdy(pos_w);\n vec2 st1 = dFdx(uv0);\n vec2 st2 = dFdy(uv0);\n vec3 N = normalize(normal_w);\n vec3 T = normalize(q1*st2.t - q2*st1.t);\n vec3 B = -normalize(cross(N, T));\n mat3 TBN = mat3(T, B, N);\n return normalize(TBN * tangentNormal);\n }\n#endif\nfloat distributionGGX(vec3 N, vec3 H, float roughness) {\n float a = roughness * roughness;\n float a2 = a * a;\n float NdotH = max(dot(N, H), 0.0);\n float NdotH2 = NdotH * NdotH;\n float nom = a2;\n float denom = (NdotH2 * (a2 - 1.0) + 1.0);\n denom = 3.14159265359 * denom * denom;\n return nom / denom;\n}\nfloat geometrySchlickGGX(float NdotV, float roughness) {\n float r = (roughness + 1.0);\n float k = (r * r) / 8.0;\n float nom = NdotV;\n float denom = NdotV * (1.0 - k) + k;\n return nom / denom;\n}\nfloat geometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {\n float NdotV = max(dot(N, V), 0.0);\n float NdotL = max(dot(N, L), 0.0);\n float ggx2 = geometrySchlickGGX(NdotV, roughness);\n float ggx1 = geometrySchlickGGX(NdotL, roughness);\n return ggx1 * ggx2;\n}\nvec3 fresnelSchlick(float cosTheta, vec3 F0) {\n float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta);\n return F0 + (1.0 - F0) * fresnel;\n}\nvec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) {\n float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta);\n return F0 + (max(vec3(1.0 - roughness), F0) - F0) * fresnel;\n}\nvec3 brdf(LightInfo lightInfo, vec3 N, vec3 V, vec3 F0, vec3 albedo, float metallic, float roughness) {\n vec3 H = normalize(V + lightInfo.lightDir);\n float NDF = distributionGGX(N, H, roughness);\n float G = geometrySmith(N, V, lightInfo.lightDir, roughness);\n vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0);\n vec3 nominator = NDF * G * F;\n float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, lightInfo.lightDir), 0.0) + 0.001; \n vec3 specular = nominator / denominator;\n \n vec3 kS = F;\n \n \n \n vec3 kD = vec3(1.0) - kS;\n \n \n \n kD *= 1.0 - metallic;\n float NdotL = max(dot(N, lightInfo.lightDir), 0.0);\n return (kD * albedo / 3.14159265359 + specular) * lightInfo.radiance * NdotL;\n}\nvec4 frag() {\n float opacity = 1.0;\n #if USE_ALBEDO_TEXTURE\n vec4 baseColor = albedo * gammaToLinearSpaceRGBA(texture2D(albedo_texture, uv0));\n vec3 albedo = baseColor.rgb;\n opacity = baseColor.a;\n #else\n opacity = albedo.a;\n vec3 albedo = albedo.rgb;\n #endif\n #if USE_ALPHA_TEST\n if(opacity < alphaTestThreshold) discard;\n #endif\n #if USE_MRA_TEXTURE\n vec3 metalRoughness = texture2D(mra_texture, uv0).rgb;\n float metallic = metalRoughness.r;\n float roughness = metalRoughness.g;\n float ao = metalRoughness.b;\n #else\n #if USE_METALLIC_TEXTURE\n float metallic = texture2D(metallic_texture, uv0).r;\n #endif\n #if USE_ROUGHNESS_TEXTURE\n float roughness = texture2D(roughness_texture, uv0).r;\n #endif\n #if USE_AO_TEXTURE\n float ao = texture2D(ao_texture, uv0).r;\n #endif\n #endif\n vec3 N = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n N = getNormalFromTexture();\n #endif\n vec3 V = normalize(cc_cameraPos.xyz - pos_w);\n \n \n vec3 F0 = vec3(0.04);\n F0 = mix(F0, albedo, metallic);\n \n vec3 Lo = vec3(0.0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n LightInfo info = computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n LightInfo info = computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n LightInfo info = computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if USE_EMISSIVE\n vec3 emissiveColor = emissive.rgb;\n #if USE_EMISSIVE_TEXTURE\n emissiveColor *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n Lo += emissiveColor;\n #endif\n \n vec3 ambient = vec3(0.03) * albedo * ao;\n #if USE_IBL\n \n vec3 F = fresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);\n vec3 kS = F;\n vec3 kD = vec3(1.0) - kS;\n kD *= 1.0 - metallic;\n #if USE_RGBE_IBL_DIFFUSE\n vec3 diffuseEnv = unpackRGBE(textureCube(diffuseEnvTexture, N));\n #else\n vec3 diffuseEnv = textureCube(diffuseEnvTexture, N).rgb;\n #endif\n vec3 diffuse = diffuseEnv * albedo;\n \n vec3 R = reflect(-V, N);\n #if USE_TEX_LOD\n #if USE_RGBE_IBL_SPECULAR\n vec3 specularEnv = unpackRGBE(textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod));\n #else\n vec3 specularEnv = textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod).rgb;\n #endif\n #else\n #if USE_RGBE_IBL_SPECULAR\n vec3 specularEnv = unpackRGBE(textureCube(specularEnvTexture, R));\n #else\n vec3 specularEnv = textureCube(specularEnvTexture, R).rgb;\n #endif\n #endif\n vec2 brdf = texture2D(brdfLUT, vec2(max(dot(N, V), 0.0), 1.0 - roughness)).rg;\n vec3 specular = specularEnv * (F * brdf.x + brdf.y);\n ambient = (kD * diffuse + specular) * ao;\n #endif\n vec3 color = ambient + Lo;\n #if CC_USE_SHADOW_MAP\n color *= computeShadow();\n #endif\n \n color = color / (color + vec3(1.0));\n \n vec4 finalColor = vec4(color, opacity);\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"USE_ALBEDO_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, + {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_TEX_LOD", "type":"boolean", "defines":[]}, + {"name":"USE_IBL", "type":"boolean", "defines":[]}, + {"name":"USE_MRA_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_METALLIC_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_ROUGHNESS_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_AO_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, + {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, + {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, + {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, + {"name":"USE_RGBE_IBL_DIFFUSE", "type":"boolean", "defines":["USE_IBL"]}, + {"name":"USE_RGBE_IBL_SPECULAR", "type":"boolean", "defines":["USE_IBL"]} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8} + ]}, + {"name": "Constants", "size": 52, "defines": [], "binding": 1, "members": [ + {"name":"albedo", "type":16, "count":1, "size":16}, + {"name":"metallic", "type":13, "count":1, "size":4}, + {"name":"roughness", "type":13, "count":1, "size":4}, + {"name":"ao", "type":13, "count":1, "size":4}, + {"name":"maxReflectionLod", "type":13, "count":1, "size":4}, + {"name":"emissive", "type":16, "count":1, "size":16}, + {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} + ]} + ], + "samplers": [ + {"name":"diffuseEnvTexture", "type":32, "count":1, "defines":["USE_IBL"], "binding":2}, + {"name":"specularEnvTexture", "type":32, "count":1, "defines":["USE_IBL"], "binding":3}, + {"name":"brdfLUT", "type":29, "count":1, "defines":["USE_IBL"], "binding":4}, + {"name":"albedo_texture", "type":29, "count":1, "defines":["USE_ALBEDO_TEXTURE"], "binding":5}, + {"name":"mra_texture", "type":29, "count":1, "defines":["USE_MRA_TEXTURE"], "binding":6}, + {"name":"metallic_texture", "type":29, "count":1, "defines":["USE_METALLIC_TEXTURE"], "binding":7}, + {"name":"roughness_texture", "type":29, "count":1, "defines":["USE_ROUGHNESS_TEXTURE"], "binding":8}, + {"name":"ao_texture", "type":29, "count":1, "defines":["USE_AO_TEXTURE"], "binding":9}, + {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":10}, + {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":11} + ], + "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives", "USE_TEX_LOD":"EXT_shader_texture_lod"} + }, + { + "name": "builtin-effect-pbr|shadow-depth-vs:vert|shadow-depth-fs:frag", + "vert": "\nattribute vec3 a_position;\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 float vDepth;\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 mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} + ], + "blocks": [], + "samplers": [], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-phong", "techniques": [{"passes":[{"program":"builtin-effect-phong|phong-vs:vert|phong-fs:frag", "properties":{"diffuseColor":{"type":17, "value":[0.3, 0.3, 0.3, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "diffuse_texture":{"type":29, "value":"grey"}, "specularColor":{"type":17, "value":[0, 0, 0, 0]}, "specular_texture":{"type":29, "value":"grey"}, "emissiveColor":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "glossiness":{"type":13, "value":[10]}, "normal_texture":{"type":29, "value":"normal"}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts index a15be397b5..361d058cf6 100644 --- a/cocos/3d/framework/light-component.ts +++ b/cocos/3d/framework/light-component.ts @@ -183,9 +183,10 @@ export default class LightComponent extends Component { set color (val) { this._color = val; - this._colorData[0] = val.r * this._intensity; - this._colorData[1] = val.g * this._intensity; - this._colorData[2] = val.b * this._intensity; + const scale = this._intensity / 255; + this._colorData[0] = val.r * scale; + this._colorData[1] = val.g * scale; + this._colorData[2] = val.b * scale; if (this._light) { this._light.color = this._colorData; } @@ -204,9 +205,10 @@ export default class LightComponent extends Component { set intensity (val) { this._intensity = val; - this._colorData[0] = this._color.r * val; - this._colorData[1] = this._color.g * val; - this._colorData[2] = this._color.b * val; + const scale = val / 255; + this._colorData[0] = this._color.r * scale; + this._colorData[1] = this._color.g * scale; + this._colorData[2] = this._color.b * scale; if (this._light) { this._light.color = this._colorData; } diff --git a/cocos/renderer/core/pass.ts b/cocos/renderer/core/pass.ts index 3b5e0c3bec..9de364d044 100644 --- a/cocos/renderer/core/pass.ts +++ b/cocos/renderer/core/pass.ts @@ -155,12 +155,8 @@ export class Pass { stride: 1, // N/A for blocks usage: GFXBufferUsageBit.UNIFORM, }); - if (buffer) { - this._buffers[u.binding] = buffer; - } else { - console.error('create buffer failed.'); - return; - } + if (buffer) { this._buffers[u.binding] = buffer; } + else { console.error('create buffer failed.'); return; } // buffer data processing system const block: IBlock = this._blocks[u.binding] = { buffer: buffer.buffer as ArrayBuffer, @@ -188,13 +184,12 @@ export class Pass { const inf = info.properties && info.properties[u.name]; const samplerInfo = Object.assign({ name: u.name }, inf && inf.sampler); const sampler = device.createSampler(samplerInfo); - if (sampler) { - this._samplers[u.binding] = sampler; - } else { - console.error('create sampler failed.'); - } + if (sampler) { this._samplers[u.binding] = sampler; } + else { console.error('create sampler failed.'); } const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type]; - this._textureViews[u.binding] = builtinResMgr.get(texName).getGFXTextureView()!; + const texture = builtinResMgr.get(texName); + if (texture) { this._textureViews[u.binding] = texture.getGFXTextureView()!; } + else { console.warn(`illegal texture default value ${texName}`); } } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 2bfc0a874f..7945b1bf94 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -125,6 +125,7 @@ class ProgramLib { if (program !== undefined) { return program; } + defines.CC_NUM_DIR_LIGHTS = 1; // get template const tmpl = this._templates[name]; diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/renderer/scene/directional-light.ts index cde70935a4..c58f678aba 100644 --- a/cocos/renderer/scene/directional-light.ts +++ b/cocos/renderer/scene/directional-light.ts @@ -4,7 +4,7 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; export class DirectionalLight extends Light { - protected _direction = new Float32Array(4); + protected _direction = Float32Array.from([0, 0, 1, 0]); set direction (val: Vec3) { vec3.array(this._direction, val); diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts index 45379330e2..526b708991 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/renderer/scene/light.ts @@ -8,7 +8,7 @@ export enum LightType { } export class Light { - protected _color = new Float32Array(4); + protected _color = Float32Array.from([1, 1, 1, 1]); protected _enabled = false; set enabled (val) { diff --git a/cocos/renderer/scene/point-light.ts b/cocos/renderer/scene/point-light.ts index 68af391dc0..bfd677c175 100644 --- a/cocos/renderer/scene/point-light.ts +++ b/cocos/renderer/scene/point-light.ts @@ -4,7 +4,7 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; export class PointLight extends Light { - protected _positionAndRange = new Float32Array(4); + protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); set position (val: Vec3) { vec3.array(this._positionAndRange, val); diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts index 30ce89a366..dd56fd8c1f 100644 --- a/cocos/renderer/scene/spot-light.ts +++ b/cocos/renderer/scene/spot-light.ts @@ -4,8 +4,8 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; export class SpotLight extends Light { - protected _direction = new Float32Array(4); - protected _positionAndRange = new Float32Array(4); + protected _direction = Float32Array.from([0, 0, 1, 0]); + protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); set position (val: Vec3) { vec3.array(this._positionAndRange, val); diff --git a/playground/simple.html b/playground/simple.html index aef133da14..b02fcdb872 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -68,7 +68,7 @@ const material = new cc.Material(); material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js - material.effectName = 'builtin-effect-phong'; + material.effectName = 'builtin-effect-pbr'; const len = 50; const models = [], passes = []; @@ -84,7 +84,7 @@ // material instance initialized here passes.push(modelCom.material.passes[0]); } - const handle = passes[0].getHandle('diffuseColor'); + const handle = passes[0].getHandle('albedo'); { const material = new cc.Material(); From 0cf11c82152029a2cb498a5b28c905774f31204a Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 16:05:34 +0800 Subject: [PATCH 249/267] commit files --- cocos/3d/builtin/effects.js | 32 ++++++++- cocos/gfx/webgl/webgl-commands.ts | 111 ++++++++++++++++-------------- cocos/renderer/ui/ui.ts | 11 ++- 3 files changed, 98 insertions(+), 56 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index b8c14cddfd..89b4e73776 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -79,7 +79,7 @@ export default [ }, { "name": "builtin-effect-sprite", - "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":{"u_texSampler":{"type":29, "value":"default"}}}]}], + "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":{"u_texSampler":{"type":29, "value":"default", "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0, "addressU":2, "addressV":2}}}}]}], "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", @@ -97,5 +97,35 @@ export default [ "dependencies": {} } ] + }, + { + "name": "builtin-effect-unlit", + "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}], + "shaders": [ + { + "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", + "vert": "\nattribute vec3 a_position;\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":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"USE_COLOR", "type":"boolean", "defines":[]} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [ + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8} + ]}, + {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [ + {"name":"color", "type":16, "count":1, "size":16} + ]} + ], + "samplers": [ + {"name":"mainTexture", "type":29, "count":1, "defines":["USE_TEXTURE"], "binding":2} + ], + "dependencies": {} + } + ] } ]; diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 0c42b0d202..8c08de88b4 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1899,7 +1899,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case GFXBindingType.SAMPLER: { - if (gpuBinding.gpuSampler && gpuBinding.gpuTexView) { + if (gpuBinding.gpuSampler) { let glSampler: WebGLGPUUniformSampler | null = null; @@ -1911,8 +1911,6 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } if (glSampler) { - const gpuTexture = gpuBinding.gpuTexView.gpuTexture; - for (const texUnit of glSampler.units) { if (device.stateCache.texUnit !== texUnit) { @@ -1923,64 +1921,71 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web let glTexUnit: IWebGLTexUnit | null = null; let isTexParamInvalied = false; - switch (glSampler.glType) { - case WebGLRenderingContext.SAMPLER_2D: { - glTexUnit = device.stateCache.glTex2DUnits[texUnit]; - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; - isTexParamInvalied = true; + if (gpuBinding.gpuTexView) { + const gpuTexture = gpuBinding.gpuTexView.gpuTexture; + switch (glSampler.glType) { + case WebGLRenderingContext.SAMPLER_2D: { + glTexUnit = device.stateCache.glTex2DUnits[texUnit]; + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_2D, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + isTexParamInvalied = true; + } + break; } - break; - } - case WebGLRenderingContext.SAMPLER_CUBE: { - glTexUnit = device.stateCache.glTexCubeUnits[texUnit]; - - if (glTexUnit.glTexture !== gpuTexture.glTexture) { - gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); - glTexUnit.glTexture = gpuTexture.glTexture; - isTexParamInvalied = true; + case WebGLRenderingContext.SAMPLER_CUBE: { + glTexUnit = device.stateCache.glTexCubeUnits[texUnit]; + + if (glTexUnit.glTexture !== gpuTexture.glTexture) { + gl.bindTexture(WebGLRenderingContext.TEXTURE_CUBE_MAP, gpuTexture.glTexture); + glTexUnit.glTexture = gpuTexture.glTexture; + isTexParamInvalied = true; + } + break; + } + default: { + console.error('Unsupported GL Texture type.'); } - break; - } - default: { - console.error('Unsupported GL Texture type.'); - } - } - - if (glTexUnit) { - const gpuSampler = gpuBinding.gpuSampler; - - if (glTexUnit.minFilter !== gpuSampler.glMinFilter || isTexParamInvalied) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuSampler.glMinFilter); - glTexUnit.minFilter = gpuSampler.glMinFilter; } - if (glTexUnit.magFilter !== gpuSampler.glMagFilter || isTexParamInvalied) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter); - glTexUnit.magFilter = gpuSampler.glMagFilter; + if (glTexUnit) { + const gpuSampler = gpuBinding.gpuSampler; + + if (glTexUnit.minFilter !== gpuSampler.glMinFilter || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MIN_FILTER, gpuSampler.glMinFilter); + glTexUnit.minFilter = gpuSampler.glMinFilter; + } + + if (glTexUnit.magFilter !== gpuSampler.glMagFilter || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter); + glTexUnit.magFilter = gpuSampler.glMagFilter; + } + + if (glTexUnit.wrapS !== gpuSampler.glWrapS || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuSampler.glWrapS); + glTexUnit.wrapS = gpuSampler.glWrapS; + } + + if (glTexUnit.wrapT !== gpuSampler.glWrapT || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuSampler.glWrapT); + glTexUnit.wrapT = gpuSampler.glWrapT; + } + + /* + if(glTexUnit.wrapR !== gpuSampler.glWrapR || isTexParamInvalied) { + gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_R, gpuSampler.glWrapR); + glTexUnit.wrapR = gpuSampler.glWrapR; + } + */ } - - if (glTexUnit.wrapS !== gpuSampler.glWrapS || isTexParamInvalied) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_S, gpuSampler.glWrapS); - glTexUnit.wrapS = gpuSampler.glWrapS; - } - - if (glTexUnit.wrapT !== gpuSampler.glWrapT || isTexParamInvalied) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_T, gpuSampler.glWrapT); - glTexUnit.wrapT = gpuSampler.glWrapT; - } - - /* - if(glTexUnit.wrapR !== gpuSampler.glWrapR || isTexParamInvalied) { - gl.texParameteri(gpuTexture.glTarget, WebGLRenderingContext.TEXTURE_WRAP_R, gpuSampler.glWrapR); - glTexUnit.wrapR = gpuSampler.glWrapR; - } - */ + } else { + console.error("Not found texture view on binding unit " + gpuBinding.binding); } } } // if - } // if + } else { + console.error("Not found sampler or texture view on binding unit " + gpuBinding.binding); + } break; } diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 1927ce3b97..0d64621502 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -227,7 +227,12 @@ export class UI { } public update (dt: number) { + + for (let i = 0; i < this._batches.array.length; ++i) { + this._drawBatchPool.remove(this._batches.array[i]); + } this._batches.clear(); + this._commitUIRenderDatas = []; this._renderScreens(); @@ -287,7 +292,7 @@ export class UI { curCamera = camera; - cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); + cmdBuff.beginRenderPass(framebuffer, this._renderArea, [camera.clearColor], camera.clearDepth, camera.clearStencil); } material.bindingLayout.bindBuffer(0, this._uiUBO!); @@ -422,7 +427,9 @@ export class UI { if (curCamera !== uiRenderData.camera) { isNewBatch = true; curCamera = uiRenderData.camera; - } else if (curTexView !== uiRenderData.texture.getGFXTextureView()) { + } + + if (curTexView !== uiRenderData.texture.getGFXTextureView()) { curTexView = uiRenderData.texture.getGFXTextureView(); isNewBatch = true; } From 3d40193b3c5d5d21f6d9194b0359dfd2111397b4 Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Thu, 24 Jan 2019 16:08:20 +0800 Subject: [PATCH 250/267] fix set material bug --- cocos/3d/framework/model-component.ts | 23 ++++++++++++----------- cocos/renderer/scene/submodel.ts | 13 +++++++++++-- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index 201b134e1a..2488cfc3bd 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -163,15 +163,16 @@ export class ModelComponent extends RenderableComponent { } public onLoad () { - + super.onLoad(); } public onEnable () { this._updateModels(); this._updateCastShadow(); this._updateReceiveShadow(); + if (this._model) { - this._model.enabled = true; + this._model.enabled = this.enabledInHierarchy; } } @@ -189,23 +190,21 @@ export class ModelComponent extends RenderableComponent { protected _updateModels (forceUpdate: boolean = false) { if (!this.enabled || !this.node._scene || !this._mesh || (this._model && !forceUpdate)) { + if (this._model) { + this._model.enabled = false; + } return; } if (this._model) { this._model.destroy(); - this._model = null; + } else { + this._model = this._createModel(); } - this._model = this._createModel(); - this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._updateModelParams(); - - if (this._model) { - this._model.enabled = this.enabledInHierarchy; - } } protected _createModel () { @@ -234,11 +233,13 @@ export class ModelComponent extends RenderableComponent { if (this._model == null) { return; } - this._model.setSubModelMaterial(idx, material); + this._onRebuildPSO(idx, material); } protected _onRebuildPSO (idx, material) { - this._onMaterialModified(idx, material); + if (this._model) { + this._model.setSubModelMaterial(idx, material); + } } protected _clearMaterials () { diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts index 3e031746e5..ecc5427ff8 100644 --- a/cocos/renderer/scene/submodel.ts +++ b/cocos/renderer/scene/submodel.ts @@ -1,7 +1,7 @@ import { Material } from '../../3d/assets/material'; import { IRenderingSubmesh } from '../../3d/assets/mesh'; import { GFXCommandBuffer } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; +import { GFXCommandBufferType, GFXStatus } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler, IGFXInputAssemblerInfo } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; @@ -69,7 +69,11 @@ export class SubModel { if (this._subMeshObject!.indirectBuffer) { iaInfo.indirectBuffer = this._subMeshObject!.indirectBuffer; } - this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); + if (this._inputAssembler) { + this._inputAssembler.initialize(iaInfo); + } else { + this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); + } } get subMeshData () { @@ -128,6 +132,11 @@ export class SubModel { type: GFXCommandBufferType.SECONDARY, }; this._cmdBuffers[index] = device.createCommandBuffer(cmdBufferInfo); + } else if (this._cmdBuffers[index].status == GFXStatus.UNREADY) { + this._cmdBuffers[index].initialize({ + allocator: device.commandAllocator, + type: GFXCommandBufferType.SECONDARY, + }); } const inputAssembler = this._inputAssembler as GFXInputAssembler; From be9eb8b54c1fd96d449a9357c8085b9cc8a4af91 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 16:16:02 +0800 Subject: [PATCH 251/267] ban webgl debug tools --- cocos/gfx/webgl/webgl-device.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index ae5a1230c4..e16a86d647 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,4 +1,4 @@ -import * as WebGLDeveloperTools from 'webgl-debug'; +//import * as WebGLDeveloperTools from 'webgl-debug'; import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -254,9 +254,11 @@ export class WebGLGFXDevice extends GFXDevice { }; this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); + /* if (this._webGLRC && info.debug) { this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); } + */ } catch (err) { console.error(err); return false; From 82210c93545b65f44174828ade64fd17769244e7 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 16:26:16 +0800 Subject: [PATCH 252/267] fix bug --- cocos/gfx/webgl/webgl-commands.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 8c08de88b4..e466db03b6 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1743,7 +1743,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } glUniform.vf32!.set(_uniformValues); - gl.uniform1fv(glUniform.glLoc, glUniform.vf32!); + gl.uniform1fv(glUniform.glLoc, _uniformValues); break; } } From a09ecfc89ffcb7f64b1eb21d1b9a2b21f175308f Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 24 Jan 2019 16:31:17 +0800 Subject: [PATCH 253/267] fix webgl-debug --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 665a556c2d..7bb2f28519 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,7 @@ "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0", - "webgl-debug": "^2.0.1", + "webgl-debug": "github:cocos-creator/webgl-debug#5f9cbdd", "yargs": "^12.0.5" } } From b9c93ccf642b6e8bf0aa7635344ec2d26b813466 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 24 Jan 2019 17:06:03 +0800 Subject: [PATCH 254/267] fix webgl-debug --- cocos/gfx/webgl/webgl-device.ts | 4 +--- package.json | 2 +- rollup/build-engine.ts | 1 + rollup/config.js | 3 ++- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index e16a86d647..ae5a1230c4 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -1,4 +1,4 @@ -//import * as WebGLDeveloperTools from 'webgl-debug'; +import * as WebGLDeveloperTools from 'webgl-debug'; import { GFXBindingLayout, GFXBindingUnit, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, GFXBufferSource, IGFXBufferInfo, IGFXIndirectBuffer } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -254,11 +254,9 @@ export class WebGLGFXDevice extends GFXDevice { }; this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); - /* if (this._webGLRC && info.debug) { this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); } - */ } catch (err) { console.error(err); return false; diff --git a/package.json b/package.json index 7bb2f28519..7e5cabdfa4 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,7 @@ "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0", - "webgl-debug": "github:cocos-creator/webgl-debug#5f9cbdd", + "webgl-debug": "github:cocos-creator/webgl-debug#4e535ed", "yargs": "^12.0.5" } } diff --git a/rollup/build-engine.ts b/rollup/build-engine.ts index 4a437caf29..7586926293 100644 --- a/rollup/build-engine.ts +++ b/rollup/build-engine.ts @@ -66,6 +66,7 @@ async function _doBundle (options: IBuildOptions) { commonjs({ namedExports: { cannon: ['CANNON', 'Shape'], + 'webgl-debug': ['makeDebugContext', 'glEnumToString'], }, }), ]; diff --git a/rollup/config.js b/rollup/config.js index 1bc59f2ff8..58c99afb04 100644 --- a/rollup/config.js +++ b/rollup/config.js @@ -60,7 +60,8 @@ export default { commonjs({ namedExports: { - 'cannon': ['CANNON'] + 'cannon': ['CANNON'], + 'webgl-debug': ['makeDebugContext', 'glEnumToString'] } }), ] From 28da22b1e5190457c2d7bd066e034a10a815b0a7 Mon Sep 17 00:00:00 2001 From: Leslie Date: Thu, 24 Jan 2019 18:03:33 +0800 Subject: [PATCH 255/267] support joints texture --- .../3d/framework/skinning-model-component.ts | 7 ++-- cocos/3d/misc/utils.ts | 34 ----------------- cocos/renderer/core/program-lib.ts | 17 ++++++++- cocos/renderer/models/model-uniforms.ts | 2 +- cocos/renderer/models/skinning-model.ts | 37 +++++++++++++++++-- 5 files changed, 54 insertions(+), 43 deletions(-) diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts index ee0737bb9c..a4f6e0bbea 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/3d/framework/skinning-model-component.ts @@ -27,7 +27,7 @@ import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { mat4 } from '../../core/vmath'; import { GFXDevice, GFXFeature } from '../../gfx/device'; -import { SkinningModel } from '../../renderer/models/skinning-model'; +import { SkinningModel, __FORCE_USE_UNIFORM_STORAGE__ } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; import { Material } from '../assets/material'; import Skeleton from '../assets/skeleton'; @@ -131,15 +131,16 @@ export default class SkinningModelComponent extends ModelComponent { } public _updateModelParams () { - super._updateModelParams(); + // Should bind skeleton before super create pso this._bindSkeleton(); + super._updateModelParams(); } protected _onMaterialModified (index: number, material: Material) { super._onMaterialModified(index, material); const device = _getGlobalDevice(); - const useJointTexture = device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false; + const useJointTexture = !__FORCE_USE_UNIFORM_STORAGE__ && device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT); this.getMaterial(0, CC_EDITOR)!.setDefines({ CC_USE_SKINNING: true, CC_USE_JOINTS_TEXTURE: useJointTexture, diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index dc34b4371c..7b2e70722c 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -1,44 +1,10 @@ import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define'; export { default as find } from '../../scene-graph/find'; -import { Texture2D } from '../../assets/texture-2d'; -import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; import { Vec3 } from '../../core/value-types'; import { AttributeBaseType, AttributeType, IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh } from '../assets/mesh'; import { IGeometry } from '../primitive/define'; -/** - * - */ -export function createJointsTexture (skinning: { joints: any[]; }) { - const jointCount = skinning.joints.length; - - // Set jointsTexture. - // A squared texture with side length N(N > 1) multiples of 2 can store - // 2 ^ (2 * N - 2) matrices. - // We support most 1024 joints. - let size = 0; - if (jointCount > 1024) { - throw new Error('To many joints(more than 1024).'); - } else if (jointCount > 256) { - size = 64; - } else if (jointCount > 64) { - size = 32; - } else if (jointCount > 16) { - size = 16; - } else if (jointCount > 4) { - size = 8; - } else { - size = 4; - } - - const texture = new Texture2D(); - texture.create(size, size, PixelFormat.RGBA32F); - texture.setFilters(Filter.NEAREST, Filter.NEAREST); - texture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); - return texture; -} - const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); export function createMesh (geometry: IGeometry) { // Collect attributes and calculate length of result vertex buffer. diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 7945b1bf94..a9e917167c 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -1,9 +1,9 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. -import { IBlockInfo, IBlockMember, IDefineInfo, IShaderInfo } from '../../3d/assets/effect-asset'; +import { IBlockInfo, IBlockMember, IDefineInfo, IShaderInfo, ISamplerInfo } from '../../3d/assets/effect-asset'; import { GFXGetTypeSize, GFXShaderType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; -import { GFXShader, GFXUniform, GFXUniformBlock } from '../../gfx/shader'; +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'; @@ -87,6 +87,8 @@ class ProgramLib { } if (def.name === 'CC_USE_SKINNING') { tmpl.blocks = tmpl.blocks.concat(skinning); + } else if (def.name === 'CC_USE_JOINTS_TEXTURE') { + tmpl.samplers = tmpl.samplers.concat(jointsTexture); } offset += cnt; def._offset = offset; @@ -151,6 +153,7 @@ class ProgramLib { const globals = convertToBlockInfo(UBOGlobal.BLOCK); const locals = convertToBlockInfo(UBOLocal.BLOCK); const skinning = convertToBlockInfo(SkinningUBO.BLOCK); +const jointsTexture = convertToSamplerInfo(SkinningUBO.JOINT_TEXTURE); function convertToUniformInfo (uniform: GFXUniform): IBlockMember { return { @@ -177,5 +180,15 @@ function convertToBlockInfo (block: GFXUniformBlock): IBlockInfo { }; } +function convertToSamplerInfo (sampler: GFXUniformSampler): ISamplerInfo { + return { + name: sampler.name, + binding: sampler.binding, + defines: [], + type: sampler.type, + count: sampler.count + }; +} + const programLib = cc.programLib = new ProgramLib(); export { programLib }; diff --git a/cocos/renderer/models/model-uniforms.ts b/cocos/renderer/models/model-uniforms.ts index 16ef5e976f..dc7fc83596 100644 --- a/cocos/renderer/models/model-uniforms.ts +++ b/cocos/renderer/models/model-uniforms.ts @@ -15,6 +15,6 @@ export class SkinningUBO { }; public static JOINT_TEXTURE: GFXUniformSampler = { - binding: 28, name: 'CCJointTexture', type: GFXType.SAMPLER2D, count: 1, + binding: 28, name: 'cc_jointsTexture', type: GFXType.SAMPLER2D, count: 1, }; } diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index e734f8f7d6..14e7e0a9a7 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -1,7 +1,6 @@ // Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. import Skeleton from '../../3d/assets/skeleton'; -import { createJointsTexture } from '../../3d/misc/utils'; import { Texture2D } from '../../assets/texture-2d'; import { mat4 } from '../../core/vmath'; import { GFXBuffer } from '../../gfx/buffer'; @@ -12,6 +11,7 @@ import { Node } from '../../scene-graph/node'; import { Model } from '../scene/model'; import { RenderScene } from '../scene/render-scene'; import { SkinningUBO } from './model-uniforms'; +import { PixelFormat, Filter, WrapMode } from '../../assets/texture-base'; const textureSizeBuffer = new Float32Array(4); @@ -34,6 +34,8 @@ function isUniformStorage (storage: JointStorage): storage is IJointUniformsStor return !('texture' in storage); } +export const __FORCE_USE_UNIFORM_STORAGE__ = false; + export class SkinningModel extends Model { private _jointStorage: JointStorage | null = null; private _skinningUBO: GFXBuffer; @@ -52,8 +54,8 @@ export class SkinningModel extends Model { public bindSkeleton (skeleton: Skeleton) { this._destroyJointStorage(); - if (this._device.hasFeature(GFXFeature.TEXTURE_FLOAT) && false) { - const jointsTexture = createJointsTexture(skeleton); + if (!__FORCE_USE_UNIFORM_STORAGE__ && this._device.hasFeature(GFXFeature.TEXTURE_FLOAT)) { + const jointsTexture = _createJointsTexture(skeleton); textureSizeBuffer[0] = jointsTexture.width; this._skinningUBO.update( textureSizeBuffer, SkinningUBO.JOINTS_TEXTURE_SIZE_OFFSET, textureSizeBuffer.byteLength); @@ -129,3 +131,32 @@ function _setJointMatrix (out: Float32Array, iMatrix: number, matrix: mat4) { out[16 * iMatrix + 14] = matrix.m14; out[16 * iMatrix + 15] = matrix.m15; } + +function _createJointsTexture (skinning: { joints: any[]; }) { + const jointCount = skinning.joints.length; + + // Set jointsTexture. + // A squared texture with side length N(N > 1) multiples of 2 can store + // 2 ^ (2 * N - 2) matrices. + // We support most 1024 joints. + let size = 0; + if (jointCount > 1024) { + throw new Error('To many joints(more than 1024).'); + } else if (jointCount > 256) { + size = 64; + } else if (jointCount > 64) { + size = 32; + } else if (jointCount > 16) { + size = 16; + } else if (jointCount > 4) { + size = 8; + } else { + size = 4; + } + + const texture = new Texture2D(); + texture.create(size, size, PixelFormat.RGBA32F); + texture.setFilters(Filter.NEAREST, Filter.NEAREST); + texture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return texture; +} \ No newline at end of file From 0094aeafea7e26c5e3678b897e687519577a4edc Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Thu, 24 Jan 2019 18:05:21 +0800 Subject: [PATCH 256/267] repaire tslint tips and add other ui component add scroll-view, scroll-bar layout component --- .../{CCWidgetManager.js => widget-manager.ts} | 431 ++++--- .../{CCLabelOutline.js => label-outline.ts} | 20 +- cocos/2d/renderer/utils/label/ttf.js | 12 +- cocos/3d/ui/assembler/{index.js => index.ts} | 4 +- cocos/3d/ui/assembler/label/index.ts | 4 +- cocos/3d/ui/assembler/label/ttf.ts | 12 +- cocos/3d/ui/assembler/sprite/bar-filled.ts | 3 +- cocos/3d/ui/assembler/sprite/radial-filled.ts | 3 +- cocos/3d/ui/assembler/sprite/simple.ts | 2 +- cocos/3d/ui/assembler/sprite/sliced.ts | 3 +- cocos/3d/ui/assembler/sprite/tiled.ts | 3 +- cocos/3d/ui/assembler/{utils.js => utils.ts} | 126 ++- cocos/3d/ui/components/button-component.ts | 10 +- cocos/3d/ui/components/canvas-component.ts | 2 +- .../components/editbox/edit-box-component.ts | 339 +++--- .../3d/ui/components/editbox/edit-box-impl.ts | 279 ++--- cocos/3d/ui/components/editbox/types.ts | 18 +- cocos/3d/ui/components/label-component.ts | 20 +- .../{CCLayout.js => layout-component.ts} | 970 ++++++++-------- .../ui/components/progress-bar-component.ts | 122 +- .../ui/components/scroll-bar-component.ts} | 161 +-- .../ui/components/scroll-view-component.ts} | 1001 +++++++++-------- cocos/3d/ui/components/slider-component.ts | 107 +- cocos/3d/ui/components/ui-render-component.ts | 16 +- .../ui/components/ui-transfrom-component.ts | 21 +- .../ui/components/view-group-component.ts} | 8 +- cocos/3d/ui/components/widget-component.ts | 373 +++--- cocos/3d/ui/index.ts | 11 +- cocos/scene-graph/node.ts | 10 +- 29 files changed, 2097 insertions(+), 1994 deletions(-) rename cocos/2d/base-ui/{CCWidgetManager.js => widget-manager.ts} (55%) rename cocos/2d/label/{CCLabelOutline.js => label-outline.ts} (87%) rename cocos/3d/ui/assembler/{index.js => index.ts} (98%) rename cocos/3d/ui/assembler/{utils.js => utils.ts} (64%) rename cocos/3d/ui/components/{CCLayout.js => layout-component.ts} (52%) rename cocos/{2d/ui/CCScrollBar.js => 3d/ui/components/scroll-bar-component.ts} (76%) rename cocos/{2d/ui/CCScrollView.js => 3d/ui/components/scroll-view-component.ts} (70%) rename cocos/{2d/ui/CCViewGroup.js => 3d/ui/components/view-group-component.ts} (94%) diff --git a/cocos/2d/base-ui/CCWidgetManager.js b/cocos/2d/base-ui/widget-manager.ts similarity index 55% rename from cocos/2d/base-ui/CCWidgetManager.js rename to cocos/2d/base-ui/widget-manager.ts index 99794d5376..7f3d37d7cc 100644 --- a/cocos/2d/base-ui/CCWidgetManager.js +++ b/cocos/2d/base-ui/widget-manager.ts @@ -2,7 +2,7 @@ Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + https://www.cocos.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, @@ -23,43 +23,48 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +// import { WidgetComponent } from '../../3d/ui/components/widget-component'; +import { array } from '../../core/utils/js'; +import { Enum, Size, Vec3 } from '../../core/value-types'; +import { Node } from '../../scene-graph/node'; +const Event = Node.EventType; -// var Event = require('../CCNode').EventType; -import { Node } from '../../scene-graph/index' +const TOP = 1 << 0; +const MID = 1 << 1; // vertical center +const BOT = 1 << 2; +const LEFT = 1 << 3; +const CENTER = 1 << 4; // horizontal center +const RIGHT = 1 << 5; +const HORIZONTAL = LEFT | CENTER | RIGHT; +const VERTICAL = TOP | MID | BOT; -var Event = Node.EventType; -var TOP = 1 << 0; -var MID = 1 << 1; // vertical center -var BOT = 1 << 2; -var LEFT = 1 << 3; -var CENTER = 1 << 4; // horizontal center -var RIGHT = 1 << 5; -var HORIZONTAL = LEFT | CENTER | RIGHT; -var VERTICAL = TOP | MID | BOT; - -var AlignMode = cc.Enum({ - ONCE: 0, - ON_WINDOW_RESIZE: 1, - ALWAYS: 2, -}); - -// returns a readonly size of the node -function getReadonlyNodeSize(parent) { - if (parent instanceof cc.Scene) { - return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect; - } - else { - return parent._contentSize; - } +enum AlignMode { + ONCE = 0, + ON_WINDOW_RESIZE = 1, + ALWAYS = 2, } -function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) { - var scaleX = widgetNode._parent._scale.x; - var scaleY = widgetNode._parent._scale.y; - var translateX = 0; - var translateY = 0; - for (var node = widgetNode._parent; ;) { - var pos = node._position; +Enum(AlignMode); + +// returns a readonly size of the node +export function getReadonlyNodeSize (parent) { + // TODO: check with Editor + // if (parent instanceof cc.Scene) { + // return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect; + // } else { + // return parent._contentSize; + // } + + return cc.visibleRect; +} + +export function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseScale) { + let scaleX = widgetNode._parent._scale.x; + let scaleY = widgetNode._parent._scale.y; + let translateX = 0; + let translateY = 0; + for (let node = widgetNode._parent; ;) { + const pos = node._position; translateX += pos.x; translateY += pos.y; node = node._parent; // loop increment @@ -70,14 +75,13 @@ function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, return; } if (node !== target) { - var sx = node._scale.x; - var sy = node._scale.y; + const sx = node._scale.x; + const sy = node._scale.y; translateX *= sx; translateY *= sy; scaleX *= sx; scaleY *= sy; - } - else { + } else { break; } } @@ -87,38 +91,40 @@ function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseTranslate.y = -translateY; } -var tInverseTranslate = cc.Vec2.ZERO; -var tInverseScale = cc.Vec2.ONE; +const tInverseTranslate = cc.Vec2.ZERO; +const tInverseScale = cc.Vec2.ONE; // align to borders by adjusting node's position and size (ignore rotation) -function align(node, widget) { - var hasTarget = widget._target; - var target; - var inverseTranslate, inverseScale; +function align (node, widget) { + const hasTarget = widget._target; + let target; + let inverseTranslate; + let inverseScale; if (hasTarget) { target = hasTarget; inverseTranslate = tInverseTranslate; inverseScale = tInverseScale; computeInverseTransForTarget(node, target, inverseTranslate, inverseScale); - } - else { + } else { target = node._parent; } - var targetSize = getReadonlyNodeSize(target); - var targetAnchor = target._anchorPoint; + const targetSize = getReadonlyNodeSize(target); + const targetAnchor = target._anchorPoint; - var isRoot = !CC_EDITOR && target instanceof cc.Scene; - var x = node._position.x, y = node._position.y; - var anchor = node._anchorPoint; + const isRoot = !CC_EDITOR && target instanceof cc.Scene; + let x = node._position.x; + let y = node._position.y; + const anchor = node._anchorPoint; if (widget._alignFlags & HORIZONTAL) { - var localLeft, localRight, targetWidth = targetSize.width; + let localLeft; + let localRight; + const targetWidth = targetSize.width; if (isRoot) { localLeft = cc.visibleRect.left.x; localRight = cc.visibleRect.right.x; - } - else { + } else { localLeft = -targetAnchor.x * targetWidth; localRight = localLeft + targetWidth; } @@ -134,7 +140,9 @@ function align(node, widget) { localRight *= inverseScale.x; } - var width, anchorX = anchor.x, scaleX = node._scale.x; + let width; + let anchorX = anchor.x; + let scaleX = node._scale.x; if (scaleX < 0) { anchorX = 1.0 - anchorX; scaleX = -scaleX; @@ -145,23 +153,21 @@ function align(node, widget) { node.width = width / scaleX; } x = localLeft + anchorX * width; - } - else { + } else { width = node.width * scaleX; if (widget.isAlignHorizontalCenter) { - var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * targetWidth; - var targetCenter = (0.5 - targetAnchor.x) * targetSize.width; + let localHorizontalCenter = widget._isAbsHorizontalCenter ? + widget._horizontalCenter : widget._horizontalCenter * targetWidth; + let targetCenter = (0.5 - targetAnchor.x) * targetSize.width; if (hasTarget) { localHorizontalCenter *= inverseScale.x; targetCenter += inverseTranslate.x; targetCenter *= inverseScale.x; } x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter; - } - else if (widget.isAlignLeft) { + } else if (widget.isAlignLeft) { x = localLeft + anchorX * width; - } - else { + } else { x = localRight + (anchorX - 1) * width; } } @@ -169,12 +175,13 @@ function align(node, widget) { if (widget._alignFlags & VERTICAL) { - var localTop, localBottom, targetHeight = targetSize.height; + let localTop; + let localBottom; + const targetHeight = targetSize.height; if (isRoot) { localBottom = cc.visibleRect.bottom.y; localTop = cc.visibleRect.top.y; - } - else { + } else { localBottom = -targetAnchor.y * targetHeight; localTop = localBottom + targetHeight; } @@ -191,7 +198,9 @@ function align(node, widget) { localTop *= inverseScale.y; } - var height, anchorY = anchor.y, scaleY = node._scale.y; + let height; + let anchorY = anchor.y; + let scaleY = node._scale.y; if (scaleY < 0) { anchorY = 1.0 - anchorY; scaleY = -scaleY; @@ -202,23 +211,21 @@ function align(node, widget) { node.height = height / scaleY; } y = localBottom + anchorY * height; - } - else { + } else { height = node.height * scaleY; if (widget.isAlignVerticalCenter) { - var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * targetHeight; - var targetMiddle = (0.5 - targetAnchor.y) * targetSize.height; + let localVerticalCenter = widget._isAbsVerticalCenter ? + widget._verticalCenter : widget._verticalCenter * targetHeight; + let targetMiddle = (0.5 - targetAnchor.y) * targetSize.height; if (hasTarget) { localVerticalCenter *= inverseScale.y; targetMiddle += inverseTranslate.y; targetMiddle *= inverseScale.y; } y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter; - } - else if (widget.isAlignBottom) { + } else if (widget.isAlignBottom) { y = localBottom + anchorY * height; - } - else { + } else { y = localTop + (anchorY - 1) * height; } } @@ -227,149 +234,141 @@ function align(node, widget) { node.setPosition(x, y); } -function visitNode(node) { - var widget = node._widget; +function visitNode (node: Node) { + const widget = node.uiWidgetComp; if (widget) { if (CC_DEV) { - var target = widget._target; - if (target) { - var isParent = node !== target && node.isChildOf(target); - if (!isParent) { - cc.errorID(6500); - widget._target = null; - } - } + // widget._validateTargetInDEV(); } align(node, widget); - if ((!CC_EDITOR || animationState.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) { + if ((!CC_EDITOR /*|| animationState.animatedSinceLastFrame*/) && widget.alignMode !== AlignMode.ALWAYS) { widget.enabled = false; - } - else { + } else { activeWidgets.push(widget); } } - var children = node._children; - for (var i = 0; i < children.length; i++) { - var child = children[i]; - if (child._active) { + const children = node.children; + for (const child of children) { + if (child.active) { visitNode(child); } } } if (CC_EDITOR) { - var animationState = { + const animationState = { previewing: false, time: 0, animatedSinceLastFrame: false, }; } -function refreshScene() { +function refreshScene () { // check animation editor - if (CC_EDITOR && !Editor.isBuilder) { - var AnimUtils = Editor.require('scene://utils/animation'); - var EditMode = Editor.require('scene://edit-mode'); - if (AnimUtils && EditMode) { - var nowPreviewing = (EditMode.curMode().name === 'animation' && !!AnimUtils.Cache.animation); - if (nowPreviewing !== animationState.previewing) { - animationState.previewing = nowPreviewing; - if (nowPreviewing) { - animationState.animatedSinceLastFrame = true; - let component = cc.engine.getInstanceById(AnimUtils.Cache.component); - if (component) { - let animation = component.getAnimationState(AnimUtils.Cache.animation); - animationState.time = animation.time; - } - } - else { - animationState.animatedSinceLastFrame = false; - } - } - else if (nowPreviewing) { - let component = cc.engine.getInstanceById(AnimUtils.Cache.component); - if (component) { - let animation = component.getAnimationState(AnimUtils.Cache.animation); - if (animationState.time !== animation.time) { - animationState.animatedSinceLastFrame = true; - animationState.time = AnimUtils.Cache.animation.time; - } - } - } - } - } + // if (CC_EDITOR && !Editor.isBuilder) { + // const AnimUtils = Editor.require('scene://utils/animation'); + // const EditMode = Editor.require('scene://edit-mode'); + // if (AnimUtils && EditMode) { + // const nowPreviewing = (EditMode.curMode().name === 'animation' && !!AnimUtils.Cache.animation); + // if (nowPreviewing !== animationState.previewing) { + // animationState.previewing = nowPreviewing; + // if (nowPreviewing) { + // animationState.animatedSinceLastFrame = true; + // const component = cc.engine.getInstanceById(AnimUtils.Cache.component); + // if (component) { + // const animation = component.getAnimationState(AnimUtils.Cache.animation); + // animationState.time = animation.time; + // } + // } else { + // animationState.animatedSinceLastFrame = false; + // } + // } else if (nowPreviewing) { + // const component = cc.engine.getInstanceById(AnimUtils.Cache.component); + // if (component) { + // const animation = component.getAnimationState(AnimUtils.Cache.animation); + // if (animationState.time !== animation.time) { + // animationState.animatedSinceLastFrame = true; + // animationState.time = AnimUtils.Cache.animation.time; + // } + // } + // } + // } + // } - var scene = cc.director.getScene(); + const scene = cc.director.getScene(); if (scene) { widgetManager.isAligning = true; if (widgetManager._nodesOrderDirty) { activeWidgets.length = 0; visitNode(scene); widgetManager._nodesOrderDirty = false; - } - else { - var i, widget, iterator = widgetManager._activeWidgetsIterator; - var AnimUtils; - if (CC_EDITOR && - (AnimUtils = Editor.require('scene://utils/animation')) && - AnimUtils.Cache.animation) { - var editingNode = cc.engine.getInstanceById(AnimUtils.Cache.rNode); - if (editingNode) { - for (i = activeWidgets.length - 1; i >= 0; i--) { - widget = activeWidgets[i]; - var node = widget.node; - if (widget.alignMode !== AlignMode.ALWAYS && - animationState.animatedSinceLastFrame && - node.isChildOf(editingNode) - ) { - // widget contains in activeWidgets should aligned at least once - widget.enabled = false; - } - else { - align(node, widget); - } - } - } - } - else { - // loop reversely will not help to prevent out of sync - // because user may remove more than one item during a step. - for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) { - widget = activeWidgets[iterator.i]; - align(widget.node, widget); - } - } + } else { + // // let i; + // let widget; + // const iterator = widgetManager._activeWidgetsIterator; + // // TODO: animation + // let AnimUtils; + // if (CC_EDITOR && + // (AnimUtils = Editor.require('scene://utils/animation')) && + // AnimUtils.Cache.animation) { + // const editingNode = cc.engine.getInstanceById(AnimUtils.Cache.rNode); + // if (editingNode) { + // for (i = activeWidgets.length - 1; i >= 0; i--) { + // widget = activeWidgets[i]; + // const node = widget.node; + // if (widget.alignMode !== AlignMode.ALWAYS && + // animationState.animatedSinceLastFrame && + // node.isChildOf(editingNode) + // ) { + // // widget contains in activeWidgets should aligned at least once + // widget.enabled = false; + // } else { + // align(node, widget); + // } + // } + // } + // } else { + // // loop reversely will not help to prevent out of sync + // // because user may remove more than one item during a step. + // for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) { + // widget = activeWidgets[iterator.i]; + // align(widget.node, widget); + // } + // } } widgetManager.isAligning = false; } // check animation editor if (CC_EDITOR) { - animationState.animatedSinceLastFrame = false; + // animationState.animatedSinceLastFrame = false; } } -var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (oldPos) { +function adjustWidgetToAllowMovingInEditor (oldPos: Vec3) { + if (!CC_EDITOR) { + return; + } + if (widgetManager.isAligning) { return; } - var newPos = this.node.position; - var delta = newPos.sub(oldPos); + const newPos = this.node.position; + const delta = newPos.sub(oldPos); - var target = this.node._parent; - var inverseScale = cc.Vec2.ONE; + let target = this.node._parent; + const inverseScale = cc.Vec2.ONE; if (this._target) { target = this._target; computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale); } - var targetSize = getReadonlyNodeSize(target); - var deltaInPercent; + const targetSize = getReadonlyNodeSize(target); + let deltaInPercent; if (targetSize.width !== 0 && targetSize.height !== 0) { deltaInPercent = new cc.Vec2(delta.x / targetSize.width, delta.y / targetSize.height); - } - else { + } else { deltaInPercent = cc.Vec2.ZERO; } @@ -391,32 +390,35 @@ var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (oldPos) { if (this.isAlignVerticalCenter) { this.verticalCenter += (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y; } -}; +} + +function adjustWidgetToAllowResizingInEditor (oldSize: Size) { + if (!CC_EDITOR) { + return; + } -var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) { if (widgetManager.isAligning) { return; } - var newSize = this.node.getContentSize(); - var delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height); + const newSize = this.node.getContentSize(); + const delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height); - var target = this.node._parent; - var inverseScale = cc.Vec2.ONE; + let target = this.node._parent; + const inverseScale = cc.Vec2.ONE; if (this._target) { target = this._target; computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale); } - var targetSize = getReadonlyNodeSize(target); - var deltaInPercent; + const targetSize = getReadonlyNodeSize(target); + let deltaInPercent; if (targetSize.width !== 0 && targetSize.height !== 0) { deltaInPercent = new cc.Vec2(delta.x / targetSize.width, delta.y / targetSize.height); - } - else { + } else { deltaInPercent = cc.Vec2.ZERO; } - var anchor = this.node._anchorPoint; + const anchor = this.node._anchorPoint; if (this.isAlignTop) { this.top -= (this.isAbsoluteTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y; @@ -430,52 +432,51 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) { if (this.isAlignRight) { this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x; } -}; +} -var activeWidgets = []; +const activeWidgets = []; // updateAlignment from scene to node recursively -function updateAlignment(node) { - var parent = node._parent; - if (cc.Node.isNode(parent)) { +function updateAlignment (node: Node) { + const parent = node.parent; + if (parent && cc.Node.isNode(parent)) { updateAlignment(parent); } - var widget = node._widget || - node.getComponent(cc.Widget); // node._widget will be null when widget is disabled - if (widget) { + + // node._widget will be null when widget is disabled + const widget = node.uiWidgetComp || node.getComponent(cc.WidgetComponent); + if (widget && parent) { align(node, widget); } } -let WidgetManager = cc._widgetManager = { +export const widgetManager = cc._widgetManager = { _AlignFlags: { - TOP: TOP, - MID: MID, // vertical center - BOT: BOT, - LEFT: LEFT, - CENTER: CENTER, // horizontal center - RIGHT: RIGHT + TOP, + MID, // vertical center + BOT, + LEFT, + CENTER, // horizontal center + RIGHT, }, isAligning: false, _nodesOrderDirty: false, - _activeWidgetsIterator: new cc.js.array.MutableForwardIterator(activeWidgets), + _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets), - init: function (director) { + init (director) { director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene); if (CC_EDITOR && cc.engine) { cc.engine.on('design-resolution-changed', this.onResized.bind(this)); - } - else { + } else { if (cc.sys.isMobile) { window.addEventListener('resize', this.onResized.bind(this)); - } - else { + } else { cc.view.on('canvas-resize', this.onResized, this); } } }, - add: function (widget) { + add (widget) { widget.node._widget = widget; this._nodesOrderDirty = true; if (CC_EDITOR && !cc.engine.isPlaying) { @@ -483,7 +484,7 @@ let WidgetManager = cc._widgetManager = { widget.node.on(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); } }, - remove: function (widget) { + remove (widget) { widget.node._widget = null; this._activeWidgetsIterator.remove(widget); if (CC_EDITOR && !cc.engine.isPlaying) { @@ -491,33 +492,25 @@ let WidgetManager = cc._widgetManager = { widget.node.off(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget); } }, - onResized() { - var scene = cc.director.getScene(); + onResized () { + const scene = cc.director.getScene(); if (scene) { this.refreshWidgetOnResized(scene); } }, - refreshWidgetOnResized(node) { - var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); + refreshWidgetOnResized (node) { + const widget = cc.Node.isNode(node) && node.getComponent(cc.Widget); if (widget) { if (widget.alignMode === AlignMode.ON_WINDOW_RESIZE) { widget.enabled = true; } } - var children = node._children; - for (var i = 0; i < children.length; i++) { - var child = children[i]; + const children = node._children; + for (const child of children) { this.refreshWidgetOnResized(child); } }, - updateAlignment: updateAlignment, - AlignMode: AlignMode, + updateAlignment, + AlignMode, }; - -export default WidgetManager; - -if (CC_EDITOR) { - module.exports._computeInverseTransForTarget = computeInverseTransForTarget; - module.exports._getReadonlyNodeSize = getReadonlyNodeSize; -} diff --git a/cocos/2d/label/CCLabelOutline.js b/cocos/2d/label/label-outline.ts similarity index 87% rename from cocos/2d/label/CCLabelOutline.js rename to cocos/2d/label/label-outline.ts index dea564fe3c..578adefa0a 100644 --- a/cocos/2d/label/CCLabelOutline.js +++ b/cocos/2d/label/label-outline.ts @@ -37,11 +37,11 @@ * node.parent = this.node; */ -import Component from '../../components/component'; +import { Component } from '../../components/component'; -export default class LabelOutline extends Component { - _color = cc.color(255, 255, 255, 255); - _width = 1; +export class LabelOutline extends Component { + private _color = cc.color(255, 255, 255, 255); + private _width = 1; /** * !#en Change the outline color @@ -51,10 +51,10 @@ export default class LabelOutline extends Component { * @example * outline.color = new cc.Color(0.5, 0.3, 0.7, 1.0);; */ - get color() { + get color () { return this._color; } - set color(value) { + set color (value) { this._color = cc.color(value); this._updateRenderData(); } @@ -67,17 +67,17 @@ export default class LabelOutline extends Component { * @example * outline.width = 3; */ - get width() { + get width () { return this._width; } - set width(value) { + set width (value) { this._width = value; this._updateRenderData(); } - _updateRenderData() { - let label = this.node.getComponent(cc.Label); + private _updateRenderData () { + const label = this.node.getComponent(cc.Label); if (label) { label._updateRenderData(true); } diff --git a/cocos/2d/renderer/utils/label/ttf.js b/cocos/2d/renderer/utils/label/ttf.js index 787a04525e..2adb5d0709 100644 --- a/cocos/2d/renderer/utils/label/ttf.js +++ b/cocos/2d/renderer/utils/label/ttf.js @@ -23,17 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -// const macro = require('../../../platform/CCMacro'); -// const textUtils = require('../../../utils/text-utils'); - -// const Component = require('../../../components/component'); -// const Label = require('../../../components/CCLabel'); -// const LabelOutline = require('../../../components/CCLabelOutline'); import macro from '../../../../core/platform/CCMacro'; import * as textUtils from '../../../../core/utils/text-utils'; -import Component from '../../../../components/component'; -import LabelComponent from '../../../../3d/ui/components/label-component'; -import LabelOutline from '../../../../2d/label/CCLabelOutline'; +import { Component } from '../../../../components/component'; +import { LabelComponent } from '../../../../3d/ui/components/label-component'; +import { LabelOutline } from '../../../label/label-outline'; const Overflow = LabelComponent.Overflow; const WHITE = cc.Color.WHITE; diff --git a/cocos/3d/ui/assembler/index.js b/cocos/3d/ui/assembler/index.ts similarity index 98% rename from cocos/3d/ui/assembler/index.js rename to cocos/3d/ui/assembler/index.ts index 27e68b6314..3f8c710bb4 100644 --- a/cocos/3d/ui/assembler/index.js +++ b/cocos/3d/ui/assembler/index.ts @@ -24,8 +24,8 @@ ****************************************************************************/ // require('./sprite'); -import './sprite/index'; // require('./mask-assembler'); // require('./graphics'); -// import './label/index'; +import './label/index'; +import './sprite/index'; // require('./motion-streak'); diff --git a/cocos/3d/ui/assembler/label/index.ts b/cocos/3d/ui/assembler/label/index.ts index 8ffe9b4a54..9e79489c73 100644 --- a/cocos/3d/ui/assembler/label/index.ts +++ b/cocos/3d/ui/assembler/label/index.ts @@ -31,8 +31,8 @@ import { ttf } from './ttf'; // import bmfontAssembler from './bmfont'; const labelAssembler = { - getAssembler(comp) { - let assembler = ttf; + getAssembler (comp) { + const assembler = ttf; if (comp.font instanceof cc.BitmapFont) { // assembler = bmfontAssembler; diff --git a/cocos/3d/ui/assembler/label/ttf.ts b/cocos/3d/ui/assembler/label/ttf.ts index b8f9ac8dfa..edd7a7a8a4 100644 --- a/cocos/3d/ui/assembler/label/ttf.ts +++ b/cocos/3d/ui/assembler/label/ttf.ts @@ -23,13 +23,13 @@ THE SOFTWARE. ****************************************************************************/ -import * as js from '../../../../core/utils/js'; import ttfUtls from '../../../../2d/renderer/utils/label/ttf'; -import { fillMeshVertices3D } from '../utils'; -import { IAssembler} from '../assembler'; -import { LabelComponent } from '../../components/label-component'; +import * as js from '../../../../core/utils/js'; import { RenderData } from '../../../../renderer/ui/renderData'; -import { MeshBuffer } from '../../mesh-buffer'; +import { UI } from '../../../../renderer/ui/ui'; +import { LabelComponent } from '../../components/label-component'; +import { IAssembler} from '../assembler'; +import { fillMeshVertices3D } from '../utils'; const WHITE = cc.color(255, 255, 255, 255); @@ -55,7 +55,7 @@ export const ttf: IAssembler = { return renderData as RenderData; }, - fillBuffers (comp: LabelComponent, /*renderer*/buffer: MeshBuffer) { + fillBuffers (comp: LabelComponent, /*renderer*/buffer: UI) { fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp.renderData, WHITE); }, diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/3d/ui/assembler/sprite/bar-filled.ts index 9a0e124cbc..2df303fa4c 100644 --- a/cocos/3d/ui/assembler/sprite/bar-filled.ts +++ b/cocos/3d/ui/assembler/sprite/bar-filled.ts @@ -291,7 +291,8 @@ export const barFilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; - commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; renderer.addToQueue(commitBuffer); }, }; diff --git a/cocos/3d/ui/assembler/sprite/radial-filled.ts b/cocos/3d/ui/assembler/sprite/radial-filled.ts index 805d232a23..0dadfd690d 100644 --- a/cocos/3d/ui/assembler/sprite/radial-filled.ts +++ b/cocos/3d/ui/assembler/sprite/radial-filled.ts @@ -380,7 +380,8 @@ export const radialFilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = comp.material!; - commitBuffer.camera = renderer.getScreen(comp.viewID)!.camera!; + commitBuffer.texture = comp.spriteFrame!; + commitBuffer.camera = renderer.getScreen(comp.visibility)!.camera!; renderer.addToQueue(commitBuffer); }, }; diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts index b842fa6f9f..b2d583fb56 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -141,7 +141,7 @@ export const simple: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.texture = sprite.spriteFrame!; - commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/3d/ui/assembler/sprite/sliced.ts index f6a2cd6420..d700e79790 100644 --- a/cocos/3d/ui/assembler/sprite/sliced.ts +++ b/cocos/3d/ui/assembler/sprite/sliced.ts @@ -171,7 +171,8 @@ export const sliced: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; - commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/3d/ui/assembler/sprite/tiled.ts b/cocos/3d/ui/assembler/sprite/tiled.ts index 2cc31b7948..bc686f44bc 100644 --- a/cocos/3d/ui/assembler/sprite/tiled.ts +++ b/cocos/3d/ui/assembler/sprite/tiled.ts @@ -240,7 +240,8 @@ export const tilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; - commitBuffer.camera = renderer.getScreen(sprite.viewID)!.camera!; + commitBuffer.texture = sprite.spriteFrame!; + commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/3d/ui/assembler/utils.js b/cocos/3d/ui/assembler/utils.ts similarity index 64% rename from cocos/3d/ui/assembler/utils.js rename to cocos/3d/ui/assembler/utils.ts index 05ab64cd8a..ba3d32d004 100644 --- a/cocos/3d/ui/assembler/utils.js +++ b/cocos/3d/ui/assembler/utils.ts @@ -1,27 +1,31 @@ -import { vec3, mat4 } from '../../../core/vmath/index'; +import { mat4, vec3 } from '../../../core/vmath/index'; -let vec3_temp = vec3.create(); -let _worldMatrix = mat4.create(); +const vec3_temp = vec3.create(); +const _worldMatrix = mat4.create(); -export function fillVertices(node, buffer, renderData, color) { - let data = renderData._data, - vertexOffset = buffer.byteOffset >> 2; +export function fillVertices (node, buffer, renderData, color) { + const data = renderData._data; + let vertexOffset = buffer.byteOffset >> 2; - let vertexCount = renderData.vertexCount; + const vertexCount = renderData.vertexCount; buffer.request(vertexCount, renderData.indiceCount); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - uintbuf = buffer._uintVData; + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData; // let matrix = node._worldMatrix; node.getWorldMatrix(_worldMatrix); - let matrix = _worldMatrix; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; + const matrix = _worldMatrix; + const a = matrix.m00; + const b = matrix.m01; + const c = matrix.m04; + const d = matrix.m05; + const tx = matrix.m12; + const ty = matrix.m13; for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; + const vert = data[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; @@ -34,28 +38,32 @@ export function fillVertices(node, buffer, renderData, color) { } } -export function fillMeshVertices(node, buffer, renderData, color) { - let data = renderData._data, - vertexOffset = buffer.byteOffset >> 2; +export function fillMeshVertices (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; - let vertexCount = renderData.vertexCount, - indiceOffset = buffer.indiceOffset, - vertexId = buffer.vertexOffset; + const vertexCount = renderData.vertexCount; + let indiceOffset = buffer.indiceOffset; + const vertexId = buffer.vertexOffset; buffer.request(vertexCount, renderData.indiceCount); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - uintbuf = buffer._uintVData, - ibuf = buffer._iData; + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData, + const ibuf = buffer._iData; // let matrix = node._worldMatrix; node.getWorldMatrix(_worldMatrix); - let matrix = _worldMatrix; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, - tx = matrix.m12, ty = matrix.m13; + const matrix = _worldMatrix; + const a = matrix.m00; + const b = matrix.m01; + const c = matrix.m04; + const d = matrix.m05; + const tx = matrix.m12; + const ty = matrix.m13; for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; + const vert = datas[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset++] = vert.u; @@ -69,7 +77,7 @@ export function fillMeshVertices(node, buffer, renderData, color) { // fill indice data for (let i = 0, count = vertexCount / 4; i < count; i++) { - let start = vertexId + i * 4; + const start = vertexId + i * 4; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 2; @@ -79,22 +87,22 @@ export function fillMeshVertices(node, buffer, renderData, color) { } } -export function fillVertices3D(node, buffer, renderData, color) { - let data = renderData._data, - vertexOffset = buffer.byteOffset >> 2; +export function fillVertices3D (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; - let vertexCount = renderData.vertexCount; + const vertexCount = renderData.vertexCount; buffer.request(vertexCount, renderData.indiceCount); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - uintbuf = buffer._uintVData; + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData; // let matrix = node._worldMatrix; node.getWorldMatrix(_worldMatrix); for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; + const vert = datas[i]; vec3.set(vec3_temp, vert.x, vert.y, 0); vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); vbuf[vertexOffset++] = vec3_temp.x; @@ -110,26 +118,26 @@ export function fillVertices3D(node, buffer, renderData, color) { } } -export function fillMeshVertices3D(node, buffer, renderData, color) { - let data = renderData._data, - vertexOffset = buffer.byteOffset >> 2; +export function fillMeshVertices3D (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; - let vertexCount = renderData.vertexCount, - indiceOffset = buffer.indiceOffset, - vertexId = buffer.vertexOffset; + const vertexCount = renderData.vertexCount; + let indiceOffset = buffer.indiceOffset; + const vertexId = buffer.vertexOffset; buffer.request(vertexCount, renderData.indiceCount); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - uintbuf = buffer._uintVData, - ibuf = buffer._iData; + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData, + const ibuf = buffer.iData; // let matrix = node._worldMatrix; node.getWorldMatrix(_worldMatrix); for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; + const vert = datas[i]; vec3.set(vec3_temp, vert.x, vert.y, 0); vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix); vbuf[vertexOffset++] = vec3_temp.x; @@ -146,7 +154,7 @@ export function fillMeshVertices3D(node, buffer, renderData, color) { // fill indice data for (let i = 0, count = vertexCount / 4; i < count; i++) { - let start = vertexId + i * 4; + const start = vertexId + i * 4; ibuf[indiceOffset++] = start; ibuf[indiceOffset++] = start + 1; ibuf[indiceOffset++] = start + 2; @@ -156,19 +164,19 @@ export function fillMeshVertices3D(node, buffer, renderData, color) { } } -export function fillVerticesWithoutCalc(node, buffer, renderData, color) { - let data = renderData._data, - vertexOffset = buffer.byteOffset >> 2; +export function fillVerticesWithoutCalc (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; - let vertexCount = renderData.vertexCount; + const vertexCount = renderData.vertexCount; buffer.request(vertexCount, renderData.indiceCount); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - uintbuf = buffer._uintVData; + const vbuf = buffer.vData; + // uintbuf = buffer._uintVData; for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; + const vert = datas[i]; vbuf[vertexOffset++] = vert.x; vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = vert.u; @@ -181,19 +189,19 @@ export function fillVerticesWithoutCalc(node, buffer, renderData, color) { } } -export function fillVerticesWithoutCalc3D(node, buffer, renderData, color) { - let data = renderData._data, - vertexOffset = buffer.byteOffset >> 2; +export function fillVerticesWithoutCalc3D (node, buffer, renderData, color) { + const datas = renderData.datas; + let vertexOffset = buffer.byteOffset >> 2; - let vertexCount = renderData.vertexCount; + const vertexCount = renderData.vertexCount; buffer.request(vertexCount, renderData.indiceCount); // buffer data may be realloc, need get reference after request. - let vbuf = buffer._vData, - uintbuf = buffer._uintVData; + const vbuf = buffer.vData; + // const uintbuf = buffer._uintVData; for (let i = 0; i < vertexCount; i++) { - let vert = data[i]; + const vert = datas[i]; vbuf[vertexOffset++] = vert.x; vbuf[vertexOffset++] = vert.y; vbuf[vertexOffset++] = vert.z; diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts index a57b618c79..95bd18b3e7 100644 --- a/cocos/3d/ui/components/button-component.ts +++ b/cocos/3d/ui/components/button-component.ts @@ -29,12 +29,12 @@ import ComponentEventHandler from '../../../components/CCComponentEventHandler'; import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import Event from '../../../core/event/event'; +import { EventTouch } from '../../../core/platform/event-manager'; import { lerp } from '../../../core/utils/misc'; -import { Color, Vec3, Enum } from '../../../core/value-types/index'; +import { Color, Enum, Vec3 } from '../../../core/value-types/index'; import * as math from '../../../core/vmath/index'; import { Node } from '../../../scene-graph'; import { SpriteComponent } from './sprite-component'; -import { EventTouch } from '../../../core/platform/event-manager'; /** * !#en Enum for transition type. @@ -68,7 +68,9 @@ enum Transition { * @property {Number} SCALE */ SCALE = 3, -}; +} + +Enum(Transition); /** * !#en @@ -193,7 +195,7 @@ export class ButtonComponent extends Component { return this._transition; } - set transition(value: Transition) { + set transition (value: Transition) { if (this._transition === value) { return; } diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 972fc29372..5fe53c1206 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -204,7 +204,7 @@ export class CanvasComponent extends Component { color: cc.color(255, 0, 0, 1), clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, rect: new Rect(0, 0, 1, 1), - depth: 1 + depth: 1, } as ICameraInfo; this._camera = this._getRenderScene().createCamera(this._cameraInfo); cc.director.root.ui.addScreen(this); diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts index b3538ae13f..fc6f9a32f8 100644 --- a/cocos/3d/ui/components/editbox/edit-box-component.ts +++ b/cocos/3d/ui/components/editbox/edit-box-component.ts @@ -24,34 +24,31 @@ THE SOFTWARE. ****************************************************************************/ -import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../../core/data/class-decorator'; -import { Component } from '../../../../components/component'; -import Color from '../../../../core/value-types/color'; -import macro from '../../../../core/platform/CCMacro'; -import { EditBoxImpl} from './edit-box-impl'; -import { LabelComponent } from '../label-component'; -// import { InputMode, InputFlag, KeyboardReturnType } from './types'; -import * as Types from './types'; import { SpriteFrame } from '../../../../assets/CCSpriteFrame'; import ComponentEventHandler from '../../../../components/CCComponentEventHandler'; +import { Component } from '../../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../../core/data/class-decorator'; +import macro from '../../../../core/platform/CCMacro'; +import Color from '../../../../core/value-types/color'; +import { LabelComponent } from '../label-component'; import { SpriteComponent } from '../sprite-component'; import { UIRenderComponent } from '../ui-render-component'; import { UITransformComponent } from '../ui-transfrom-component'; -const InputMode = Types.InputMode; -const InputFlag = Types.InputFlag; -const KeyboardReturnType = Types.KeyboardReturnType; +import { EditBoxImpl} from './edit-box-impl'; +import { InputFlag, InputMode, KeyboardReturnType } from './types'; const LEFT_PADDING = 2; -function capitalize(string) { - return string.replace(/(?:^|\s)\S/g, function (a) { return a.toUpperCase(); }); +function capitalize (string) { + return string.replace(/(?:^|\s)\S/g, (a) => { + return a.toUpperCase(); + }); } -function capitalizeFirstLetter(string) { +function capitalizeFirstLetter (string) { return string.charAt(0).toUpperCase() + string.slice(1); } - /** * !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. * !#zh EditBox 组件,用于获取用户的输入文本。 @@ -64,72 +61,6 @@ function capitalizeFirstLetter(string) { @menu('UI/EditBox') @executeInEditMode export class EditBoxComponent extends Component { - @property - _useOriginalSize = true; - @property - _string = ''; - @property - _tabIndex = 0; - @property - _backgroundImage: SpriteFrame | null = null; - @property - _returnType = KeyboardReturnType.DEFAULT; - @property - _inputFlag = InputFlag.DEFAULT; - @property - _inputMode = InputMode.SINGLE_LINE; - @property - _fontSize = 20; - @property - _lineHeight = 40; - @property - _maxLength = 20; - @property - _fontColor: Color = Color.WHITE; - @property - _placeholder = 'Enter text here...'; - @property - _placeholderFontSize = 20; - @property - _placeholderFontColor: Color = Color.GRAY; - @property - _stayOnTop = false; - /** - * !#en The event handler to be called when EditBox began to edit text. - * !#zh 开始编辑文本输入框触发的事件回调。 - * @property {Component.EventHandler[]} editingDidBegan - */ - @property - editingDidBegan: ComponentEventHandler[] = []; - - /** - * !#en The event handler to be called when EditBox text changes. - * !#zh 编辑文本输入框时触发的事件回调。 - * @property {Component.EventHandler[]} textChanged - */ - @property - textChanged: ComponentEventHandler[] = []; - - /** - * !#en The event handler to be called when EditBox edit ends. - * !#zh 结束编辑文本输入框时触发的事件回调。 - * @property {Component.EventHandler[]} editingDidEnded - */ - @property - editingDidEnded: ComponentEventHandler[] = []; - - /** - * !#en The event handler to be called when return key is pressed. Windows is not supported. - * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 - * @property {Component.EventHandler[]} editingReturn - */ - @property - editingReturn: ComponentEventHandler[] = []; - - _impl: EditBoxImpl | null = null; - _textLabel: LabelComponent | null = null; - _placeholderLabel: LabelComponent | null = null; - _background: SpriteComponent | null = null; /** * !#en Input string of EditBox. @@ -137,11 +68,11 @@ export class EditBoxComponent extends Component { * @property {String} string */ @property - get string() { + get string () { return this._string; } - set string(value) { + set string (value) { if (this._maxLength >= 0 && value.length >= this._maxLength) { value = value.slice(0, this._maxLength); } @@ -158,13 +89,13 @@ export class EditBoxComponent extends Component { * @property {SpriteFrame} backgroundImage */ @property({ - type: SpriteFrame + type: SpriteFrame, }) - get backgroundImage() { + get backgroundImage () { return this._backgroundImage; } - set backgroundImage(value: SpriteFrame | null) { + set backgroundImage (value: SpriteFrame | null) { if (this._backgroundImage === value) { return; } @@ -184,20 +115,19 @@ export class EditBoxComponent extends Component { * @default KeyboardReturnType.DEFAULT */ @property({ - type: KeyboardReturnType + type: KeyboardReturnType, }) - get returnType() { + get returnType () { return this._returnType; } - set returnType(value) { + set returnType (value: KeyboardReturnType) { this._returnType = value; if (this._impl) { this._impl.returnType = this._returnType; } } - /** * !#en Set the input flags that are to be applied to the EditBox. * !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 @@ -205,13 +135,13 @@ export class EditBoxComponent extends Component { * @default InputFlag.DEFAULT */ @property({ - type: InputFlag + type: InputFlag, }) - get inputFlag() { + get inputFlag () { return this._inputFlag; } - set inputFlag(value) { + set inputFlag (value: InputFlag) { this._inputFlag = value; if (this._impl) { this._impl.setInputFlag(this._inputFlag); @@ -228,13 +158,13 @@ export class EditBoxComponent extends Component { * @default InputMode.ANY */ @property({ - type: InputMode + type: InputMode, }) - get inputMode() { + get inputMode () { return this._inputMode; } - set inputMode(value) { + set inputMode (value: InputMode) { this._inputMode = value; if (this._impl) { this._impl.setInputMode(this._inputMode); @@ -247,11 +177,11 @@ export class EditBoxComponent extends Component { * @property {Number} fontSize */ @property - get fontSize() { + get fontSize () { return this._fontSize; } - set fontSize(value) { + set fontSize (value) { if (this._fontSize === value) { return; } @@ -265,18 +195,17 @@ export class EditBoxComponent extends Component { } } - /** * !#en Change the lineHeight of displayed text. * !#zh 输入框文本的行高。 * @property {Number} lineHeight */ @property - get lineHeight() { + get lineHeight () { return this._lineHeight; } - set lineHeight(value) { + set lineHeight (value) { if (this._lineHeight === value) { return; } @@ -287,28 +216,27 @@ export class EditBoxComponent extends Component { } } - /** * !#en Font color of the input text. * !#zh 输入框文本的颜色。 * @property {Color} fontColor */ @property({ - type: Color + type: Color, }) - get fontColor() { + get fontColor () { return this._fontColor; } - set fontColor(value: Color) { + set fontColor (value: Color) { if (this._fontColor === value) { - return + return; } this._fontColor = value; if (this._textLabel) { // this._textLabel.node.opacity = this._fontColor.a; - let renderComp = this._textLabel.node.getComponent(UIRenderComponent); + const renderComp = this._textLabel.node.getComponent(UIRenderComponent); if (renderComp) { renderComp.color = this._fontColor; } @@ -324,11 +252,11 @@ export class EditBoxComponent extends Component { * @property {String} placeholder */ @property - get placeholder() { + get placeholder () { return this._placeholder; } - set placeholder(value) { + set placeholder (value) { if (this._placeholder === value) { return; } @@ -348,11 +276,11 @@ export class EditBoxComponent extends Component { * @property {Number} placeholderFontSize */ @property - get placeholderFontSize() { + get placeholderFontSize () { return this._placeholderFontSize; } - set placeholderFontSize(value) { + set placeholderFontSize (value) { if (this._placeholderFontSize === value) { return; } @@ -369,21 +297,21 @@ export class EditBoxComponent extends Component { * @property {Color} placeholderFontColor */ @property - get placeholderFontColor() { + get placeholderFontColor () { return this._placeholderFontColor; } - set placeholderFontColor(value: Color) { + set placeholderFontColor (value: Color) { if (this._placeholderFontColor === value) { return; } this._placeholderFontColor = value; if (this._placeholderLabel) { - let comp = this._placeholderLabel.node.getComponent(UIRenderComponent); + const comp = this._placeholderLabel.node.getComponent(UIRenderComponent); if (comp) { - comp.color = this._placeholderFontColor - }; + comp.color = this._placeholderFontColor; + } // this._placeholderLabel.node.opacity = this._placeholderFontColor.a; } } @@ -398,12 +326,12 @@ export class EditBoxComponent extends Component { * @property {Number} maxLength */ @property - get maxLength() { + get maxLength () { return this._maxLength; } - set maxLength(value) { + set maxLength (value) { if (this._maxLength === value) { - return + return; } this._maxLength = value; @@ -419,11 +347,11 @@ export class EditBoxComponent extends Component { * @property {Boolean} stayOnTop */ @property - get stayOnTop() { + get stayOnTop () { return this._stayOnTop; } - set stayOnTop(value) { + set stayOnTop (value) { this._stayOnTop = value; if (this._impl) { this._updateStayOnTop(); @@ -436,40 +364,106 @@ export class EditBoxComponent extends Component { * @property {Number} tabIndex */ @property - get tabIndex() { + get tabIndex () { return this._tabIndex; } - set tabIndex(value) { + set tabIndex (value) { this._tabIndex = value; if (this._impl) { this._impl.setTabIndex(value); } } - static _EditBoxImpl = EditBoxImpl; - static KeyboardReturnType = KeyboardReturnType; - static InputFlag = InputFlag; - static InputMode = InputMode; + public static _EditBoxImpl = EditBoxImpl; + public static KeyboardReturnType = KeyboardReturnType; + public static InputFlag = InputFlag; + public static InputMode = InputMode; + @property + public _useOriginalSize = true; + @property + public _string = ''; + @property + public _tabIndex = 0; + @property + public _backgroundImage: SpriteFrame | null = null; + @property + public _returnType = KeyboardReturnType.DEFAULT; + @property + public _inputFlag = InputFlag.DEFAULT; + @property + public _inputMode = InputMode.SINGLE_LINE; + @property + public _fontSize = 20; + @property + public _lineHeight = 40; + @property + public _maxLength = 20; + @property + public _fontColor: Color = Color.WHITE; + @property + public _placeholder = 'Enter text here...'; + @property + public _placeholderFontSize = 20; + @property + public _placeholderFontColor: Color = Color.GRAY; + @property + public _stayOnTop = false; + /** + * !#en The event handler to be called when EditBox began to edit text. + * !#zh 开始编辑文本输入框触发的事件回调。 + * @property {Component.EventHandler[]} editingDidBegan + */ + @property + public editingDidBegan: ComponentEventHandler[] = []; - onEnable() { + /** + * !#en The event handler to be called when EditBox text changes. + * !#zh 编辑文本输入框时触发的事件回调。 + * @property {Component.EventHandler[]} textChanged + */ + @property + public textChanged: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when EditBox edit ends. + * !#zh 结束编辑文本输入框时触发的事件回调。 + * @property {Component.EventHandler[]} editingDidEnded + */ + @property + public editingDidEnded: ComponentEventHandler[] = []; + + /** + * !#en The event handler to be called when return key is pressed. Windows is not supported. + * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台 + * @property {Component.EventHandler[]} editingReturn + */ + @property + public editingReturn: ComponentEventHandler[] = []; + + public _impl: EditBoxImpl | null = null; + public _textLabel: LabelComponent | null = null; + public _placeholderLabel: LabelComponent | null = null; + public _background: SpriteComponent | null = null; + + public onEnable () { this._impl && this._impl.onEnable(); } - onDisable() { + public onDisable () { this._impl && this._impl.onDisable(); } - onDestroy() { + public onDestroy () { this._impl && this._impl.clear(); } - _init() { + public _init () { this._createBackgroundSprite(); this._createLabels(); this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this); - let impl = this._impl = new EditBoxImpl(); + const impl = this._impl = new EditBoxImpl(); impl.setDelegate(this); impl.setNode(this.node); @@ -487,30 +481,29 @@ export class EditBoxComponent extends Component { this._syncSize(); } - __preload() { + public __preload () { if (!CC_EDITOR) { this._registerEvent(); } this._init(); } - _registerEvent() { + public _registerEvent () { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); } - _updateStayOnTop() { + public _updateStayOnTop () { if (this.stayOnTop) { this._hideLabels(); - } - else { + } else { this._showLabels(); } this._impl && this._impl.stayOnTop(this.stayOnTop); } - _syncSize() { - let size = this.node.getContentSize(); + public _syncSize () { + const size = this.node.getContentSize(); this._background && this._background.node.setAnchorPoint(this.node.getAnchorPoint()); this._background && this._background.node.setContentSize(size); @@ -519,13 +512,13 @@ export class EditBoxComponent extends Component { this._impl && this._impl.setSize(size.width, size.height); } - _updateLabelPosition(size) { - let node = this.node; - let offx = -node.anchorX * node.width; - let offy = -node.anchorY * node.height; + public _updateLabelPosition (size) { + const node = this.node; + const offx = -node.anchorX * node.width; + const offy = -node.anchorY * node.height; - let placeholderLabel = this._placeholderLabel; - let textLabel = this._textLabel; + const placeholderLabel = this._placeholderLabel; + const textLabel = this._textLabel; if (textLabel) { textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height); textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, textLabel.node.getPosition().z); @@ -543,7 +536,7 @@ export class EditBoxComponent extends Component { } } - _createBackgroundSprite() { + public _createBackgroundSprite () { if (!this._background) { this._background = this.node.getComponent(cc.SpriteComponent); if (!this._background) { @@ -573,7 +566,7 @@ export class EditBoxComponent extends Component { // background.spriteFrame = this._backgroundImage; } - _createLabels() { + public _createLabels () { if (!this._textLabel) { let node = this.node.getChildByName('TEXT_LABEL'); if (!node) { @@ -586,7 +579,7 @@ export class EditBoxComponent extends Component { textLabel = node!.addComponent(LabelComponent); } - let transformComp = node!.getComponent(UITransformComponent); + const transformComp = node!.getComponent(UITransformComponent); transformComp!.setAnchorPoint(0, 1); textLabel!.color = this._fontColor; textLabel!.overflow = LabelComponent.Overflow.CLAMP; @@ -604,13 +597,12 @@ export class EditBoxComponent extends Component { if (!placeholderLabel) { placeholderLabel = node!.addComponent(LabelComponent); } - let transform = node!.getComponent(UITransformComponent); + const transform = node!.getComponent(UITransformComponent); node!.parent = this.node; placeholderLabel!.color = this._placeholderFontColor; transform!.setAnchorPoint(0, 1); - placeholderLabel!.overflow = LabelComponent.Overflow.CLAMP; placeholderLabel!.fontSize = this._placeholderFontSize; placeholderLabel!.string = this._placeholder; @@ -618,7 +610,7 @@ export class EditBoxComponent extends Component { } } - _resizeChildNodes() { + public _resizeChildNodes () { const textLabelNode = this._textLabel && this._textLabel.node; if (textLabelNode) { textLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, textLabelNode.getPosition().z); @@ -638,9 +630,9 @@ export class EditBoxComponent extends Component { } } - _showLabels() { + public _showLabels () { if (this._textLabel) { - let displayText = this._textLabel.string; + const displayText = this._textLabel.string; this._textLabel.node.active = displayText !== ''; if (this._placeholderLabel) { this._placeholderLabel.node.active = displayText === ''; @@ -648,7 +640,7 @@ export class EditBoxComponent extends Component { } } - _hideLabels() { + public _hideLabels () { if (this._textLabel) { this._textLabel.node.active = false; } @@ -657,8 +649,8 @@ export class EditBoxComponent extends Component { } } - _updateString(text) { - let textLabel = this._textLabel; + public _updateString (text) { + const textLabel = this._textLabel; // Not inited yet if (!textLabel) { return; @@ -678,36 +670,33 @@ export class EditBoxComponent extends Component { } } - _updateLabelStringStyle(text: string, ignorePassword: boolean = false) { - let inputFlag = this._inputFlag; + public _updateLabelStringStyle (text: string, ignorePassword: boolean = false) { + const inputFlag = this._inputFlag; if (!ignorePassword && inputFlag === InputFlag.PASSWORD) { let passwordString = ''; - let len = text.length; + const len = text.length; for (let i = 0; i < len; ++i) { passwordString += '\u25CF'; } text = passwordString; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + } else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { text = text.toUpperCase(); - } - else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { text = capitalize(text); - } - else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { + } else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { text = capitalizeFirstLetter(text); } return text; } - editBoxEditingDidBegan() { + public editBoxEditingDidBegan () { this._hideLabels(); ComponentEventHandler.emitEvents(this.editingDidBegan, this); this.node.emit('editing-did-began', this); } - editBoxEditingDidEnded() { + public editBoxEditingDidEnded () { if (!this.stayOnTop) { this._showLabels(); } @@ -715,33 +704,33 @@ export class EditBoxComponent extends Component { this.node.emit('editing-did-ended', this); } - editBoxTextChanged(text) { + public editBoxTextChanged (text) { text = this._updateLabelStringStyle(text, true); this.string = text; ComponentEventHandler.emitEvents(this.textChanged, text, this); this.node.emit('text-changed', this); } - editBoxEditingReturn() { + public editBoxEditingReturn () { ComponentEventHandler.emitEvents(this.editingReturn, this); this.node.emit('editing-return', this); } - _onTouchBegan(event) { + public _onTouchBegan (event) { if (this._impl) { this._impl._onTouchBegan(event.touch); } event.stopPropagation(); } - _onTouchCancel(event) { + public _onTouchCancel (event) { // if (this._impl) { // this._impl._onTouchCancel(); // } event.stopPropagation(); } - _onTouchEnded(event) { + public _onTouchEnded (event) { if (this._impl) { this._impl._onTouchEnded(); } @@ -753,7 +742,7 @@ export class EditBoxComponent extends Component { * !#zh 让当前 EditBox 获得焦点 * @method setFocus */ - setFocus() { + public setFocus () { if (this._impl) { this._impl.setFocus(); } @@ -765,7 +754,7 @@ export class EditBoxComponent extends Component { * Note: only available on Web at the moment. * @method isFocused */ - isFocused() { + public isFocused () { let isFocused = false; if (this._impl) { isFocused = this._impl.isFocused(); @@ -773,7 +762,7 @@ export class EditBoxComponent extends Component { return isFocused; } - update() { + public update () { if (this._impl) { this._impl.update(); } diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts index 77d91165cc..47aa5c7fdb 100644 --- a/cocos/3d/ui/components/editbox/edit-box-impl.ts +++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts @@ -27,34 +27,35 @@ ****************************************************************************/ import { ccclass } from '../../../../core/data/class-decorator'; -import { contains } from '../../../../core/utils/misc'; import macro from '../../../../core/platform/CCMacro'; +import { contains } from '../../../../core/utils/misc'; +import { Color, Size } from '../../../../core/value-types'; +import * as math from '../../../../core/vmath'; +import { Node } from '../../../../scene-graph/node'; +import { UIRenderComponent } from '../ui-render-component'; +import { EditBoxComponent} from './edit-box-component'; // import { InputMode, InputFlag, KeyboardReturnType } from './types'; import * as Types from './types'; -import * as math from '../../../../core/vmath'; -import { Size, Color } from '../../../../core/value-types'; -import { EditBoxComponent} from './edit-box-component'; -import { Node } from '../../../../scene-graph/node'; const InputMode = Types.InputMode; const InputFlag = Types.InputFlag; const KeyboardReturnType = Types.KeyboardReturnType; // https://segmentfault.com/q/1010000002914610 -let SCROLLY = 40; -let LEFT_PADDING = 2; -let DELAY_TIME = 400; -let FOCUS_DELAY_UC = 400; -let FOCUS_DELAY_FIREFOX = 0; +const SCROLLY = 40; +const LEFT_PADDING = 2; +const DELAY_TIME = 400; +const FOCUS_DELAY_UC = 400; +const FOCUS_DELAY_FIREFOX = 0; -let _matrix = cc.mat4(); -let _matrix_temp = cc.mat4(); -let _vec3 = cc.v3(); +const _matrix = cc.mat4(); +const _matrix_temp = cc.mat4(); +const _vec3 = cc.v3(); -let _currentEditBoxImpl: EditBoxImpl | null= null; +let _currentEditBoxImpl: EditBoxImpl | null = null; // polyfill -let polyfill = { - zoomInvalid: false +const polyfill = { + zoomInvalid: false, }; if (cc.sys.OS_ANDROID === cc.sys.os && @@ -63,7 +64,7 @@ if (cc.sys.OS_ANDROID === cc.sys.os && polyfill.zoomInvalid = true; } -function getKeyboardReturnType(type) { +function getKeyboardReturnType (type) { switch (type) { case KeyboardReturnType.DEFAULT: case KeyboardReturnType.DONE: @@ -83,10 +84,10 @@ function getKeyboardReturnType(type) { @ccclass export class EditBoxImpl { private _delegate: EditBoxComponent | null = null; - private _inputMode= -1; - private _inputFlag= -1; + private _inputMode = -1; + private _inputFlag = -1; private _returnType = KeyboardReturnType.DEFAULT; - private _maxLength= 50; + private _maxLength = 50; private _text = ''; private _placeholderText = ''; private _alwaysOnTop = false; @@ -102,72 +103,71 @@ export class EditBoxImpl { private _textColor: Color = Color.WHITE; private _edFontSize = 14; - get text() { + get text () { return this._text; } - set text(value: string) { + set text (value: string) { this._text = value; } - get textColor() { + get textColor () { return this._textColor; } - get fontSize() { + get fontSize () { return this._edFontSize; } - set returnType(value: Types.KeyboardReturnType) { + set returnType (value: Types.KeyboardReturnType) { this._returnType = value; } - get alwayOnTop() { + get alwayOnTop () { return this._alwaysOnTop; } - set editing(value: boolean) { + set editing (value: boolean) { this._editing = value; } - get delegate() { + get delegate () { return this._delegate; } - get eventListeners() { + get eventListeners () { return this.__eventListeners; } - onEnable() { + public onEnable () { if (!this._edTxt) { return; } if (this._alwaysOnTop) { this._edTxt.style.display = ''; - } - else { + } else { this._edTxt.style.display = 'none'; } } - onDisable() { + public onDisable () { if (!this._edTxt) { return; } this._edTxt.style.display = 'none'; } - setTabIndex(index) { + public setTabIndex (index) { if (this._edTxt) { this._edTxt.tabIndex = index; } } - setFocus() { + public setFocus () { this._beginEditing(); } - isFocused() { + public isFocused () { if (this._edTxt) { return document.activeElement === this._edTxt; } @@ -175,8 +175,8 @@ export class EditBoxImpl { return false; } - stayOnTop(flag) { - if (this._alwaysOnTop === flag || !this._edTxt) return; + public stayOnTop (flag) { + if (this._alwaysOnTop === flag || !this._edTxt) { return; } this._alwaysOnTop = flag; @@ -187,41 +187,45 @@ export class EditBoxImpl { } } - setMaxLength(maxLength) { + public setMaxLength (maxLength) { if (!isNaN(maxLength)) { if (maxLength < 0) { - //we can't set Number.MAX_VALUE to input's maxLength property - //so we use a magic number here, it should works at most use cases. + // we can't set Number.MAX_VALUE to input's maxLength property + // so we use a magic number here, it should works at most use cases. maxLength = 65535; } this._maxLength = maxLength; - this._edTxt && (this._edTxt.maxLength = maxLength); + if (this._edTxt) { + this._edTxt.maxLength = maxLength; + } } } - setString(text) { + public setString (text) { this._text = text; - this._edTxt && (this._edTxt.value = text); + if (this._edTxt) { + this._edTxt.value = text; + } } - getString() { + public getString () { return this._text; } - setPlaceholderText(text) { + public setPlaceholderText (text) { this._placeholderText = text; } - getPlaceholderText() { + public getPlaceholderText () { return this._placeholderText; } - setDelegate(delegate) { + public setDelegate (delegate) { this._delegate = delegate; } - setInputMode(inputMode) { - if (this._inputMode === inputMode) return; + public setInputMode (inputMode) { + if (this._inputMode === inputMode) { return; } this._inputMode = inputMode; this.createInput(); @@ -230,8 +234,8 @@ export class EditBoxImpl { this._updateSize(this._size.width, this._size.height); } - setInputFlag(inputFlag) { - if (this._inputFlag === inputFlag) return; + public setInputFlag (inputFlag) { + if (this._inputFlag === inputFlag) { return; } this._inputFlag = inputFlag; this._updateDomInputType(); @@ -240,8 +244,7 @@ export class EditBoxImpl { if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { textTransform = 'uppercase'; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { textTransform = 'capitalize'; } @@ -251,53 +254,57 @@ export class EditBoxImpl { } } - setReturnType(returnType) { + public setReturnType (returnType) { this._returnType = returnType; this._updateDomInputType(); } - setFontSize(fontSize) { + public setFontSize (fontSize) { this._edFontSize = fontSize || this._edFontSize; - this._edTxt && (this._edTxt.style.fontSize = this._edFontSize + 'px'); + if (this._edTxt) { + this._edTxt.style.fontSize = this._edFontSize + 'px'; + } } - setFontColor(color) { + public setFontColor (color) { this._textColor = color; - this._edTxt && (this._edTxt.style.color = color.toCSS('rgba')); + if (this._edTxt) { + this._edTxt.style.color = color.toCSS('rgba'); + } } - setSize(width, height) { + public setSize (width, height) { this._size.width = width; this._size.height = height; this._updateSize(width, height); } - setNode(node) { + public setNode (node) { this._node = node; } - update() { + public update () { // TODO: find better way to update matrix // if (this._editing) { this._updateMatrix(); // } } - clear() { + public clear () { this._node = null; this.setDelegate(null); this.removeDom(); } - _onTouchBegan(touch) { + public _onTouchBegan (touch) { } - _onTouchEnded() { + public _onTouchEnded () { this._beginEditing(); } - _beginEditing() { + public _beginEditing () { if (cc.sys.isMobile && !this._editing) { // Pre adaptation this._beginEditingOnMobile(); @@ -306,18 +313,16 @@ export class EditBoxImpl { if (this._edTxt) { this._edTxt.style.display = ''; - let self = this; - function startFocus() { + const self = this; + function startFocus () { self._edTxt!.focus(); } if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { setTimeout(startFocus, FOCUS_DELAY_UC); - } - else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { + } else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { setTimeout(startFocus, FOCUS_DELAY_FIREFOX); - } - else { + } else { startFocus(); } } @@ -325,9 +330,9 @@ export class EditBoxImpl { this._editing = true; } - _endEditing() { - let self = this; - let hideDomInputAndShowLabel = function () { + public _endEditing () { + const self = this; + const hideDomInputAndShowLabel = () => { if (!self._alwaysOnTop && self._edTxt) { self._edTxt.style.display = 'none'; } @@ -338,22 +343,21 @@ export class EditBoxImpl { if (this._editing) { if (cc.sys.isMobile) { // Delay end editing adaptation to ensure virtual keyboard is disapeared - setTimeout(function () { + setTimeout(() => { self._endEditingOnMobile(); hideDomInputAndShowLabel(); }, DELAY_TIME); - } - else { + } else { hideDomInputAndShowLabel(); } } this._editing = false; } - _updateDomInputType() { - let inputMode = this._inputMode; - let edTxt = this._edTxt as HTMLInputElement; - if (!edTxt) return; + public _updateDomInputType () { + const inputMode = this._inputMode; + const edTxt = this._edTxt as HTMLInputElement; + if (!edTxt) { return; } if (this._inputFlag === InputFlag.PASSWORD) { edTxt!.type = 'password'; @@ -381,16 +385,16 @@ export class EditBoxImpl { edTxt.type = type; } - _updateSize(newWidth, newHeight) { - let edTxt = this._edTxt; - if (!edTxt) return; + public _updateSize (newWidth, newHeight) { + const edTxt = this._edTxt; + if (!edTxt) { return; } edTxt.style.width = newWidth + 'px'; edTxt.style.height = newHeight + 'px'; } - _updateMatrix() { - if (!this._edTxt) return; + public _updateMatrix () { + if (!this._edTxt) { return; } const node = this._node; let scaleX = cc.view._scaleX; @@ -399,7 +403,7 @@ export class EditBoxImpl { const dpr = cc.view._devicePixelRatio; node!.getWorldMatrix(_matrix); - const transform = node!.uiTransfromComp + const transform = node!.uiTransfromComp; if (transform) { _vec3.x = -transform.anchorX.x * transform.width; _vec3.y = -transform.anchorY.y * transform.height; @@ -415,21 +419,21 @@ export class EditBoxImpl { // else { // camera = cc.Camera.findCamera(node); // } - let renderComp = node!.getComponent(cc.RenderComponent); + const renderComp = node!.getComponent(UIRenderComponent); if (!renderComp) { return false; } // let canvas = cc.CanvasComponent.findView(renderComp); - let canvas = cc.director.root.ui.getScreen() + const canvas = cc.director.root.ui.getScreen(renderComp.visibility); if (!canvas) { return; } // camera.getWorldToCameraMatrix(_matrix_temp); canvas.node.getWorldRT(_matrix_temp); - let m12 = _matrix_temp.m12; - let m13 = _matrix_temp.m13; - let center = cc.visibleRect.center; + const m12 = _matrix_temp.m12; + const m13 = _matrix_temp.m13; + const center = cc.visibleRect.center; _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13); _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13); @@ -438,14 +442,18 @@ export class EditBoxImpl { scaleX /= dpr; scaleY /= dpr; - let container = cc.game.container; - let a = _matrix_temp.m00 * scaleX, b = _matrix.m01, c = _matrix.m04, d = _matrix_temp.m05 * scaleY; + const container = cc.game.container; + let a = _matrix_temp.m00 * scaleX; + const b = _matrix.m01; + const c = _matrix.m04; + let d = _matrix_temp.m05 * scaleY; let offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); offsetX += viewport.x / dpr; let offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); offsetY += viewport.y / dpr; - let tx = _matrix_temp.m12 * scaleX + offsetX, ty = _matrix_temp.m13 * scaleY + offsetY; + const tx = _matrix_temp.m12 * scaleX + offsetX; + const ty = _matrix_temp.m13 * scaleY + offsetY; if (polyfill.zoomInvalid) { this._updateSize(this._size.width * a, this._size.height * d); @@ -453,45 +461,44 @@ export class EditBoxImpl { d = 1; } - let matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; - this._edTxt.style['transform'] = matrix; + const matrix = 'matrix(' + a + ',' + -b + ',' + -c + ',' + d + ',' + tx + ',' + -ty + ')'; + this._edTxt.style.transform = matrix; this._edTxt.style['-webkit-transform'] = matrix; this._edTxt.style['transform-origin'] = '0px 100% 0px'; this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; } - _adjustEditBoxPosition() { + public _adjustEditBoxPosition () { this._node!.getWorldMatrix(_matrix); - let y = _matrix.m13; - let windowHeight = cc.visibleRect.height; - let windowWidth = cc.visibleRect.width; + const y = _matrix.m13; + const windowHeight = cc.visibleRect.height; + const windowWidth = cc.visibleRect.width; let factor = 0.5; if (windowWidth > windowHeight) { factor = 0.7; } - setTimeout(function () { + setTimeout(() => { if (window.scrollY < SCROLLY && y < windowHeight * factor) { let scrollOffset = windowHeight * factor - y - window.scrollY; - if (scrollOffset < 35) scrollOffset = 35; - if (scrollOffset > 320) scrollOffset = 320; + if (scrollOffset < 35) { scrollOffset = 35; } + if (scrollOffset > 320) { scrollOffset = 320; } window.scrollTo(0, scrollOffset); } }, DELAY_TIME); } - createInput() { + public createInput () { if (this._inputMode === InputMode.ANY) { this._createDomTextArea(); - } - else { + } else { this._createDomInput(); } } // Called before editbox focus to register cc.view status - _beginEditingOnMobile() { - let self = this; - this.__orientationChanged = function () { + public _beginEditingOnMobile () { + const self = this; + this.__orientationChanged = () => { self._adjustEditBoxPosition(); }; window.addEventListener('orientationchange', this.__orientationChanged); @@ -509,14 +516,14 @@ export class EditBoxImpl { } // Called after keyboard disappeared to readapte the game view - _endEditingOnMobile() { + public _endEditingOnMobile () { if (this.__rotateScreen) { cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; cc.game.container.style.transform = 'rotate(90deg)'; - let view = cc.view; - let width = view._originalDesignResolutionSize.width; - let height = view._originalDesignResolutionSize.height; + const view = cc.view; + const width = view._originalDesignResolutionSize.width; + const height = view._originalDesignResolutionSize.height; if (width > 0) { view.setDesignResolutionSize(width, height, view._resolutionPolicy); } @@ -540,10 +547,10 @@ export class EditBoxImpl { } } - _createDomInput() { + public _createDomInput () { this.removeDom(); - let tmpEdTxt = this._edTxt = document.createElement('input'); + const tmpEdTxt = this._edTxt = document.createElement('input'); tmpEdTxt.type = 'text'; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; @@ -556,11 +563,11 @@ export class EditBoxImpl { tmpEdTxt.style.padding = '0'; tmpEdTxt.style.textTransform = 'uppercase'; tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = "absolute"; - tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = LEFT_PADDING + "px"; + tmpEdTxt.style.position = 'absolute'; + tmpEdTxt.style.bottom = '0px'; + tmpEdTxt.style.left = LEFT_PADDING + 'px'; tmpEdTxt.style['-moz-appearance'] = 'textfield'; - tmpEdTxt.className = "cocosEditBox"; + tmpEdTxt.className = 'cocosEditBox'; tmpEdTxt.style.fontFamily = 'Arial'; registerInputEventListener(tmpEdTxt, this); @@ -568,10 +575,10 @@ export class EditBoxImpl { return tmpEdTxt; } - _createDomTextArea() { + public _createDomTextArea () { this.removeDom(); - let tmpEdTxt = this._edTxt = document.createElement('textarea'); + const tmpEdTxt = this._edTxt = document.createElement('textarea'); // tmpEdTxt.type = 'text'; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; @@ -586,10 +593,10 @@ export class EditBoxImpl { tmpEdTxt.style.textTransform = 'uppercase'; tmpEdTxt.style.overflowY = 'scroll'; tmpEdTxt.style.display = 'none'; - tmpEdTxt.style.position = "absolute"; - tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = LEFT_PADDING + "px"; - tmpEdTxt.className = "cocosEditBox"; + tmpEdTxt.style.position = 'absolute'; + tmpEdTxt.style.bottom = '0px'; + tmpEdTxt.style.left = LEFT_PADDING + 'px'; + tmpEdTxt.className = 'cocosEditBox'; tmpEdTxt.style.fontFamily = 'Arial'; registerInputEventListener(tmpEdTxt, this, true); @@ -597,15 +604,15 @@ export class EditBoxImpl { return tmpEdTxt; } - _addDomToGameContainer() { + public _addDomToGameContainer () { cc.game.container.appendChild(this._edTxt); } - removeDom() { - let edTxt = this._edTxt; + public removeDom () { + const edTxt = this._edTxt; if (edTxt) { // Remove listeners - let cbs = this.__eventListeners; + const cbs = this.__eventListeners; edTxt.removeEventListener('compositionstart', cbs.compositionstart); edTxt.removeEventListener('compositionend', cbs.compositionend); edTxt.removeEventListener('input', cbs.input); @@ -619,7 +626,7 @@ export class EditBoxImpl { cbs.keypress = null; cbs.blur = null; - let hasChild = contains(cc.game.container, edTxt); + const hasChild = contains(cc.game.container, edTxt); if (hasChild) { cc.game.container.removeChild(edTxt); } @@ -628,7 +635,7 @@ export class EditBoxImpl { } } -function _inputValueHandle(input, editBoxImpl) { +function _inputValueHandle (input, editBoxImpl) { if (input.value.length > editBoxImpl._maxLength) { input.value = input.value.slice(0, editBoxImpl._maxLength); } @@ -640,10 +647,10 @@ function _inputValueHandle(input, editBoxImpl) { } } -function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) { +function registerInputEventListener (tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) { let inputLock = false; - let cbs = editBoxImpl.eventListeners; - cbs.compositionstart = function () { + const cbs = editBoxImpl.eventListeners; + cbs.compositionstart = () => { inputLock = true; }; tmpEdTxt.addEventListener('compositionstart', cbs.compositionstart); diff --git a/cocos/3d/ui/components/editbox/types.ts b/cocos/3d/ui/components/editbox/types.ts index cd78a8ab6e..49b1bb0570 100644 --- a/cocos/3d/ui/components/editbox/types.ts +++ b/cocos/3d/ui/components/editbox/types.ts @@ -22,6 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + +import { Enum } from '../../../../core/value-types'; /** * !#en Enum for keyboard return types * !#zh 键盘的返回键类型 @@ -64,8 +66,9 @@ export enum KeyboardReturnType { * !#zh 下一个类型 * @property {Number} NEXT */ - NEXT = 5 -}; + NEXT = 5, +} +Enum(KeyboardReturnType); /** * !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. @@ -118,8 +121,10 @@ export enum InputMode { * !#zh 除了换行符以外,用户可以输入任何文本。 * @property {Number} SINGLE_LINE */ - SINGLE_LINE = 6 -}; + SINGLE_LINE = 6, +} + +Enum(InputMode); /** * !#en Enum for the EditBox's input flags @@ -177,6 +182,7 @@ export enum InputFlag { * Don't do anything with the input text. * @property {Number} DEFAULT */ - DEFAULT = 5 -}; + DEFAULT = 5, +} +Enum(InputFlag); diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts index 2d1dbe2943..79b96d186c 100644 --- a/cocos/3d/ui/components/label-component.ts +++ b/cocos/3d/ui/components/label-component.ts @@ -24,21 +24,21 @@ THE SOFTWARE. ****************************************************************************/ // @ts-check -import macro from '../../../core/platform/CCMacro'; -import { UIRenderComponent } from './ui-render-component'; +import Font from '../../../assets/CCFont'; import { ImageAsset } from '../../../assets/image-asset'; +import { Texture2D } from '../../../assets/texture-2d'; // import { vec2, vec3, mat4, color4 } from '../../../core/vmath/index'; import { ccclass, - property, - menu, - executionOrder, executeInEditMode, + executionOrder, + menu, + property, } from '../../../core/data/class-decorator'; -import Font from '../../../assets/CCFont'; -import { Texture2D } from '../../../assets/texture-2d'; -import { MeshBuffer } from '../mesh-buffer'; +import macro from '../../../core/platform/CCMacro'; import { Enum } from '../../../core/value-types'; +import { MeshBuffer } from '../mesh-buffer'; +import { UIRenderComponent } from './ui-render-component'; // import { value } from '../../../core/utils/js'; /** @@ -553,7 +553,7 @@ export class LabelComponent extends UIRenderComponent { } public onDestroy () { - if (this._assembler && this._assembler._resetAssemblerData){ + if (this._assembler && this._assembler._resetAssemblerData) { this._assembler._resetAssemblerData(this._assemblerData); } @@ -584,7 +584,7 @@ export class LabelComponent extends UIRenderComponent { } public _updateAssembler () { - const assembler = LabelComponent._assembler.getAssembler(this); + const assembler = LabelComponent.Assembler.getAssembler(this); if (this._assembler !== assembler) { this.destroyRenderData(); diff --git a/cocos/3d/ui/components/CCLayout.js b/cocos/3d/ui/components/layout-component.ts similarity index 52% rename from cocos/3d/ui/components/CCLayout.js rename to cocos/3d/ui/components/layout-component.ts index ad0c8b7ff9..c19b245d94 100644 --- a/cocos/3d/ui/components/CCLayout.js +++ b/cocos/3d/ui/components/layout-component.ts @@ -24,66 +24,72 @@ THE SOFTWARE. ****************************************************************************/ -const NodeEvent = require('../CCNode').EventType; - +import { Component } from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { Enum, Size } from '../../../core/value-types'; +import { Node } from '../../../scene-graph/node'; +const NodeEvent = Node.EventType; /** * !#en Enum for Layout type * !#zh 布局类型 * @enum Layout.Type */ -var Type = cc.Enum({ +enum Type { /** * !#en None Layout * !#zh 取消布局 - *@property {Number} NONE */ - NONE: 0, + NONE = 0, /** * !#en Horizontal Layout * !#zh 水平布局 * @property {Number} HORIZONTAL */ - HORIZONTAL: 1, + HORIZONTAL = 1, /** * !#en Vertical Layout * !#zh 垂直布局 * @property {Number} VERTICAL */ - VERTICAL: 2, + VERTICAL = 2, /** * !#en Grid Layout * !#zh 网格布局 * @property {Number} GRID */ - GRID: 3, -}); + GRID = 3, +} + +Enum(Type); /** * !#en Enum for Layout Resize Mode * !#zh 缩放模式 * @enum Layout.ResizeMode */ -var ResizeMode = cc.Enum({ +enum ResizeMode { /** * !#en Don't do any scale. * !#zh 不做任何缩放 * @property {Number} NONE */ - NONE: 0, + NONE = 0, /** * !#en The container size will be expanded with its children's size. * !#zh 容器的大小会根据子节点的大小自动缩放。 * @property {Number} CONTAINER */ - CONTAINER: 1, + CONTAINER = 1, /** * !#en Child item size will be adjusted with the container's size. * !#zh 子节点的大小会随着容器的大小自动缩放。 * @property {Number} CHILDREN */ - CHILDREN: 2 -}); + CHILDREN = 2, +} + +Enum(ResizeMode); /** * !#en Enum for Grid Layout start axis direction. @@ -91,20 +97,22 @@ var ResizeMode = cc.Enum({ * !#zh 布局轴向,只用于 GRID 布局。 * @enum Layout.AxisDirection */ -var AxisDirection = cc.Enum({ +enum AxisDirection { /** * !#en The horizontal axis. * !#zh 进行水平方向布局 * @property {Number} HORIZONTAL */ - HORIZONTAL: 0, + HORIZONTAL = 0, /** * !#en The vertical axis. * !#zh 进行垂直方向布局 * @property {Number} VERTICAL */ - VERTICAL: 1, -}); + VERTICAL = 1, +} + +Enum(AxisDirection); /** * !#en Enum for vertical layout direction. @@ -112,20 +120,22 @@ var AxisDirection = cc.Enum({ * !#zh 垂直方向布局方式 * @enum Layout.VerticalDirection */ -var VerticalDirection = cc.Enum({ +enum VerticalDirection { /** * !#en Items arranged from bottom to top. * !#zh 从下到上排列 * @property {Number} BOTTOM_TO_TOP */ - BOTTOM_TO_TOP: 0, + BOTTOM_TO_TOP = 0, /** * !#en Items arranged from top to bottom. * !#zh 从上到下排列 * @property {Number} TOP_TO_BOTTOM */ - TOP_TO_BOTTOM: 1, -}); + TOP_TO_BOTTOM = 1, +} + +Enum(VerticalDirection); /** * !#en Enum for horizontal layout direction. @@ -133,20 +143,20 @@ var VerticalDirection = cc.Enum({ * !#zh 水平方向布局方式 * @enum Layout.HorizontalDirection */ -var HorizontalDirection = cc.Enum({ +enum HorizontalDirection { /** * !#en Items arranged from left to right. * !#zh 从左往右排列 - * @property {Number} LEFT_TO_RIGHT */ - LEFT_TO_RIGHT: 0, + LEFT_TO_RIGHT = 0, /** * !#en Items arranged from right to left. * !#zh 从右往左排列 - *@property {Number} RIGHT_TO_LEFT */ - RIGHT_TO_LEFT: 1, -}); + RIGHT_TO_LEFT = 1, +} + +Enum(HorizontalDirection); /** * !#en @@ -163,257 +173,333 @@ var HorizontalDirection = cc.Enum({ * @class Layout * @extends Component */ -var Layout = cc.Class({ - name: 'cc.Layout', - extends: require('./CCComponent'), +@ccclass('cc.LayoutComponent') +@executionOrder(100) +@menu('UI/Layout') +@executeInEditMode +export class LayoutComponent extends Component { - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/Layout', - help: 'i18n:COMPONENT.help_url.layout', - inspector: 'packages://inspector/inspectors/comps/cclayout.js', - executeInEditMode: true, - }, + /** + * !#en The layout type. + * !#zh 布局类型 + * @property {Layout.Type} type + * @default Layout.Type.NONE + */ + @property + get type () { + return this._N$layoutType; + } - properties: { - _layoutSize: cc.size(300, 200), - _layoutDirty: { - default: true, - serializable: false, - }, + set type (value) { + this._N$layoutType = value; - _resize: ResizeMode.NONE, + if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + // if (reLayouted) { + // return; + // } + } + this._doLayoutDirty(); + } + /** + * !#en + * The are three resize modes for Layout. + * None, resize Container and resize children. + * !#zh 缩放模式 + * @property {Layout.ResizeMode} resizeMode + * @default ResizeMode.NONE + */ + @property({ + type: ResizeMode, + }) + get resizeMode () { + return this._resize; + } + set resizeMode (value) { + if (this.type === Type.NONE && value === ResizeMode.CHILDREN) { + return; + } - //TODO: refactoring this name after data upgrade machanism is out. - _N$layoutType: Type.NONE, - /** - * !#en The layout type. - * !#zh 布局类型 - * @property {Layout.Type} type - * @default Layout.Type.NONE - */ - type: { - type: Type, - get: function () { - return this._N$layoutType; - }, - set: function (value) { - this._N$layoutType = value; + this._resize = value; + if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + // if (reLayouted) { + // return; + // } + } + this._doLayoutDirty(); + } - if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { - var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); - if (reLayouted) { - return; - } - } - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.layout_type', - animatable: false, - }, + /** + * !#en The cell size for grid layout. + * !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。 + * @property {Size} cellSize + * @default cc.size(40, 40) + */ + @property + get cellSize () { + return this._cellSize; + } + set cellSize (value: Size) { + if (this._cellSize === value) { + return; + } - /** - * !#en - * The are three resize modes for Layout. - * None, resize Container and resize children. - * !#zh 缩放模式 - * @property {Layout.ResizeMode} resizeMode - * @default ResizeMode.NONE - */ - resizeMode: { - type: ResizeMode, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.resize_mode', - animatable: false, - get: function () { - return this._resize; - }, - set: function (value) { - if (this.type === Type.NONE && value === ResizeMode.CHILDREN) { - return; - } + this._cellSize = value; + this._doLayoutDirty(); + } - this._resize = value; - if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) { - var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); - if (reLayouted) { - return; - } - } - this._doLayoutDirty(); - }, - }, + /** + * !#en + * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, + * and then break line on demand. Choose vertical if you want to layout vertically at first . + * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 + * @property {Layout.AxisDirection} startAxis + */ + @property + get startAxis () { + return this._startAxis; + } - /** - * !#en The cell size for grid layout. - * !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。 - * @property {Size} cellSize - * @default cc.size(40, 40) - */ - cellSize: { - default: cc.size(40, 40), - tooltip: CC_DEV && 'i18n:COMPONENT.layout.cell_size', - type: cc.Size, - notify: function () { - this._doLayoutDirty(); - }, - }, + set startAxis (value) { + if (this._startAxis === value) { + return; + } - /** - * !#en - * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, - * and then break line on demand. Choose vertical if you want to layout vertically at first . - * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 - * @property {Layout.AxisDirection} startAxis - */ - startAxis: { - default: AxisDirection.HORIZONTAL, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.start_axis', - type: AxisDirection, - notify: function () { - if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { - var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); - if (reLayouted) { - return; - } - } - this._doLayoutDirty(); - }, - animatable: false - }, + if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + // if (reLayouted) { + // return; + // } + } - _N$padding: { - default: 0 - }, - /** - * !#en The left padding of layout, it only effect the layout in one direction. - * !#zh 容器内左边距,只会在一个布局方向上生效。 - * @property {Number} paddingLeft - */ - paddingLeft: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_left', - notify: function () { - this._doLayoutDirty(); - }, - }, + this._startAxis = value; + this._doLayoutDirty(); + } + /** + * !#en The left padding of layout, it only effect the layout in one direction. + * !#zh 容器内左边距,只会在一个布局方向上生效。 + * @property {Number} paddingLeft + */ + @property + get paddingLeft () { + return this._paddingLeft; + } + set paddingLeft (value) { + if (this._paddingLeft === value) { + return; + } - /** - * !#en The right padding of layout, it only effect the layout in one direction. - * !#zh 容器内右边距,只会在一个布局方向上生效。 - * @property {Number} paddingRight - */ - paddingRight: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_right', - notify: function () { - this._doLayoutDirty(); - }, - }, + this._paddingLeft = value; + this._doLayoutDirty(); + } - /** - * !#en The top padding of layout, it only effect the layout in one direction. - * !#zh 容器内上边距,只会在一个布局方向上生效。 - * @property {Number} paddingTop - */ - paddingTop: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_top', - notify: function () { - this._doLayoutDirty(); - }, - }, + /** + * !#en The right padding of layout, it only effect the layout in one direction. + * !#zh 容器内右边距,只会在一个布局方向上生效。 + * @property {Number} paddingRight + */ + @property + get paddingRight () { + return this._paddingRight; + } + set paddingRight (value) { + if (this._paddingRight === value) { + return; + } - /** - * !#en The bottom padding of layout, it only effect the layout in one direction. - * !#zh 容器内下边距,只会在一个布局方向上生效。 - * @property {Number} paddingBottom - */ - paddingBottom: { - default: 0, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_bottom', - notify: function () { - this._doLayoutDirty(); - }, - }, + this._paddingRight = value; + this._doLayoutDirty(); + } - /** - * !#en The distance in x-axis between each element in layout. - * !#zh 子节点之间的水平间距。 - * @property {Number} spacingX - */ - spacingX: { - default: 0, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.space_x' - }, + /** + * !#en The top padding of layout, it only effect the layout in one direction. + * !#zh 容器内上边距,只会在一个布局方向上生效。 + * @property {Number} paddingTop + */ + @property + get paddingTop () { + return this._paddingTop; + } + set paddingTop (value) { + if (this._paddingTop === value) { + return; + } - /** - * !#en The distance in y-axis between each element in layout. - * !#zh 子节点之间的垂直间距。 - * @property {Number} spacingY - */ - spacingY: { - default: 0, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.space_y' - }, + this._paddingTop = value; + this._doLayoutDirty(); + } - /** - * !#en - * Only take effect in Vertical layout mode. - * This option changes the start element's positioning. - * !#zh 垂直排列子节点的方向。 - * @property {Layout.VerticalDirection} verticalDirection - */ - verticalDirection: { - default: VerticalDirection.TOP_TO_BOTTOM, - type: VerticalDirection, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.vertical_direction', - animatable: false - }, + /** + * !#en The bottom padding of layout, it only effect the layout in one direction. + * !#zh 容器内下边距,只会在一个布局方向上生效。 + * @property {Number} paddingBottom + */ + @property + get paddingBottom () { + return this._paddingBottom; + } + set paddingBottom (value) { + if (this._paddingBottom === value) { + return; + } - /** - * !#en - * Only take effect in Horizontal layout mode. - * This option changes the start element's positioning. - * !#zh 水平排列子节点的方向。 - * @property {Layout.HorizontalDirection} horizontalDirection - */ - horizontalDirection: { - default: HorizontalDirection.LEFT_TO_RIGHT, - type: HorizontalDirection, - notify: function () { - this._doLayoutDirty(); - }, - tooltip: CC_DEV && 'i18n:COMPONENT.layout.horizontal_direction', - animatable: false - }, - }, + this._paddingBottom = value; + this._doLayoutDirty(); + } - statics: { - Type: Type, - VerticalDirection: VerticalDirection, - HorizontalDirection: HorizontalDirection, - ResizeMode: ResizeMode, - AxisDirection: AxisDirection, - }, + /** + * !#en The distance in x-axis between each element in layout. + * !#zh 子节点之间的水平间距。 + * @property {Number} spacingX + */ + get spacingX () { + return this._spacingX; + } - _migratePaddingData: function () { + set spacingX (value) { + if (this._spacingX === value) { + return; + } + + this._spacingX = value; + this._doLayoutDirty(); + } + + /** + * !#en The distance in y-axis between each element in layout. + * !#zh 子节点之间的垂直间距。 + * @property {Number} spacingY + */ + @property + get spacingY () { + return this._spacingY; + } + + set spacingY (value) { + if (this._spacingY === value) { + return; + } + + this._spacingY = value; + this._doLayoutDirty(); + } + + /** + * !#en + * Only take effect in Vertical layout mode. + * This option changes the start element's positioning. + * !#zh 垂直排列子节点的方向。 + * @property {VerticalDirection} verticalDirection + */ + @property({ + type: VerticalDirection, + }) + get verticalDirection () { + return this._verticalDirection; + } + + set verticalDirection (value: VerticalDirection) { + if (this._verticalDirection === value) { + return; + } + + this._verticalDirection = value; + this._doLayoutDirty(); + } + + /** + * !#en + * Only take effect in Horizontal layout mode. + * This option changes the start element's positioning. + * !#zh 水平排列子节点的方向。 + * @property {Layout.HorizontalDirection} horizontalDirection + */ + @property({ + type: HorizontalDirection, + }) + get horizontalDirection () { + return this._horizontalDirection; + } + + set horizontalDirection (value: HorizontalDirection) { + if (this._horizontalDirection === value) { + return; + } + + this._horizontalDirection = value; + this._doLayoutDirty(); + } + + /** + * !#en The padding of layout, it effects the layout in four direction. + * !#zh 容器内边距,该属性会在四个布局方向上生效。 + * @property {Number} padding + */ + @property + get padding() { + return this._paddingLeft; + } + + set padding(value) { + this._N$padding = value; + + this._migratePaddingData(); + this._doLayoutDirty(); + } + + /** + * !#en Adjust the layout if the children scaled. + * !#zh 子节点缩放比例是否影响布局。 + * @property affectedByScale + * @type {Boolean} + * @default false + */ + @property + get affectedByScale() { + return this._affectedByScale; + } + + set affectedByScale(value) { + this._affectedByScale = value; + this._doLayoutDirty(); + } + + public static Type = Type; + public static VerticalDirection = VerticalDirection; + public static HorizontalDirection = HorizontalDirection; + public static ResizeMode = ResizeMode; + public static AxisDirection = AxisDirection; + + private _layoutDirty = true; + private _resize = ResizeMode.NONE; + + // TODO: refactoring this name after data upgrade machanism is out. + private _N$layoutType = Type.NONE; + private _N$padding = 0; + private _cellSize = cc.size(40, 40); + private _startAxis = AxisDirection.HORIZONTAL; + private _paddingLeft = 0; + private _paddingRight = 0; + private _paddingTop = 0; + private _paddingBottom = 0; + private _spacingX = 0; + private _spacingY = 0; + private _layoutSize = cc.size(300, 200); + private _verticalDirection = VerticalDirection.TOP_TO_BOTTOM; + private _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT; + private _affectedByScale = false; + + private _migratePaddingData () { this.paddingLeft = this._N$padding; this.paddingRight = this._N$padding; this.paddingTop = this._N$padding; this.paddingBottom = this._N$padding; this._N$padding = 0; - }, + } - onEnable: function () { + protected onEnable () { this._addEventListeners(); if (this.node.getContentSize().equals(cc.size(0, 0))) { @@ -425,17 +511,13 @@ var Layout = cc.Class({ } this._doLayoutDirty(); - }, + } - onDisable: function () { + protected onDisable () { this._removeEventListeners(); - }, + } - _doLayoutDirty: function () { - this._layoutDirty = true; - }, - - _addEventListeners: function () { + private _addEventListeners () { cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -443,9 +525,9 @@ var Layout = cc.Class({ this.node.on(NodeEvent.CHILD_REMOVED, this._childRemoved, this); this.node.on(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._addChildrenEventListeners(); - }, + } - _removeEventListeners: function () { + private _removeEventListeners () { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this); this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this); this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); @@ -453,96 +535,98 @@ var Layout = cc.Class({ this.node.off(NodeEvent.CHILD_REMOVED, this._childRemoved, this); this.node.off(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this); this._removeChildrenEventListeners(); - }, + } - _addChildrenEventListeners: function () { - var children = this.node.children; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + private _addChildrenEventListeners () { + const children = this.node.children; + for (const child of children) { + child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on('active-in-hierarchy-changed', this._doLayoutDirty, this); } - }, + } - _removeChildrenEventListeners: function () { - var children = this.node.children; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + private _removeChildrenEventListeners () { + const children = this.node.children; + for (const child of children) { + child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off('active-in-hierarchy-changed', this._doLayoutDirty, this); } - }, + } - _childAdded: function (child) { + private _childAdded (child) { + child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.on('active-in-hierarchy-changed', this._doLayoutDirty, this); this._doLayoutDirty(); - }, + } - _childRemoved: function (child) { + private _childRemoved (child) { + child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this); child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this); child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this); child.off('active-in-hierarchy-changed', this._doLayoutDirty, this); this._doLayoutDirty(); - }, + } - _resized: function () { + private _resized () { this._layoutSize = this.node.getContentSize(); this._doLayoutDirty(); - }, + } - _doLayoutHorizontally: function (baseWidth, rowBreak, fnPositionY, applyChildren) { - var layoutAnchor = this.node.getAnchorPoint(); - var children = this.node.children; + private _doLayoutHorizontally (baseWidth, rowBreak, fnPositionY, applyChildren) { + const layoutAnchor = this.node.getAnchorPoint(); + const children = this.node.children; - var sign = 1; - var paddingX = this.paddingLeft; - var leftBoundaryOfLayout = -layoutAnchor.x * baseWidth; + let sign = 1; + let paddingX = this.paddingLeft; + let leftBoundaryOfLayout = -layoutAnchor.x * baseWidth; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * baseWidth; paddingX = this.paddingRight; } - var nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX; - var rowMaxHeight = 0; - var tempMaxHeight = 0; - var secondMaxHeight = 0; - var row = 0; - var containerResizeBoundary = 0; + let nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX; + let rowMaxHeight = 0; + let tempMaxHeight = 0; + let secondMaxHeight = 0; + let row = 0; + let containerResizeBoundary = 0; - var maxHeightChildAnchorY = 0; + let maxHeightChildAnchorY = 0; + + let activeChildCount = 0; + for (const child of children) { - var activeChildCount = 0; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; if (child.activeInHierarchy) { activeChildCount++; } } - var newChildWidth = this.cellSize.width; + let newChildWidth = this.cellSize.width; if (this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN) { newChildWidth = (baseWidth - (this.paddingLeft + this.paddingRight) - (activeChildCount - 1) * this.spacingX) / activeChildCount; } - for (var i = 0; i < children.length; ++i) { - var child = children[i]; - let childScaleX = Math.abs(child.scaleX); - let childScaleY = Math.abs(child.scaleY); + for (const child of children) { + + const childScaleX = this._getUsedScaleValue(child.scaleX); + const childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) { continue; } - //for resizing children + // for resizing children if (this._resize === ResizeMode.CHILDREN) { child.width = newChildWidth / childScaleX; if (this.type === Type.GRID) { @@ -550,9 +634,9 @@ var Layout = cc.Class({ } } - var anchorX = child.anchorX; - var childBoundingBoxWidth = child.width * childScaleX; - var childBoundingBoxHeight = child.height * childScaleY; + let anchorX = child.anchorX; + const childBoundingBoxWidth = child.width * childScaleX; + const childBoundingBoxHeight = child.height * childScaleY; if (secondMaxHeight > tempMaxHeight) { tempMaxHeight = secondMaxHeight; @@ -568,12 +652,12 @@ var Layout = cc.Class({ anchorX = 1 - child.anchorX; } nextX = nextX + sign * anchorX * childBoundingBoxWidth + sign * this.spacingX; - var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth; + const rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth; if (rowBreak) { - var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft); - var leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; - var rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth; + const rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft); + const leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth; + const rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth; if (leftToRightRowBreak || rightToLeftRowBreak) { @@ -583,8 +667,7 @@ var Layout = cc.Class({ } rowMaxHeight += secondMaxHeight; secondMaxHeight = tempMaxHeight; - } - else { + } else { rowMaxHeight += tempMaxHeight; secondMaxHeight = childBoundingBoxHeight; tempMaxHeight = 0; @@ -594,16 +677,16 @@ var Layout = cc.Class({ } } - var finalPositionY = fnPositionY(child, rowMaxHeight, row); + const finalPositionY = fnPositionY(child, rowMaxHeight, row); if (baseWidth >= (childBoundingBoxWidth + this.paddingLeft + this.paddingRight)) { if (applyChildren) { child.setPosition(cc.v2(nextX, finalPositionY)); } } - var signX = 1; - var tempFinalPositionY; - var topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight; + let signX = 1; + let tempFinalPositionY; + const topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { containerResizeBoundary = containerResizeBoundary || this.node._contentSize.height; @@ -612,8 +695,7 @@ var Layout = cc.Class({ if (tempFinalPositionY < containerResizeBoundary) { containerResizeBoundary = tempFinalPositionY; } - } - else { + } else { containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.height; tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingTop); if (tempFinalPositionY > containerResizeBoundary) { @@ -625,71 +707,68 @@ var Layout = cc.Class({ } return containerResizeBoundary; - }, + } - _getVerticalBaseHeight: function (children) { - var newHeight = 0; - var activeChildCount = 0; + private _getVerticalBaseHeight (children) { + let newHeight = 0; + let activeChildCount = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + for (const child of children) { if (child.activeInHierarchy) { activeChildCount++; - newHeight += child.height * Math.abs(child.scaleY); + newHeight += child.height * this._getUsedScaleValue(child.scaleY); } } newHeight += (activeChildCount - 1) * this.spacingY + this.paddingBottom + this.paddingTop; - } - else { + } else { newHeight = this.node.getContentSize().height; } return newHeight; - }, + } - _doLayoutVertically: function (baseHeight, columnBreak, fnPositionX, applyChildren) { - var layoutAnchor = this.node.getAnchorPoint(); - var children = this.node.children; + private _doLayoutVertically (baseHeight, columnBreak, fnPositionX, applyChildren) { + const layoutAnchor = this.node.getAnchorPoint(); + const children = this.node.children; - var sign = 1; - var paddingY = this.paddingBottom; - var bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight; + let sign = 1; + let paddingY = this.paddingBottom; + let bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * baseHeight; paddingY = this.paddingTop; } - var nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY; - var columnMaxWidth = 0; - var tempMaxWidth = 0; - var secondMaxWidth = 0; - var column = 0; - var containerResizeBoundary = 0; - var maxWidthChildAnchorX = 0; + let nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY; + let columnMaxWidth = 0; + let tempMaxWidth = 0; + let secondMaxWidth = 0; + let column = 0; + let containerResizeBoundary = 0; + let maxWidthChildAnchorX = 0; - var activeChildCount = 0; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + let activeChildCount = 0; + for (const child of children) { if (child.activeInHierarchy) { activeChildCount++; } } - var newChildHeight = this.cellSize.height; + let newChildHeight = this.cellSize.height; if (this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN) { newChildHeight = (baseHeight - (this.paddingTop + this.paddingBottom) - (activeChildCount - 1) * this.spacingY) / activeChildCount; } - for (var i = 0; i < children.length; ++i) { - var child = children[i]; - let childScaleX = Math.abs(child.scaleX); - let childScaleY = Math.abs(child.scaleY); + for (const child of children) { + + const childScaleX = this._getUsedScaleValue(child.scaleX); + const childScaleY = this._getUsedScaleValue(child.scaleY); if (!child.activeInHierarchy) { continue; } - //for resizing children + // for resizing children if (this.resizeMode === ResizeMode.CHILDREN) { child.height = newChildHeight / childScaleY; if (this.type === Type.GRID) { @@ -697,9 +776,9 @@ var Layout = cc.Class({ } } - var anchorY = child.anchorY; - var childBoundingBoxWidth = child.width * childScaleX; - var childBoundingBoxHeight = child.height * childScaleY; + let anchorY = child.anchorY; + const childBoundingBoxWidth = child.width * childScaleX; + const childBoundingBoxHeight = child.height * childScaleY; if (secondMaxWidth > tempMaxWidth) { tempMaxWidth = secondMaxWidth; @@ -715,12 +794,12 @@ var Layout = cc.Class({ anchorY = 1 - child.anchorY; } nextY = nextY + sign * anchorY * childBoundingBoxHeight + sign * this.spacingY; - var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight; + const topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight; if (columnBreak) { - var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom); - var bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; - var topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight; + const columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom); + const bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight; + const topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight; if (bottomToTopColumnBreak || topToBottomColumnBreak) { if (childBoundingBoxWidth >= tempMaxWidth) { @@ -729,8 +808,7 @@ var Layout = cc.Class({ } columnMaxWidth += secondMaxWidth; secondMaxWidth = tempMaxWidth; - } - else { + } else { columnMaxWidth += tempMaxWidth; secondMaxWidth = childBoundingBoxWidth; tempMaxWidth = 0; @@ -740,17 +818,17 @@ var Layout = cc.Class({ } } - var finalPositionX = fnPositionX(child, columnMaxWidth, column); + const finalPositionX = fnPositionX(child, columnMaxWidth, column); if (baseHeight >= (childBoundingBoxHeight + (this.paddingTop + this.paddingBottom))) { if (applyChildren) { child.setPosition(cc.v2(finalPositionX, nextY)); } } - var signX = 1; - var tempFinalPositionX; - //when the item is the last column break item, the tempMaxWidth will be 0. - var rightMarign = (tempMaxWidth === 0) ? childBoundingBoxWidth : tempMaxWidth; + let signX = 1; + let tempFinalPositionX; + // when the item is the last column break item, the tempMaxWidth will be 0. + const rightMarign = (tempMaxWidth === 0) ? childBoundingBoxWidth : tempMaxWidth; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { signX = -1; @@ -759,8 +837,7 @@ var Layout = cc.Class({ if (tempFinalPositionX < containerResizeBoundary) { containerResizeBoundary = tempFinalPositionX; } - } - else { + } else { containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.width; tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingRight); if (tempFinalPositionX > containerResizeBoundary) { @@ -773,66 +850,67 @@ var Layout = cc.Class({ } return containerResizeBoundary; - }, + } - _doLayoutBasic: function () { - var children = this.node.children; + private _doLayoutBasic () { + const children = this.node.children; - var allChildrenBoundingBox = null; + let allChildrenBoundingBox = null; - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + for (const child of children) { if (child.activeInHierarchy) { if (!allChildrenBoundingBox) { allChildrenBoundingBox = child.getBoundingBoxToWorld(); } else { - allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld()); + // allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld()); } } } if (allChildrenBoundingBox) { - var leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); + let leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y)); leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this.paddingLeft, leftBottomInParentSpace.y - this.paddingBottom); - var rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, - allChildrenBoundingBox.y + allChildrenBoundingBox.height)); + let rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width, + allChildrenBoundingBox.y + allChildrenBoundingBox.height)); rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this.paddingRight, rightTopInParentSpace.y + this.paddingTop); - var newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), - parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); + const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), + parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); - var layoutPosition = this.node.getPosition(); - var newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width; - var newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height; - var newAnchor = cc.v2(parseFloat(newAnchorX.toFixed(2)), parseFloat(newAnchorY.toFixed(2))); - - this.node.setAnchorPoint(newAnchor); + const layoutPosition = this.node.getPosition(); + if (newSize.width !== 0) { + const newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width; + this.node.anchorX = parseFloat(newAnchorX.toFixed(2)); + } + if (newSize.height !== 0) { + const newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height; + this.node.anchorY = parseFloat(newAnchorY.toFixed(2)); + } this.node.setContentSize(newSize); } - }, + } - _doLayoutGridAxisHorizontal: function (layoutAnchor, layoutSize) { - var baseWidth = layoutSize.width; + private _doLayoutGridAxisHorizontal (layoutAnchor, layoutSize) { + const baseWidth = layoutSize.width; - var sign = 1; - var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; - var paddingY = this.paddingBottom; + let sign = 1; + let bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height; + let paddingY = this.paddingBottom; if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) { sign = -1; bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height; paddingY = this.paddingTop; } - var fnPositionY = function (child, topOffset, row) { - return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * Math.abs(child.scaleY) + paddingY + row * this.spacingY); + const fnPositionY = function (child, topOffset, row) { + return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this.spacingY); }.bind(this); - - var newHeight = 0; + let newHeight = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - //calculate the new height of container, it won't change the position of it's children - var boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false); + // calculate the new height of container, it won't change the position of it's children + const boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false); newHeight = bottomBoundaryOfLayout - boundary; if (newHeight < 0) { newHeight *= -1; @@ -851,27 +929,27 @@ var Layout = cc.Class({ if (this.resizeMode === ResizeMode.CONTAINER) { this.node.setContentSize(baseWidth, newHeight); } - }, + } - _doLayoutGridAxisVertical: function (layoutAnchor, layoutSize) { - var baseHeight = layoutSize.height; + private _doLayoutGridAxisVertical (layoutAnchor, layoutSize) { + const baseHeight = layoutSize.height; - var sign = 1; - var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; - var paddingX = this.paddingLeft; + let sign = 1; + let leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width; + let paddingX = this.paddingLeft; if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) { sign = -1; leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width; paddingX = this.paddingRight; } - var fnPositionX = function (child, leftOffset, column) { - return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * Math.abs(child.scaleX) + paddingX + column * this.spacingX); + const fnPositionX = function (child, leftOffset, column) { + return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this.spacingX); }.bind(this); - var newWidth = 0; + let newWidth = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - var boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false); + const boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false); newWidth = leftBoundaryOfLayout - boundary; if (newWidth < 0) { newWidth *= -1; @@ -890,74 +968,72 @@ var Layout = cc.Class({ if (this.resizeMode === ResizeMode.CONTAINER) { this.node.setContentSize(newWidth, baseHeight); } - }, + } - _doLayoutGrid: function () { - var layoutAnchor = this.node.getAnchorPoint(); - var layoutSize = this.node.getContentSize(); + private _doLayoutGrid () { + const layoutAnchor = this.node.getAnchorPoint(); + const layoutSize = this.node.getContentSize(); if (this.startAxis === AxisDirection.HORIZONTAL) { this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize); - } - else if (this.startAxis === AxisDirection.VERTICAL) { + } else if (this.startAxis === AxisDirection.VERTICAL) { this._doLayoutGridAxisVertical(layoutAnchor, layoutSize); } - }, + } - _getHorizontalBaseWidth: function (children) { - var newWidth = 0; - var activeChildCount = 0; + private _getHorizontalBaseWidth (children) { + let newWidth = 0; + let activeChildCount = 0; if (this.resizeMode === ResizeMode.CONTAINER) { - for (var i = 0; i < children.length; ++i) { - var child = children[i]; + for (const child of children) { if (child.activeInHierarchy) { activeChildCount++; - newWidth += child.width * Math.abs(child.scaleX); + newWidth += child.width * this._getUsedScaleValue(child.scaleX); } } newWidth += (activeChildCount - 1) * this.spacingX + this.paddingLeft + this.paddingRight; - } - else { + } else { newWidth = this.node.getContentSize().width; } return newWidth; - }, + } - _doLayout: function () { + private _doLayout () { if (this.type === Type.HORIZONTAL) { - var newWidth = this._getHorizontalBaseWidth(this.node.children); + const newWidth = this._getHorizontalBaseWidth(this.node.children); - var fnPositionY = function (child) { + const fnPositionY = (child) => { return child.y; }; this._doLayoutHorizontally(newWidth, false, fnPositionY, true); this.node.width = newWidth; - } - else if (this.type === Type.VERTICAL) { - var newHeight = this._getVerticalBaseHeight(this.node.children); + } else if (this.type === Type.VERTICAL) { + const newHeight = this._getVerticalBaseHeight(this.node.children); - var fnPositionX = function (child) { + const fnPositionX = (child) => { return child.x; }; this._doLayoutVertically(newHeight, false, fnPositionX, true); this.node.height = newHeight; - } - else if (this.type === Type.NONE) { + } else if (this.type === Type.NONE) { if (this.resizeMode === ResizeMode.CONTAINER) { this._doLayoutBasic(); } - } - else if (this.type === Type.GRID) { + } else if (this.type === Type.GRID) { this._doLayoutGrid(); } - }, + } + + private _getUsedScaleValue (value) { + return this.affectedByScale ? Math.abs(value) : 1; + } /** * !#en Perform the layout update @@ -972,31 +1048,19 @@ var Layout = cc.Class({ * layout.updateLayout(); * cc.log(childNode.x); // changed */ - updateLayout: function () { + public updateLayout () { if (this._layoutDirty && this.node.children.length > 0) { this._doLayout(); this._layoutDirty = false; } } -}); - -/** - * !#en The padding of layout, it effects the layout in four direction. - * !#zh 容器内边距,该属性会在四个布局方向上生效。 - * @property {Number} padding - */ -Object.defineProperty(Layout.prototype, "padding", { - get: function () { - cc.warnID(4100); - return this.paddingLeft; - }, - set: function (value) { - this._N$padding = value; - - this._migratePaddingData(); - this._doLayoutDirty(); + private _doLayoutDirty () { + this._layoutDirty = true; } -}); -cc.Layout = module.exports = Layout; + private _doScaleDirty () { + this._layoutDirty = this._layoutDirty || this.affectedByScale; + } + +} diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/3d/ui/components/progress-bar-component.ts index 604d3cf3cc..019653a675 100644 --- a/cocos/3d/ui/components/progress-bar-component.ts +++ b/cocos/3d/ui/components/progress-bar-component.ts @@ -25,11 +25,11 @@ ****************************************************************************/ import { Component} from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { clamp01 } from '../../../core/utils/misc'; -import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; +import { Enum } from '../../../core/value-types'; import { SpriteComponent } from './sprite-component'; - /** * !#en Enum for ProgressBar mode * !#zh 进度条模式 @@ -55,7 +55,9 @@ enum Mode { * @property {Number} FILLED */ FILLED = 2, -}; +} + +Enum(Mode); /** * !#en @@ -84,15 +86,6 @@ enum Mode { @menu('UI/ProgressBar') // @executeInEditMode export class ProgressBarComponent extends Component { - @property - _barSprite: SpriteComponent | null = null; - @property - _mode: number = Mode.HORIZONTAL; - _N$totalLength: number = 1; - @property - _progress: number = 0.1; - @property - _reverse: boolean = false; /** * !#en The targeted Sprite which will be changed progressively. @@ -100,15 +93,15 @@ export class ProgressBarComponent extends Component { * @property {Sprite} barSprite */ @property({ - type: SpriteComponent + type: SpriteComponent, }) - get barSprite() { + get barSprite () { return this._barSprite; } - set barSprite(value: SpriteComponent) { + set barSprite (value: SpriteComponent) { if (this._barSprite === value) { - return + return; } this._barSprite = value; @@ -121,23 +114,23 @@ export class ProgressBarComponent extends Component { * @property {ProgressBar.Mode} mode */ @property({ - type: Mode + type: Mode, }) - get mode() { + get mode () { return this._mode; } - set mode(value: number) { + set mode (value: Mode) { if (this._mode === value) { return; } this._mode = value; if (this._barSprite) { - var entity = this._barSprite.node; - if (!entity) return; + const entity = this._barSprite.node; + if (!entity) { return; } - var entitySize = entity.getContentSize(); + const entitySize = entity.getContentSize(); if (this._mode === Mode.HORIZONTAL) { this.totalLength = entitySize.width; } else if (this._mode === Mode.VERTICAL) { @@ -154,11 +147,11 @@ export class ProgressBarComponent extends Component { * @property {Number} totalLength - range[[0, Number.MAX_VALUE]] */ @property - get totalLength() { + get totalLength () { return this._N$totalLength; } - set totalLength(value: number) { + set totalLength (value: number) { if (this._mode === Mode.FILLED) { value = clamp01(value); } @@ -172,17 +165,16 @@ export class ProgressBarComponent extends Component { * @property {Number} progress */ @property({ - default: 0.1, range: [0, 1, 0.1], - slide: true + slide: true, }) - get progress() { + get progress () { return this._progress; } - set progress(value: number) { + set progress (value: number) { if (this._progress === value) { - return + return; } this._progress = value; @@ -195,11 +187,11 @@ export class ProgressBarComponent extends Component { * @property {Boolean} reverse */ @property - get reverse() { + get reverse () { return this._reverse; } - set reverse(value: boolean) { + set reverse (value: boolean) { if (this._reverse === value) { return; } @@ -211,17 +203,26 @@ export class ProgressBarComponent extends Component { this._updateBarStatus(); } - static Mode = Mode; + public static Mode = Mode; + @property + private _barSprite: SpriteComponent | null = null; + @property + private _mode: number = Mode.HORIZONTAL; + private _N$totalLength: number = 1; + @property + private _progress: number = 0.1; + @property + private _reverse: boolean = false; - _initBarSprite() { + public _initBarSprite () { if (this._barSprite) { - var entity = this._barSprite.node; - if (!entity) return; + const entity = this._barSprite.node; + if (!entity) { return; } - var nodeSize = this.node.getContentSize(); - var nodeAnchor = this.node.getAnchorPoint(); + const nodeSize = this.node.getContentSize(); + const nodeAnchor = this.node.getAnchorPoint(); - var entitySize = entity.getContentSize(); + const entitySize = entity.getContentSize(); if (entity.parent === this.node) { this.node.setContentSize(entitySize); @@ -231,41 +232,39 @@ export class ProgressBarComponent extends Component { this._mode = Mode.FILLED; } - var barSpriteSize = entity.getContentSize(); + const barSpriteSize = entity.getContentSize(); if (this._mode === Mode.HORIZONTAL) { this.totalLength = barSpriteSize.width; - } - else if (this._mode === Mode.VERTICAL) { + } else if (this._mode === Mode.VERTICAL) { this.totalLength = barSpriteSize.height; - } - else { + } else { this.totalLength = this._barSprite.fillRange; } if (entity.parent === this.node) { - var x = - nodeSize.width * nodeAnchor.x; - var y = 0; + const x = - nodeSize.width * nodeAnchor.x; + const y = 0; entity.setPosition(cc.v2(x, y)); } } } - _updateBarStatus() { + public _updateBarStatus () { if (this._barSprite) { - var entity = this._barSprite.node; + const entity = this._barSprite.node; - if (!entity) return; + if (!entity) { return; } - var entityAnchorPoint = entity.getAnchorPoint(); - var entitySize = entity.getContentSize(); - var entityPosition = entity.getPosition(); + const entityAnchorPoint = entity.getAnchorPoint(); + const entitySize = entity.getContentSize(); + const entityPosition = entity.getPosition(); - var anchorPoint = cc.v2(0, 0.5); - var progress = clamp01(this._progress); - var actualLenth = this.totalLength * progress; - var finalContentSize; - var totalWidth; - var totalHeight; + let anchorPoint = cc.v2(0, 0.5); + const progress = clamp01(this._progress); + let actualLenth = this.totalLength * progress; + let finalContentSize; + let totalWidth; + let totalHeight; switch (this._mode) { case Mode.HORIZONTAL: if (this._reverse) { @@ -287,7 +286,7 @@ export class ProgressBarComponent extends Component { break; } - //handling filled mode + // handling filled mode if (this._mode === Mode.FILLED) { if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) { cc.warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!'); @@ -300,9 +299,9 @@ export class ProgressBarComponent extends Component { } else { if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) { - var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; - var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; - var finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); + const anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; + const anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; + const finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entity.getPosition().z); @@ -315,4 +314,3 @@ export class ProgressBarComponent extends Component { } } } - diff --git a/cocos/2d/ui/CCScrollBar.js b/cocos/3d/ui/components/scroll-bar-component.ts similarity index 76% rename from cocos/2d/ui/CCScrollBar.js rename to cocos/3d/ui/components/scroll-bar-component.ts index abbf584406..2910c625de 100644 --- a/cocos/2d/ui/CCScrollBar.js +++ b/cocos/3d/ui/components/scroll-bar-component.ts @@ -24,9 +24,12 @@ THE SOFTWARE. ****************************************************************************/ -import Component from '../../components/CCComponent'; -import misc from '../../core/utils/misc'; -import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../core/data/class-decorator'; +import { Component} from '../../../components/component'; +import { clamp01 } from '../../../core/utils/misc'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { UIRenderComponent } from './ui-render-component'; +import { Vec2 } from '../../../core/value-types'; +import { Node } from '../../../scene-graph/node'; var GETTINGSHORTERFACTOR = 20; @@ -55,41 +58,43 @@ var Direction = cc.Enum({ */ @ccclass('cc.ScrollBarComponent') @executionOrder(100) -@menu('UI/ScrollBar') -// @executeInEditMode -export default class ScrollBarComponent extends Component { +@executeInEditMode +export class ScrollBarComponent extends Component { @property - _scrollView = null; - _touching = false; - _autoHideRemainingTime = 0; + private _scrollView: Component | null = null; @property - _handle = null; + private _handle: UIRenderComponent | null = null; @property - _direction = Direction.HORIZONTAL; + private _direction = Direction.HORIZONTAL; @property - _enableAutoHide = false; + private _enableAutoHide = false; @property - _autoHideTime = 1.0; + private _autoHideTime = 1.0; + + private _touching = false; + private _opacity = 0; + private _autoHideRemainingTime = 0; + /** * !#en The "handle" part of the scrollbar. * !#zh 作为当前滚动区域位置显示的滑块 Sprite。 * @property {Sprite} handle */ @property({ - type: cc.Node + type: UIRenderComponent }) get handle() { return this._handle; } - set handle(value) { - value = value.getComponent(cc.RenderComponent); + set handle(value: UIRenderComponent) { if (this._handle === value) { return } this._handle = value; - this._onScroll(cc.v2(0, 0)); + this.onScroll(cc.v2(0, 0)); } + /** * !#en The direction of scrollbar. * !#zh ScrollBar 的滚动方向。 @@ -108,7 +113,7 @@ export default class ScrollBarComponent extends Component { } this._direction = value; - this._onScroll(cc.v2(0, 0)); + this.onScroll(cc.v2(0, 0)); } /** @@ -126,6 +131,9 @@ export default class ScrollBarComponent extends Component { } this._enableAutoHide = value; + if(this._enableAutoHide){ + this._setOpacity(0); + } } /** @@ -152,24 +160,60 @@ export default class ScrollBarComponent extends Component { static Direction = Direction; - setTargetScrollView(scrollView) { - this._scrollView = scrollView; + protected onEnable() { + let renderComp = this.node.getComponent(UIRenderComponent); + if (renderComp) { + this._opacity = renderComp.color.a; + } } - _convertToScrollViewSpace(content) { - var worldSpacePos = content.convertToWorldSpace(cc.v2(0, 0)); - var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos); - return scrollViewSpacePos; + protected start() { + if (this._enableAutoHide) { + this._setOpacity(0); + } } - // _setOpacity(opacity) { - // if (this._handle) { - // this.node.opacity = opacity; - // this._handle.node.opacity = opacity; - // } - // } + public hide() { + this._autoHideRemainingTime = 0; + this._setOpacity(0); + } - _onScroll(outOfBoundary) { + public show() { + this._autoHideRemainingTime = this._autoHideTime; + this._setOpacity(this._opacity); + } + + protected update(dt) { + this._processAutoHide(dt); + } + + private _convertToScrollViewSpace(content: Node) { + return new Vec2(0, 0); + if (!this._scrollView){ + return; + } + + // TODO: + // var worldSpacePos = content.convertToWorldSpace(new Vec2(0, 0)); + // var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos); + // return scrollViewSpacePos; + } + + private _setOpacity(opacity: number) { + if (this._handle) { + let renderComp = this.node.getComponent(UIRenderComponent); + if (renderComp){ + renderComp.color.a = opacity; + } + + renderComp = this._handle.getComponent(UIRenderComponent); + if (renderComp) { + renderComp.color.a = opacity; + } + } + } + + public onScroll(outOfBoundary) { if (this._scrollView) { var content = this._scrollView.content; @@ -184,7 +228,7 @@ export default class ScrollBarComponent extends Component { if (this._enableAutoHide) { this._autoHideRemainingTime = this._autoHideTime; - this._setOpacity(this._opacity); + // this._setOpacity(this._opacity); } var contentMeasure = 0; @@ -218,7 +262,12 @@ export default class ScrollBarComponent extends Component { } } - _updateHanlderPosition(position) { + // FIXME: use ScrollViewComponent + public setScrollView(scrollView: Component) { + this._scrollView = scrollView; + } + + private _updateHanlderPosition(position) { if (this._handle) { var oldPosition = this._fixupHandlerPosition(); @@ -226,7 +275,11 @@ export default class ScrollBarComponent extends Component { } } - _fixupHandlerPosition() { + private _fixupHandlerPosition() { + if(!this._handle){ + return; + } + var barSize = this.node.getContentSize(); var barAnchor = this.node.getAnchorPoint(); var handleSize = this._handle.node.getContentSize(); @@ -247,14 +300,14 @@ export default class ScrollBarComponent extends Component { return fixupPosition; } - _onTouchBegan() { + public onTouchBegan() { if (!this._enableAutoHide) { return; } this._touching = true; } - _conditionalDisableScrollBar(contentSize, scrollViewSize) { + private _conditionalDisableScrollBar(contentSize, scrollViewSize) { if (contentSize.width <= scrollViewSize.width && this._direction === Direction.HORIZONTAL) { return true; @@ -267,7 +320,7 @@ export default class ScrollBarComponent extends Component { return false; } - _onTouchEnded() { + public onTouchEnded() { if (!this._enableAutoHide) { return; } @@ -294,7 +347,7 @@ export default class ScrollBarComponent extends Component { this._autoHideRemainingTime = this._autoHideTime; } - _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { + private _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) { var denominatorValue = contentMeasure; if (outOfBoundary) { denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR; @@ -304,7 +357,7 @@ export default class ScrollBarComponent extends Component { return handleNodeMeasure * lengthRation; } - _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { + private _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) { var denominatorValue = contentMeasure - scrollViewMeasure; if (outOfBoundary) { denominatorValue += Math.abs(outOfBoundary); @@ -313,7 +366,7 @@ export default class ScrollBarComponent extends Component { var positionRatio = 0; if (denominatorValue) { positionRatio = contentPosition / denominatorValue; - positionRatio = misc.clamp01(positionRatio); + positionRatio = clamp01(positionRatio); } var position = (handleNodeMeasure - actualLenth) * positionRatio; @@ -324,7 +377,7 @@ export default class ScrollBarComponent extends Component { } } - _updateLength(length) { + private _updateLength(length) { if (this._handle) { var handleNode = this._handle.node; var handleNodeSize = handleNode.getContentSize(); @@ -337,7 +390,7 @@ export default class ScrollBarComponent extends Component { } } - _processAutoHide(deltaTime) { + private _processAutoHide(deltaTime) { if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) { return; } else if (this._touching) { @@ -348,28 +401,8 @@ export default class ScrollBarComponent extends Component { this._autoHideRemainingTime -= deltaTime; if (this._autoHideRemainingTime <= this._autoHideTime) { this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); - var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime); - this._setOpacity(opacity); + // var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime); + // this._setOpacity(opacity); } } - - start() { - if (this._enableAutoHide) { - this._setOpacity(0); - } - } - - hide() { - this._autoHideRemainingTime = 0; - this._setOpacity(0); - } - - show() { - this._autoHideRemainingTime = this._autoHideTime; - this._setOpacity(this._opacity); - } - - update(dt) { - this._processAutoHide(dt); - } } diff --git a/cocos/2d/ui/CCScrollView.js b/cocos/3d/ui/components/scroll-view-component.ts similarity index 70% rename from cocos/2d/ui/CCScrollView.js rename to cocos/3d/ui/components/scroll-view-component.ts index 8c32b746b0..8c96d96499 100644 --- a/cocos/2d/ui/CCScrollView.js +++ b/cocos/3d/ui/components/scroll-view-component.ts @@ -23,20 +23,28 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +import { Node } from '../../../scene-graph/node'; +import { Enum, Vec2, Vec3, Size } from '../../../core/value-types'; +import { ViewGroupComponent } from './view-group-component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ScrollBarComponent } from './scroll-bar-component'; +import ComponentEventHandler from '../../../components/CCComponentEventHandler'; +import { LayoutComponent } from './layout-component'; -const NodeEvent = require('../CCNode').EventType; +const NodeEvent = Node.EventType; const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; const EPSILON = 1e-4; const MOVEMENT_FACTOR = 0.7; +const _vec3Zero = new Vec3(); -let quintEaseOut = function(time) { +let quintEaseOut = function (time) { time -= 1; return (time * time * time * time * time + 1); }; -let getTimeInMilliseconds = function() { +let getTimeInMilliseconds = function () { let currentTime = new Date(); return currentTime.getMilliseconds(); }; @@ -46,100 +54,102 @@ let getTimeInMilliseconds = function() { * !#zh 滚动视图事件类型 * @enum ScrollView.EventType */ -const EventType = cc.Enum({ +enum EventType { /** * !#en The event emmitted when ScrollView scroll to the top boundary of inner container * !#zh 滚动视图滚动到顶部边界事件 * @property {Number} SCROLL_TO_TOP */ - SCROLL_TO_TOP : 0, + SCROLL_TO_TOP = 0, /** * !#en The event emmitted when ScrollView scroll to the bottom boundary of inner container * !#zh 滚动视图滚动到底部边界事件 * @property {Number} SCROLL_TO_BOTTOM */ - SCROLL_TO_BOTTOM : 1, + SCROLL_TO_BOTTOM = 1, /** * !#en The event emmitted when ScrollView scroll to the left boundary of inner container * !#zh 滚动视图滚动到左边界事件 * @property {Number} SCROLL_TO_LEFT */ - SCROLL_TO_LEFT : 2, + SCROLL_TO_LEFT = 2, /** * !#en The event emmitted when ScrollView scroll to the right boundary of inner container * !#zh 滚动视图滚动到右边界事件 * @property {Number} SCROLL_TO_RIGHT */ - SCROLL_TO_RIGHT : 3, + SCROLL_TO_RIGHT = 3, /** * !#en The event emmitted when ScrollView is scrolling * !#zh 滚动视图正在滚动时发出的事件 * @property {Number} SCROLLING */ - SCROLLING : 4, + SCROLLING = 4, /** * !#en The event emmitted when ScrollView scroll to the top boundary of inner container and start bounce * !#zh 滚动视图滚动到顶部边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_TOP */ - BOUNCE_TOP : 5, + BOUNCE_TOP = 5, /** * !#en The event emmitted when ScrollView scroll to the bottom boundary of inner container and start bounce * !#zh 滚动视图滚动到底部边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_BOTTOM */ - BOUNCE_BOTTOM : 6, + BOUNCE_BOTTOM = 6, /** * !#en The event emmitted when ScrollView scroll to the left boundary of inner container and start bounce * !#zh 滚动视图滚动到左边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_LEFT */ - BOUNCE_LEFT : 7, + BOUNCE_LEFT = 7, /** * !#en The event emmitted when ScrollView scroll to the right boundary of inner container and start bounce * !#zh 滚动视图滚动到右边界并且开始回弹时发出的事件 * @property {Number} BOUNCE_RIGHT */ - BOUNCE_RIGHT : 8, + BOUNCE_RIGHT = 8, /** * !#en The event emmitted when ScrollView auto scroll ended * !#zh 滚动视图滚动结束的时候发出的事件 * @property {Number} SCROLL_ENDED */ - SCROLL_ENDED : 9, + SCROLL_ENDED = 9, /** * !#en The event emmitted when user release the touch * !#zh 当用户松手的时候会发出一个事件 * @property {Number} TOUCH_UP */ - TOUCH_UP : 10, + TOUCH_UP = 10, /** * !#en The event emmitted when ScrollView auto scroll ended with a threshold * !#zh 滚动视图自动滚动快要结束的时候发出的事件 * @property {Number} AUTOSCROLL_ENDED_WITH_THRESHOLD */ - AUTOSCROLL_ENDED_WITH_THRESHOLD: 11, + AUTOSCROLL_ENDED_WITH_THRESHOLD = 11, /** * !#en The event emmitted when ScrollView scroll began * !#zh 滚动视图滚动开始时发出的事件 * @property {Number} SCROLL_BEGAN */ - SCROLL_BEGAN: 12 -}); + SCROLL_BEGAN = 12 +} + +Enum(EventType); const eventMap = { - 'scroll-to-top' : EventType.SCROLL_TO_TOP, + 'scroll-to-top': EventType.SCROLL_TO_TOP, 'scroll-to-bottom': EventType.SCROLL_TO_BOTTOM, - 'scroll-to-left' : EventType.SCROLL_TO_LEFT, - 'scroll-to-right' : EventType.SCROLL_TO_RIGHT, - 'scrolling' : EventType.SCROLLING, - 'bounce-bottom' : EventType.BOUNCE_BOTTOM, - 'bounce-left' : EventType.BOUNCE_LEFT, - 'bounce-right' : EventType.BOUNCE_RIGHT, - 'bounce-top' : EventType.BOUNCE_TOP, + 'scroll-to-left': EventType.SCROLL_TO_LEFT, + 'scroll-to-right': EventType.SCROLL_TO_RIGHT, + 'scrolling': EventType.SCROLLING, + 'bounce-bottom': EventType.BOUNCE_BOTTOM, + 'bounce-left': EventType.BOUNCE_LEFT, + 'bounce-right': EventType.BOUNCE_RIGHT, + 'bounce-top': EventType.BOUNCE_TOP, 'scroll-ended': EventType.SCROLL_ENDED, - 'touch-up' : EventType.TOUCH_UP, - 'scroll-ended-with-threshold' : EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD, + 'touch-up': EventType.TOUCH_UP, + 'scroll-ended-with-threshold': EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD, 'scroll-began': EventType.SCROLL_BEGAN }; @@ -153,197 +163,190 @@ const eventMap = { * @class ScrollView * @extends Component */ -let ScrollView = cc.Class({ - name: 'cc.ScrollView', - extends: require('./CCViewGroup'), - editor: CC_EDITOR && { - menu: 'i18n:MAIN_MENU.component.ui/ScrollView', - help: 'i18n:COMPONENT.help_url.scrollview', - executeInEditMode: false, - }, +@ccclass('cc.ScrollViewComponent') +@executionOrder(100) +@menu('UI/ScrollView') +@executeInEditMode +export class ScrollViewComponent extends ViewGroupComponent { + /** + * !#en Enable horizontal scroll. + * !#zh 是否开启水平滚动。 + * @property {Boolean} horizontal + */ + @property + public horizontal = true; - ctor () { - this._topBoundary = 0; - this._bottomBoundary = 0; - this._leftBoundary = 0; - this._rightBoundary = 0; + /** + * !#en Enable vertical scroll. + * !#zh 是否开启垂直滚动。 + * @property {Boolean} vertical + */ + @property + public vertical = true; - this._touchMoveDisplacements = []; - this._touchMoveTimeDeltas = []; - this._touchMovePreviousTimestamp = 0; - this._touchMoved = false; + /** + * !#en When inertia is set, the content will continue to move when touch ended. + * !#zh 是否开启滚动惯性。 + * @property {Boolean} inertia + */ + @property + public inertia = true; - this._autoScrolling = false; - this._autoScrollAttenuate = false; - this._autoScrollStartPosition = cc.v2(0, 0); - this._autoScrollTargetDelta = cc.v2(0, 0); - this._autoScrollTotalTime = 0; - this._autoScrollAccumulatedTime = 0; - this._autoScrollCurrentlyOutOfBoundary = false; - this._autoScrollBraking = false; - this._autoScrollBrakingStartPosition = cc.v2(0, 0); + /** + * !#en + * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. + * A value of 0 will never stop the movement until it reaches to the boundary of scrollview. + * !#zh + * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 + * @property {Number} brake + */ + @property({ + range: [0, 1, 0.1] + }) + public brake = 0.5; - this._outOfBoundaryAmount = cc.v2(0, 0); - this._outOfBoundaryAmountDirty = true; - this._stopMouseWheel = false; - this._mouseWheelEventElapsedTime = 0.0; - this._isScrollEndedWithThresholdEventFired = false; - //use bit wise operations to indicate the direction - this._scrollEventEmitMask = 0; - this._isBouncing = false; - this._scrolling = false; - }, + /** + * !#en When elastic is set, the content will be bounce back when move out of boundary. + * !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。 + */ + @property + public elastic = true; - properties: { - /** - * !#en This is a reference to the UI element to be scrolled. - * !#zh 可滚动展示内容的节点。 - * @property {Node} content - */ - content: { - default: undefined, - type: cc.Node, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.content', - formerlySerializedAs: 'content', - notify (oldValue) { - this._calculateBoundary(); - } - }, + /** + * !#en The elapse time of bouncing back. A value of 0 will bounce back immediately. + * !#zh 回弹持续的时间,0 表示将立即反弹。 + * @property {Number} bounceDuration + */ + @property({ + range: [1, 10] + }) + public bounceDuration = 1; - /** - * !#en Enable horizontal scroll. - * !#zh 是否开启水平滚动。 - * @property {Boolean} horizontal - */ - horizontal: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.horizontal', - }, + /** + * !#en Scrollview events callback + * !#zh 滚动视图的事件回调函数 + * @property {Component.EventHandler[]} scrollEvents + */ + @property + public scrollEvents: ComponentEventHandler[] = []; - /** - * !#en Enable vertical scroll. - * !#zh 是否开启垂直滚动。 - * @property {Boolean} vertical - */ - vertical: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.vertical', - }, + /** + * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes + * It's set to true by default. + * !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。 + * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 + * @property {Boolean} cancelInnerEvents + */ + @property + public cancelInnerEvents = true; + @property + private _content: Node | null = null; + @property + private _horizontalScrollBar: ScrollBarComponent | null = null; + @property + private _verticalScrollBar: ScrollBarComponent | null = null; - /** - * !#en When inertia is set, the content will continue to move when touch ended. - * !#zh 是否开启滚动惯性。 - * @property {Boolean} inertia - */ - inertia: { - default: true, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.inertia', - }, + private _topBoundary = 0; + private _bottomBoundary = 0; + private _leftBoundary = 0; + private _rightBoundary = 0; - /** - * !#en - * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. - * A value of 0 will never stop the movement until it reaches to the boundary of scrollview. - * !#zh - * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 - * @property {Number} brake - */ - brake: { - default: 0.5, - type: 'Float', - range: [0, 1, 0.1], - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.brake', - }, + private _touchMoveDisplacements: Vec3[] = []; + private _touchMoveTimeDeltas: number[] = []; + private _touchMovePreviousTimestamp = 0; + private _touchMoved = false; - /** - * !#en When elastic is set, the content will be bounce back when move out of boundary. - * !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。 - * @property {Boolean} elastic - */ - elastic: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.elastic', - }, + private _autoScrolling = false; + private _autoScrollAttenuate = false; + private _autoScrollStartPosition = new Vec3(0, 0); + private _autoScrollTargetDelta = new Vec3(0, 0); + private _autoScrollTotalTime = 0; + private _autoScrollAccumulatedTime = 0; + private _autoScrollCurrentlyOutOfBoundary = false; + private _autoScrollBraking = false; + private _autoScrollBrakingStartPosition = new Vec3(0, 0); - /** - * !#en The elapse time of bouncing back. A value of 0 will bounce back immediately. - * !#zh 回弹持续的时间,0 表示将立即反弹。 - * @property {Number} bounceDuration - */ - bounceDuration: { - default: 1, - range: [0, 10], - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.bounceDuration', - }, + private _outOfBoundaryAmount = new Vec3(0, 0); + private _outOfBoundaryAmountDirty = true; + private _stopMouseWheel = false; + private _mouseWheelEventElapsedTime = 0.0; + private _isScrollEndedWithThresholdEventFired = false; + //use bit wise operations to indicate the direction + private _scrollEventEmitMask = 0; + private _isBouncing = false; + private _scrolling = false; + private _contentPos = new Vec3(); - /** - * !#en The horizontal scrollbar reference. - * !#zh 水平滚动的 ScrollBar。 - * @property {Scrollbar} horizontalScrollBar - */ - horizontalScrollBar: { - default: undefined, - type: cc.Scrollbar, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.horizontal_bar', - notify () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.setTargetScrollView(this); - this._updateScrollBar(0); - } - }, - animatable: false - }, - - /** - * !#en The vertical scrollbar reference. - * !#zh 垂直滚动的 ScrollBar。 - * @property {Scrollbar} verticalScrollBar - */ - verticalScrollBar: { - default: undefined, - type: cc.Scrollbar, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.vertical_bar', - notify () { - if (this.verticalScrollBar) { - this.verticalScrollBar.setTargetScrollView(this); - this._updateScrollBar(0); - } - }, - animatable: false - }, - - /** - * !#en Scrollview events callback - * !#zh 滚动视图的事件回调函数 - * @property {Component.EventHandler[]} scrollEvents - */ - scrollEvents: { - default: [], - type: cc.Component.EventHandler, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.scrollEvents' - }, - - /** - * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes - * It's set to true by default. - * !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。 - * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。 - * @property {Boolean} cancelInnerEvents - */ - cancelInnerEvents: { - default: true, - animatable: false, - tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.cancelInnerEvents' + /** + * !#en This is a reference to the UI element to be scrolled. + * !#zh 可滚动展示内容的节点。 + * @property {Node} content + */ + @property({ + type: Node + }) + get content() { + return this._content; + } + set content(value: Node) { + if(this._content === value){ + return; } - }, - statics: { - EventType: EventType, - }, + this._content = value; + this._calculateBoundary(); + } + + /** + * !#en The horizontal scrollbar reference. + * !#zh 水平滚动的 ScrollBar。 + * @property {Scrollbar} horizontalScrollBar + */ + @property({ + type: ScrollBarComponent + }) + get horizontalScrollBar() { + return this._horizontalScrollBar; + } + + set horizontalScrollBar(value: ScrollBarComponent) { + if(this._horizontalScrollBar === value){ + return; + } + + this._horizontalScrollBar = value; + + if (this._horizontalScrollBar) { + this._horizontalScrollBar.setScrollView(this); + this._updateScrollBar(0); + } + } + + /** + * !#en The vertical scrollbar reference. + * !#zh 垂直滚动的 ScrollBar。 + * @property {Scrollbar} verticalScrollBar + */ + @property + get verticalScrollBar() { + return this._verticalScrollBar; + } + + set verticalScrollBar(value: ScrollBarComponent) { + if (this._verticalScrollBar === value) { + return; + } + + this._verticalScrollBar = value; + + if (this._verticalScrollBar) { + this._verticalScrollBar.setScrollView(this); + this._updateScrollBar(0); + } + } + + static EventType = EventType; /** * !#en Scroll the content to the bottom boundary of ScrollView. @@ -356,9 +359,9 @@ let ScrollView = cc.Class({ * // Scroll to the bottom of the view. * scrollView.scrollToBottom(0.1); */ - scrollToBottom (timeInSecond, attenuated) { + scrollToBottom(timeInSecond: number, attenuated: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 0), + anchor: new Vec2(0, 0), applyToHorizontal: false, applyToVertical: true, }); @@ -368,7 +371,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta, true); } - }, + } /** * !#en Scroll the content to the top boundary of ScrollView. @@ -381,9 +384,9 @@ let ScrollView = cc.Class({ * // Scroll to the top of the view. * scrollView.scrollToTop(0.1); */ - scrollToTop (timeInSecond, attenuated) { + scrollToTop(timeInSecond: number, attenuated: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 1), + anchor: new Vec2(0, 1), applyToHorizontal: false, applyToVertical: true, }); @@ -393,7 +396,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the left boundary of ScrollView. @@ -406,9 +409,9 @@ let ScrollView = cc.Class({ * // Scroll to the left of the view. * scrollView.scrollToLeft(0.1); */ - scrollToLeft (timeInSecond, attenuated) { + scrollToLeft(timeInSecond: number, attenuated: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 0), + anchor: new Vec2(0, 0), applyToHorizontal: true, applyToVertical: false, }); @@ -418,7 +421,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the right boundary of ScrollView. @@ -431,9 +434,9 @@ let ScrollView = cc.Class({ * // Scroll to the right of the view. * scrollView.scrollToRight(0.1); */ - scrollToRight (timeInSecond, attenuated) { + scrollToRight(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(1, 0), + anchor: new Vec2(1, 0), applyToHorizontal: true, applyToVertical: false, }); @@ -443,7 +446,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the top left boundary of ScrollView. @@ -456,9 +459,9 @@ let ScrollView = cc.Class({ * // Scroll to the upper left corner of the view. * scrollView.scrollToTopLeft(0.1); */ - scrollToTopLeft (timeInSecond, attenuated) { + scrollToTopLeft(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 1), + anchor: new Vec2(0, 1), applyToHorizontal: true, applyToVertical: true, }); @@ -468,7 +471,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the top right boundary of ScrollView. @@ -481,9 +484,9 @@ let ScrollView = cc.Class({ * // Scroll to the top right corner of the view. * scrollView.scrollToTopRight(0.1); */ - scrollToTopRight (timeInSecond, attenuated) { + scrollToTopRight(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(1, 1), + anchor: new Vec2(1, 1), applyToHorizontal: true, applyToVertical: true, }); @@ -493,7 +496,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the bottom left boundary of ScrollView. @@ -506,9 +509,9 @@ let ScrollView = cc.Class({ * // Scroll to the lower left corner of the view. * scrollView.scrollToBottomLeft(0.1); */ - scrollToBottomLeft (timeInSecond, attenuated) { + scrollToBottomLeft(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, 0), + anchor: new Vec2(0, 0), applyToHorizontal: true, applyToVertical: true, }); @@ -518,7 +521,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the bottom right boundary of ScrollView. @@ -531,9 +534,9 @@ let ScrollView = cc.Class({ * // Scroll to the lower right corner of the view. * scrollView.scrollToBottomRight(0.1); */ - scrollToBottomRight (timeInSecond, attenuated) { + scrollToBottomRight(timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(1, 0), + anchor: new Vec2(1, 0), applyToHorizontal: true, applyToVertical: true, }); @@ -543,7 +546,7 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** @@ -558,12 +561,12 @@ let ScrollView = cc.Class({ * @example * // Scroll to middle position in 0.1 second in x-axis * let maxScrollOffset = this.getMaxScrollOffset(); - * scrollView.scrollToOffset(cc.v2(maxScrollOffset.x / 2, 0), 0.1); + * scrollView.scrollToOffset(new Vec3(maxScrollOffset.x / 2, 0, 0), 0.1); */ - scrollToOffset (offset, timeInSecond, attenuated) { + scrollToOffset(offset, timeInSecond, attenuated) { let maxScrollOffset = this.getMaxScrollOffset(); - let anchor = cc.v2(0, 0); + let anchor = new Vec2(0, 0); //if maxScrollOffset is 0, then always align the content's top left origin to the top left corner of its parent if (maxScrollOffset.x === 0) { anchor.x = 0; @@ -574,11 +577,11 @@ let ScrollView = cc.Class({ if (maxScrollOffset.y === 0) { anchor.y = 1; } else { - anchor.y = (maxScrollOffset.y - offset.y ) / maxScrollOffset.y; + anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y; } this.scrollTo(anchor, timeInSecond, attenuated); - }, + } /** * !#en Get the positive offset value corresponds to the content's top left boundary. @@ -586,12 +589,12 @@ let ScrollView = cc.Class({ * @method getScrollOffset * @return {Vec2} - A Vec2 value indicate the current scroll offset. */ - getScrollOffset () { - let topDelta = this._getContentTopBoundary() - this._topBoundary; + getScrollOffset() { + let topDelta = this._getContentTopBoundary() - this._topBoundary; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; - return cc.v2(leftDeta, topDelta); - }, + return new Vec2(leftDeta, topDelta); + } /** * !#en Get the maximize available scroll offset @@ -599,16 +602,16 @@ let ScrollView = cc.Class({ * @method getMaxScrollOffset * @return {Vec2} - A Vec2 value indicate the maximize scroll offset in x and y axis. */ - getMaxScrollOffset () { + getMaxScrollOffset() { let scrollSize = this.node.getContentSize(); - let contentSize = this.content.getContentSize(); - let horizontalMaximizeOffset = contentSize.width - scrollSize.width; + let contentSize = this._content!.getContentSize(); + let horizontalMaximizeOffset = contentSize.width - scrollSize.width; let verticalMaximizeOffset = contentSize.height - scrollSize.height; horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0; - verticalMaximizeOffset = verticalMaximizeOffset >=0 ? verticalMaximizeOffset : 0; + verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0; - return cc.v2(horizontalMaximizeOffset, verticalMaximizeOffset); - }, + return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset); + } /** * !#en Scroll the content to the horizontal percent position of ScrollView. @@ -622,9 +625,9 @@ let ScrollView = cc.Class({ * // Scroll to middle position. * scrollView.scrollToBottomRight(0.5, 0.1); */ - scrollToPercentHorizontal (percent, timeInSecond, attenuated) { + scrollToPercentHorizontal(percent, timeInSecond, attenuated) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(percent, 0), + anchor: new Vec2(percent, 0), applyToHorizontal: true, applyToVertical: false, }); @@ -634,36 +637,36 @@ let ScrollView = cc.Class({ } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the percent position of ScrollView in any direction. * !#zh 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。 * @method scrollTo - * @param {Vec2} anchor - A point which will be clamp between cc.v2(0,0) and cc.v2(1,1). + * @param {Vec2} anchor - A point which will be clamp between new Vec2(0,0) and new Vec2(1,1). * @param {Number} [timeInSecond=0] - Scroll time in second, if you don't pass timeInSecond, * the content will jump to the percent position of ScrollView immediately. * @param {Boolean} [attenuated=true] - Whether the scroll acceleration attenuated, default is true. * @example * // Vertical scroll to the bottom of the view. - * scrollView.scrollTo(cc.v2(0, 1), 0.1); + * scrollView.scrollTo(new Vec2(0, 1), 0.1); * * // Horizontal scroll to view right. - * scrollView.scrollTo(cc.v2(1, 0), 0.1); + * scrollView.scrollTo(new Vec2(1, 0), 0.1); */ - scrollTo (anchor, timeInSecond, attenuated) { + scrollTo(anchor: Vec2, timeInSecond: number, attenuated?: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(anchor), + anchor: new Vec2(anchor), applyToHorizontal: true, applyToVertical: true, }); if (timeInSecond) { - this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false); + this._startAutoScroll(moveDelta, timeInSecond, attenuated); } else { this._moveContent(moveDelta); } - }, + } /** * !#en Scroll the content to the vertical percent position of ScrollView. @@ -676,29 +679,29 @@ let ScrollView = cc.Class({ * // Scroll to middle position. * scrollView.scrollToPercentVertical(0.5, 0.1); */ - scrollToPercentVertical (percent, timeInSecond, attenuated) { + scrollToPercentVertical(percent: number, timeInSecond: number, attenuated?: boolean) { let moveDelta = this._calculateMovePercentDelta({ - anchor: cc.v2(0, percent), + anchor: new Vec2(0, percent), applyToHorizontal: false, applyToVertical: true, }); if (timeInSecond) { - this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false); + this._startAutoScroll(moveDelta, timeInSecond, attenuated); } else { this._moveContent(moveDelta); } - }, + } /** * !#en Stop auto scroll immediately * !#zh 停止自动滚动, 调用此 API 可以让 Scrollview 立即停止滚动 * @method stopAutoScroll */ - stopAutoScroll () { + stopAutoScroll() { this._autoScrolling = false; this._autoScrollAccumulatedTime = this._autoScrollTotalTime; - }, + } /** * !#en Modify the content position. @@ -706,14 +709,14 @@ let ScrollView = cc.Class({ * @method setContentPosition * @param {Vec2} position - The position in content's parent space. */ - setContentPosition (position) { + setContentPosition(position: Vec3) { if (position.fuzzyEquals(this.getContentPosition(), EPSILON)) { return; } - this.content.setPosition(position); + this._content!.setPosition(position); this._outOfBoundaryAmountDirty = true; - }, + } /** * !#en Query the content's position in its parent space. @@ -721,19 +724,20 @@ let ScrollView = cc.Class({ * @method getContentPosition * @returns {Position} - The content's position in its parent space. */ - getContentPosition () { - return this.content.getPosition(); - }, - + getContentPosition() { + this._content!.getPosition(this._contentPos); + return this._contentPos; + } + /** * !#en Query whether the user is currently dragging the ScrollView to scroll it * !#zh 用户是否在拖拽当前滚动视图 * @method isScrolling * @returns {Boolean} - Whether the user is currently dragging the ScrollView to scroll it */ - isScrolling () { + isScrolling() { return this._scrolling; - }, + } /** * !#en Query whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown. @@ -741,60 +745,60 @@ let ScrollView = cc.Class({ * @method isAutoScrolling * @returns {Boolean} - Whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown. */ - isAutoScrolling () { + isAutoScrolling() { return this._autoScrolling; - }, - + } + //private methods - _registerEvent () { + _registerEvent() { this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.on(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); - }, + } - _unregisterEvent () { + _unregisterEvent() { this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true); this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true); this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true); this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true); this.node.off(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true); - }, + } - _onMouseWheel (event, captureListeners) { + _onMouseWheel(event, captureListeners) { if (!this.enabledInHierarchy) return; if (this._hasNestedViewGroup(event, captureListeners)) return; - let deltaMove = cc.v2(0, 0); + let deltaMove = new Vec3(); let wheelPrecision = -0.1; - if(CC_JSB) { + if (CC_JSB) { wheelPrecision = -7; } - if(this.vertical) { - deltaMove = cc.v2(0, event.getScrollY() * wheelPrecision); + if (this.vertical) { + deltaMove = new Vec3(0, event.getScrollY() * wheelPrecision); } - else if(this.horizontal) { - deltaMove = cc.v2(event.getScrollY() * wheelPrecision, 0); + else if (this.horizontal) { + deltaMove = new Vec3(event.getScrollY() * wheelPrecision, 0); } this._mouseWheelEventElapsedTime = 0; this._processDeltaMove(deltaMove); - if(!this._stopMouseWheel) { + if (!this._stopMouseWheel) { this._handlePressLogic(); this.schedule(this._checkMouseWheel, 1.0 / 60); this._stopMouseWheel = true; } this._stopPropagationIfTargetIsMe(event); - }, + } - _checkMouseWheel (dt) { + _checkMouseWheel(dt: number) { let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); let maxElapsedTime = 0.1; - if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { this._processInertiaScroll(); this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; @@ -809,25 +813,25 @@ let ScrollView = cc.Class({ this.unschedule(this._checkMouseWheel); this._stopMouseWheel = false; } - }, + } - _calculateMovePercentDelta (options) { + _calculateMovePercentDelta(options) { let anchor = options.anchor; let applyToHorizontal = options.applyToHorizontal; let applyToVertical = options.applyToVertical; this._calculateBoundary(); - anchor = anchor.clampf(cc.v2(0, 0), cc.v2(1, 1)); + anchor = anchor.clampf(new Vec2(0, 0), new Vec2(1, 1)); let scrollSize = this.node.getContentSize(); - let contentSize = this.content.getContentSize(); + let contentSize = this._content!.getContentSize(); let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; leftDeta = -leftDeta; - let moveDelta = cc.v2(0, 0); + let moveDelta = new Vec3(0, 0); let totalScrollDelta = 0; if (applyToHorizontal) { totalScrollDelta = contentSize.width - scrollSize.width; @@ -840,14 +844,14 @@ let ScrollView = cc.Class({ } return moveDelta; - }, + } - _moveContentToTopLeft (scrollViewSize) { - let contentSize = this.content.getContentSize(); + _moveContentToTopLeft(scrollViewSize: Size) { + let contentSize = this._content!.getContentSize(); let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDeta = -bottomDeta; - let moveDelta = cc.v2(0, 0); + let moveDelta = new Vec3(0, 0); let totalScrollDelta = 0; let leftDeta = this._getContentLeftBoundary() - this._leftBoundary; @@ -870,54 +874,57 @@ let ScrollView = cc.Class({ totalScrollDelta = contentSize.width - scrollViewSize.width; moveDelta.x = leftDeta; - if (this.horizontalScrollBar) { - this.horizontalScrollBar.hide(); + if (this._horizontalScrollBar) { + this._horizontalScrollBar.hide(); } } else { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.show(); + if (this._horizontalScrollBar) { + this._horizontalScrollBar.show(); } } this._moveContent(moveDelta); this._adjustContentOutOfBoundary(); - }, + } - _calculateBoundary () { - if (this.content) { - //refresh content size - let layout = this.content.getComponent(cc.Layout); - if(layout && layout.enabledInHierarchy) { - layout.updateLayout(); - } - let viewSize = this.content.parent.getContentSize(); - - let leftBottomPosition = this._convertToContentParentSpace(cc.v2(0, 0)); - this._leftBoundary = leftBottomPosition.x; - this._bottomBoundary = leftBottomPosition.y; - - let topRightPosition = this._convertToContentParentSpace(cc.v2(viewSize.width, viewSize.height)); - this._rightBoundary = topRightPosition.x; - this._topBoundary = topRightPosition.y; - - this._moveContentToTopLeft(viewSize); + _calculateBoundary() { + if (this._content) { + return; } - }, + //refresh content size + let layout = this._content!.getComponent(LayoutComponent); + if (layout && layout.enabledInHierarchy) { + layout!.updateLayout(); + } + let viewSize = this._content!.parent!.getContentSize(); - _convertToContentParentSpace (position) { - let contentParent = this.content.parent; + let leftBottomPosition = this._convertToContentParentSpace(new Vec3(0, 0)); + this._leftBoundary = leftBottomPosition.x; + this._bottomBoundary = leftBottomPosition.y; + + let topRightPosition = this._convertToContentParentSpace(new Vec3(viewSize.width, viewSize.height)); + this._rightBoundary = topRightPosition.x; + this._topBoundary = topRightPosition.y; + + this._moveContentToTopLeft(viewSize); + + } + + _convertToContentParentSpace(position: Vec3) { + let contentParent = this._content!.parent; + // TODO: let viewPositionInWorldSpace = contentParent.convertToWorldSpace(position); return contentParent.convertToNodeSpaceAR(viewPositionInWorldSpace); - }, + } //this is for nested scrollview - _hasNestedViewGroup (event, captureListeners) { + _hasNestedViewGroup(event, captureListeners) { if (event.eventPhase !== cc.Event.CAPTURING_PHASE) return; if (captureListeners) { //captureListeners are arranged from child to parent - for (let i = 0; i < captureListeners.length; ++i){ + for (let i = 0; i < captureListeners.length; ++i) { let item = captureListeners[i]; if (this.node === item) { @@ -927,40 +934,40 @@ let ScrollView = cc.Class({ return false; } - if(item.getComponent(cc.ViewGroup)) { + if (item.getComponent(cc.ViewGroup)) { return true; } } } return false; - }, + } //This is for Scrollview as children of a Button - _stopPropagationIfTargetIsMe (event) { + _stopPropagationIfTargetIsMe(event) { if (event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) { event.stopPropagation(); } - }, + } // touch event handler - _onTouchBegan (event, captureListeners) { - if (!this.enabledInHierarchy) return; + _onTouchBegan(event, captureListeners) { + if (!this.enabledInHierarchy||!this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; let touch = event.touch; - if (this.content) { - this._handlePressLogic(touch); + if (this._content) { + this._handlePressLogic(); } this._touchMoved = false; this._stopPropagationIfTargetIsMe(event); - }, + } - _onTouchMoved (event, captureListeners) { - if (!this.enabledInHierarchy) return; + _onTouchMoved(event, captureListeners) { + if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; let touch = event.touch; - if (this.content) { + if (this._content) { this._handleMoveLogic(touch); } // Do not prevent touch events in inner nodes @@ -982,16 +989,16 @@ let ScrollView = cc.Class({ } } this._stopPropagationIfTargetIsMe(event); - }, + } - _onTouchEnded (event, captureListeners) { - if (!this.enabledInHierarchy) return; + _onTouchEnded(event, captureListeners) { + if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; this._dispatchEvent('touch-up'); let touch = event.touch; - if (this.content) { + if (this._content) { this._handleReleaseLogic(touch); } if (this._touchMoved) { @@ -999,33 +1006,33 @@ let ScrollView = cc.Class({ } else { this._stopPropagationIfTargetIsMe(event); } - }, - - _onTouchCancelled (event, captureListeners) { - if (!this.enabledInHierarchy) return; + } + + _onTouchCancelled(event, captureListeners) { + if (!this.enabledInHierarchy || !this._content) return; if (this._hasNestedViewGroup(event, captureListeners)) return; // Filte touch cancel event send from self if (!event.simulate) { let touch = event.touch; - if(this.content){ + if (this._content) { this._handleReleaseLogic(touch); } } this._stopPropagationIfTargetIsMe(event); - }, + } - _processDeltaMove (deltaMove) { + _processDeltaMove(deltaMove: Vec3) { this._scrollChildren(deltaMove); this._gatherTouchMove(deltaMove); - }, + } - _handleMoveLogic (touch) { + _handleMoveLogic(touch) { let deltaMove = touch.getDelta(); this._processDeltaMove(deltaMove); - }, + } - _scrollChildren (deltaMove) { + _scrollChildren(deltaMove: Vec3) { deltaMove = this._clampDelta(deltaMove); let realMove = deltaMove; @@ -1041,30 +1048,32 @@ let ScrollView = cc.Class({ realMove = realMove.add(outOfBoundary); } - let scrollEventType = -1; + let scrollEventType = ''; + let pos = new Vec3(); + this._content!.getPosition(pos); if (realMove.y > 0) { //up - let icBottomPos = this.content.y - this.content.anchorY * this.content.height; + let icBottomPos = pos.y - this._content!.anchorY * this._content!.height; if (icBottomPos + realMove.y > this._bottomBoundary) { scrollEventType = 'scroll-to-bottom'; } } else if (realMove.y < 0) { //down - let icTopPos = this.content.y - this.content.anchorY * this.content.height + this.content.height; + let icTopPos = pos.y - this._content!.anchorY * this._content!.height + this._content!.height; if (icTopPos + realMove.y <= this._topBoundary) { scrollEventType = 'scroll-to-top'; } } else if (realMove.x < 0) { //left - let icRightPos = this.content.x - this.content.anchorX * this.content.width + this.content.width; + let icRightPos = pos.x - this._content!.anchorX * this._content!.width + this._content!.width; if (icRightPos + realMove.x <= this._rightBoundary) { scrollEventType = 'scroll-to-right'; } } else if (realMove.x > 0) { //right - let icLeftPos = this.content.x - this.content.anchorX * this.content.width; + let icLeftPos = pos.x - this._content!.anchorX * this._content!.width; if (icLeftPos + realMove.x >= this._leftBoundary) { scrollEventType = 'scroll-to-left'; } @@ -1080,13 +1089,13 @@ let ScrollView = cc.Class({ this._dispatchEvent('scrolling'); } - if (scrollEventType !== -1) { + if (scrollEventType.length > 0) { this._dispatchEvent(scrollEventType); } - }, + } - _handlePressLogic () { + _handlePressLogic() { if (this._autoScrolling) { this._dispatchEvent('scroll-ended'); } @@ -1098,10 +1107,10 @@ let ScrollView = cc.Class({ this._touchMoveTimeDeltas.length = 0; this._onScrollBarTouchBegan(); - }, + } - _clampDelta (delta) { - let contentSize = this.content.getContentSize(); + _clampDelta(delta: Vec3) { + let contentSize = this._content!.getContentSize(); let scrollViewSize = this.node.getContentSize(); if (contentSize.width < scrollViewSize.width) { delta.x = 0; @@ -1111,9 +1120,9 @@ let ScrollView = cc.Class({ } return delta; - }, + } - _gatherTouchMove (delta) { + _gatherTouchMove(delta: Vec3) { delta = this._clampDelta(delta); while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) { @@ -1126,9 +1135,9 @@ let ScrollView = cc.Class({ let timeStamp = getTimeInMilliseconds(); this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000); this._touchMovePreviousTimestamp = timeStamp; - }, + } - _startBounceBackIfNeeded () { + _startBounceBackIfNeeded() { if (!this.elastic) { return false; } @@ -1136,7 +1145,7 @@ let ScrollView = cc.Class({ let bounceBackAmount = this._getHowMuchOutOfBoundary(); bounceBackAmount = this._clampDelta(bounceBackAmount); - if (bounceBackAmount.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (bounceBackAmount.fuzzyEquals(_vec3Zero, EPSILON)) { return false; } @@ -1152,21 +1161,21 @@ let ScrollView = cc.Class({ } return true; - }, + } - _processInertiaScroll () { + _processInertiaScroll() { let bounceBackStarted = this._startBounceBackIfNeeded(); if (!bounceBackStarted && this.inertia) { let touchMoveVelocity = this._calculateTouchMoveVelocity(); - if (!touchMoveVelocity.fuzzyEquals(cc.v2(0, 0), EPSILON) && this.brake < 1) { + if (!touchMoveVelocity.fuzzyEquals(_vec3Zero, EPSILON) && this.brake < 1) { this._startInertiaScroll(touchMoveVelocity); } } this._onScrollBarTouchEnded(); - }, + } - _handleReleaseLogic (touch) { + _handleReleaseLogic(touch) { let delta = touch.getDelta(); this._gatherTouchMove(delta); this._processInertiaScroll(); @@ -1177,14 +1186,14 @@ let ScrollView = cc.Class({ this._dispatchEvent('scroll-ended'); } } - }, + } - _isOutOfBoundary () { + _isOutOfBoundary() { let outOfBoundary = this._getHowMuchOutOfBoundary(); - return !outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON); - }, + return !outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON); + } - _isNecessaryAutoScrollBrake () { + _isNecessaryAutoScrollBrake() { if (this._autoScrollBraking) { return true; } @@ -1202,13 +1211,13 @@ let ScrollView = cc.Class({ } return false; - }, + } - getScrollEndedEventTiming () { + getScrollEndedEventTiming() { return EPSILON; - }, + } - _processAutoScrolling (dt) { + _processAutoScrolling(dt) { let isAutoScrollBrake = this._isNecessaryAutoScrollBrake(); let brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1; this._autoScrollAccumulatedTime += dt * (1 / brakingFactor); @@ -1236,7 +1245,7 @@ let ScrollView = cc.Class({ } else { let moveDelta = newPosition.sub(this.getContentPosition()); let outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); - if (!outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (!outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { newPosition = newPosition.add(outOfBoundary); reachedEnd = true; } @@ -1254,28 +1263,28 @@ let ScrollView = cc.Class({ this._isBouncing = false; this._dispatchEvent('scroll-ended'); } - }, + } - _startInertiaScroll (touchMoveVelocity) { + _startInertiaScroll(touchMoveVelocity: Vec3) { let inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR); this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); - }, + } - _calculateAttenuatedFactor (distance) { - if (this.brake <= 0){ + _calculateAttenuatedFactor(distance: number) { + if (this.brake <= 0) { return (1 - this.brake); } //attenuate formula from: http://learnopengl.com/#!Lighting/Light-casters return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008)); - }, + } - _startAttenuatingAutoScroll (deltaMove, initialVelocity) { + _startAttenuatingAutoScroll(deltaMove: Vec3, initialVelocity: Vec3) { let time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag()); let targetDelta = deltaMove.normalize(); - let contentSize = this.content.getContentSize(); + let contentSize = this._content!.getContentSize(); let scrollviewSize = this.node.getContentSize(); let totalMoveWidth = (contentSize.width - scrollviewSize.width); @@ -1284,7 +1293,7 @@ let ScrollView = cc.Class({ let attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth); let attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight); - targetDelta = cc.v2(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); + targetDelta = new Vec3(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake)); let originalMoveLength = deltaMove.mag(); let factor = targetDelta.mag() / originalMoveLength; @@ -1305,13 +1314,13 @@ let ScrollView = cc.Class({ } this._startAutoScroll(targetDelta, time, true); - }, + } - _calculateAutoScrollTimeByInitalSpeed (initalSpeed) { + _calculateAutoScrollTimeByInitalSpeed(initalSpeed) { return Math.sqrt(Math.sqrt(initalSpeed / 5)); - }, + } - _startAutoScroll (deltaMove, timeInSecond, attenuated) { + _startAutoScroll(deltaMove, timeInSecond, attenuated) { let adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); this._autoScrolling = true; @@ -1322,41 +1331,41 @@ let ScrollView = cc.Class({ this._autoScrollAccumulatedTime = 0; this._autoScrollBraking = false; this._isScrollEndedWithThresholdEventFired = false; - this._autoScrollBrakingStartPosition = cc.v2(0, 0); + this._autoScrollBrakingStartPosition = new Vec3(0, 0); let currentOutOfBoundary = this._getHowMuchOutOfBoundary(); - if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) { this._autoScrollCurrentlyOutOfBoundary = true; } - }, + } - _calculateTouchMoveVelocity () { + _calculateTouchMoveVelocity() { let totalTime = 0; - totalTime = this._touchMoveTimeDeltas.reduce(function(a, b) { + totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) { return a + b; }, totalTime); if (totalTime <= 0 || totalTime >= 0.5) { - return cc.v2(0, 0); + return new Vec3(0, 0); } - let totalMovement = cc.v2(0, 0); - totalMovement = this._touchMoveDisplacements.reduce(function(a, b) { + let totalMovement = new Vec3(0, 0); + totalMovement = this._touchMoveDisplacements.reduce(function (a, b) { return a.add(b); }, totalMovement); - return cc.v2(totalMovement.x * (1 - this.brake) / totalTime, - totalMovement.y * (1 - this.brake) / totalTime); - }, + return new Vec3(totalMovement.x * (1 - this.brake) / totalTime, + totalMovement.y * (1 - this.brake) / totalTime); + } - _flattenVectorByDirection (vector) { + _flattenVectorByDirection(vector: Vec3) { let result = vector; result.x = this.horizontal ? result.x : 0; result.y = this.vertical ? result.y : 0; return result; - }, + } - _moveContent (deltaMove, canStartBounceBack) { + _moveContent(deltaMove: Vec3, canStartBounceBack?: boolean) { let adjustedMove = this._flattenVectorByDirection(deltaMove); let newPosition = this.getContentPosition().add(adjustedMove); @@ -1368,35 +1377,35 @@ let ScrollView = cc.Class({ if (this.elastic && canStartBounceBack) { this._startBounceBackIfNeeded(); } - }, + } - _getContentLeftBoundary () { + _getContentLeftBoundary() { let contentPos = this.getContentPosition(); - return contentPos.x - this.content.getAnchorPoint().x * this.content.getContentSize().width; - }, + return contentPos.x - this._content!.getAnchorPoint().x * this._content!.getContentSize().width; + } - _getContentRightBoundary () { - let contentSize = this.content.getContentSize(); + _getContentRightBoundary() { + let contentSize = this._content!.getContentSize(); return this._getContentLeftBoundary() + contentSize.width; - }, + } - _getContentTopBoundary () { - let contentSize = this.content.getContentSize(); + _getContentTopBoundary() { + let contentSize = this._content!.getContentSize(); return this._getContentBottomBoundary() + contentSize.height; - }, + } - _getContentBottomBoundary () { + _getContentBottomBoundary() { let contentPos = this.getContentPosition(); - return contentPos.y - this.content.getAnchorPoint().y * this.content.getContentSize().height; - }, + return contentPos.y - this._content!.getAnchorPoint().y * this._content!.getContentSize().height; + } - _getHowMuchOutOfBoundary (addition) { - addition = addition || cc.v2(0, 0); - if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON) && !this._outOfBoundaryAmountDirty) { + _getHowMuchOutOfBoundary(addition?: Vec3) { + addition = addition || new Vec3(0, 0); + if (addition.fuzzyEquals(_vec3Zero, EPSILON) && !this._outOfBoundaryAmountDirty) { return this._outOfBoundaryAmount; } - let outOfBoundaryAmount = cc.v2(0, 0); + let outOfBoundaryAmount = new Vec3(0, 0); if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) { outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x); } else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) { @@ -1409,7 +1418,7 @@ let ScrollView = cc.Class({ outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y); } - if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON)) { + if (addition.fuzzyEquals(_vec3Zero, EPSILON)) { this._outOfBoundaryAmount = outOfBoundaryAmount; this._outOfBoundaryAmountDirty = false; } @@ -1417,46 +1426,46 @@ let ScrollView = cc.Class({ outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount); return outOfBoundaryAmount; - }, + } - _updateScrollBar (outOfBoundary) { - if (this.horizontalScrollBar) { - this.horizontalScrollBar._onScroll(outOfBoundary); + _updateScrollBar(outOfBoundary) { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onScroll(outOfBoundary); } if (this.verticalScrollBar) { - this.verticalScrollBar._onScroll(outOfBoundary); + this.verticalScrollBar.onScroll(outOfBoundary); } - }, + } - _onScrollBarTouchBegan () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar._onTouchBegan(); + _onScrollBarTouchBegan() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onTouchBegan(); } if (this.verticalScrollBar) { - this.verticalScrollBar._onTouchBegan(); + this.verticalScrollBar.onTouchBegan(); } - }, + } - _onScrollBarTouchEnded () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar._onTouchEnded(); + _onScrollBarTouchEnded() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.onTouchEnded(); } if (this.verticalScrollBar) { - this.verticalScrollBar._onTouchEnded(); + this.verticalScrollBar.onTouchEnded(); } - }, + } - _dispatchEvent (event) { + _dispatchEvent(event) { if (event === 'scroll-ended') { this._scrollEventEmitMask = 0; } else if (event === 'scroll-to-top' - || event === 'scroll-to-bottom' - || event === 'scroll-to-left' - || event === 'scroll-to-right') { + || event === 'scroll-to-bottom' + || event === 'scroll-to-left' + || event === 'scroll-to-right') { let flag = (1 << eventMap[event]); if (this._scrollEventEmitMask & flag) { @@ -1468,94 +1477,96 @@ let ScrollView = cc.Class({ cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]); this.node.emit(event, this); - }, + } + + _adjustContentOutOfBoundary() { + if(!this._content){ + return; + } - _adjustContentOutOfBoundary () { this._outOfBoundaryAmountDirty = true; if (this._isOutOfBoundary()) { - let outOfBoundary = this._getHowMuchOutOfBoundary(cc.v2(0, 0)); + let outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3(0, 0)); let newPosition = this.getContentPosition().add(outOfBoundary); - if (this.content) { - this.content.setPosition(newPosition); + if (this._content) { + this._content.setPosition(newPosition); this._updateScrollBar(0); } } - }, + } - start () { + start() { this._calculateBoundary(); //Because widget component will adjust content position and scrollview position is correct after visit //So this event could make sure the content is on the correct position after loading. - if (this.content) { + if (this._content) { cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this); } - }, + } - _hideScrollbar () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.hide(); + _hideScrollbar() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.hide(); } if (this.verticalScrollBar) { this.verticalScrollBar.hide(); } - }, + } - _showScrollbar () { - if (this.horizontalScrollBar) { - this.horizontalScrollBar.show(); + _showScrollbar() { + if (this._horizontalScrollBar) { + this._horizontalScrollBar.show(); } if (this.verticalScrollBar) { this.verticalScrollBar.show(); } - }, + } - onDisable () { + onDisable() { if (!CC_EDITOR) { this._unregisterEvent(); this.node.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); this.node.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content) { - this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content.parent) { - this.content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); - this.content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - this.content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + if (this._content) { + this._content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this._content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + if (this._content.parent) { + this._content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); + this._content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + this._content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } } this._hideScrollbar(); this.stopAutoScroll(); - }, + } - onEnable () { + onEnable() { if (!CC_EDITOR) { this._registerEvent(); this.node.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); this.node.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content) { - this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); - this.content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - if (this.content.parent) { - this.content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); - this.content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); - this.content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + if (this._content) { + this._content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); + this._content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + if (this._content.parent) { + this._content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this); + this._content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this); + this._content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this); } } } this._showScrollbar(); - }, + } - update (dt) { + update(dt) { if (this._autoScrolling) { this._processAutoScrolling(dt); } } -}); - -cc.ScrollView = module.exports = ScrollView; +} /** * !#en @@ -1667,12 +1678,12 @@ cc.ScrollView = module.exports = ScrollView; * @param {ScrollView} scrollView - The ScrollView component. */ - /** - * !#en - * Note: This event is emitted from the node to which the component belongs. - * !#zh - * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 - * @event scroll-began - * @param {Event.EventCustom} event - * @param {ScrollView} scrollView - The ScrollView component. - */ +/** +* !#en +* Note: This event is emitted from the node to which the component belongs. +* !#zh +* 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 +* @event scroll-began +* @param {Event.EventCustom} event +* @param {ScrollView} scrollView - The ScrollView component. +*/ diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts index c8863f999e..6e96eef091 100644 --- a/cocos/3d/ui/components/slider-component.ts +++ b/cocos/3d/ui/components/slider-component.ts @@ -24,14 +24,14 @@ THE SOFTWARE. ****************************************************************************/ -import { Component} from '../../../components/component'; -import { clamp01 } from '../../../core/utils/misc'; -import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator'; -import { SpriteComponent} from './sprite-component'; -import { Vec2 } from '../../../core/value-types/index'; import ComponentEventHandler from '../../../components/CCComponentEventHandler'; +import { Component} from '../../../components/component'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import Event from '../../../core/event/event'; import { EventTouch } from '../../../core/platform/event-manager/CCEvent'; +import { clamp01 } from '../../../core/utils/misc'; +import { Enum, Vec2 } from '../../../core/value-types/index'; +import { SpriteComponent} from './sprite-component'; import { UITransformComponent } from './ui-transfrom-component'; /** * !#en The Slider Direction @@ -50,8 +50,10 @@ enum Direction { * !#zh 垂直方向 * @property {Number} Vertical */ - Vertical = 1 -}; + Vertical = 1, +} + +Enum(Direction); /** * !#en The Slider Control @@ -64,18 +66,6 @@ enum Direction { @menu('UI/Slider') // @executeInEditMode export class SliderComponent extends Component { - @property - _handle: SpriteComponent | null = null; - @property - _direction: number = Direction.Horizontal; - @property - _progress: number = 0.1; - @property - _slideEvents: ComponentEventHandler[] = []; - - _offset: Vec2 = new Vec2(); - _dragging = false; - _touchHandle = false; /** * !#en The "handle" part of the slider @@ -83,13 +73,13 @@ export class SliderComponent extends Component { * @property {Button} handle */ @property({ - type: SpriteComponent + type: SpriteComponent, }) - get handle() { + get handle () { return this._handle; } - set handle(value: SpriteComponent) { + set handle (value: SpriteComponent) { if (this._handle === value) { return; } @@ -106,13 +96,13 @@ export class SliderComponent extends Component { * @property {Slider.Direction} direction */ @property({ - type: Direction + type: Direction, }) - get direction() { + get direction () { return this._direction; } - set direction(value: number) { + set direction (value: number) { if (this._direction === value) { return; } @@ -125,15 +115,14 @@ export class SliderComponent extends Component { * @property {Number} progress */ @property({ - default: 0.1, slide: true, range: [0.1, 1, 0.01], }) - get progress() { + get progress () { return this._progress; } - set progress(value: number) { + set progress (value: number) { if (this._progress === value) { return; } @@ -148,24 +137,36 @@ export class SliderComponent extends Component { * @property {ComponentEventHandler[]} slideEvents */ @property({ - type: ComponentEventHandler + type: ComponentEventHandler, }) - get slideEvents() { + get slideEvents () { return this._slideEvents; } - set slideEvents(value: ComponentEventHandler[]) { + set slideEvents (value: ComponentEventHandler[]) { this._slideEvents = value; } - static Direction = Direction; + public static Direction = Direction; + @property + public _handle: SpriteComponent | null = null; + @property + public _direction: number = Direction.Horizontal; + @property + public _progress: number = 0.1; + @property + public _slideEvents: ComponentEventHandler[] = []; - __preload() { + public _offset: Vec2 = new Vec2(); + public _dragging = false; + public _touchHandle = false; + + public __preload () { this._updateHandlePosition(); } // 注册事件 - onEnable() { + public onEnable () { this._updateHandlePosition(); this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); @@ -179,7 +180,7 @@ export class SliderComponent extends Component { } } - onDisable() { + public onDisable () { this.node.off(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this); this.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this); this.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this); @@ -191,8 +192,8 @@ export class SliderComponent extends Component { } } - _onHandleDragStart(event: Event) { - if (!event){ + public _onHandleDragStart (event: Event) { + if (!event) { return; } @@ -203,7 +204,7 @@ export class SliderComponent extends Component { event.stopPropagation(); } - _onTouchBegan(event: Event) { + public _onTouchBegan (event: Event) { if (!this._handle) { return; } this._dragging = true; if (!this._touchHandle) { @@ -213,57 +214,55 @@ export class SliderComponent extends Component { event.stopPropagation(); } - _onTouchMoved(event: Event) { + public _onTouchMoved (event: Event) { if (!this._dragging) { return; } this._handleSliderLogic((event as EventTouch).touch); event.stopPropagation(); } - _onTouchEnded(event: Event) { + public _onTouchEnded (event: Event) { this._dragging = false; this._touchHandle = false; this._offset = cc.v2(); event.stopPropagation(); } - _onTouchCancelled(event: Event) { + public _onTouchCancelled (event: Event) { this._dragging = false; event.stopPropagation(); } - _handleSliderLogic(touch) { + public _handleSliderLogic (touch) { this._updateProgress(touch); this._emitSlideEvent(); } - _emitSlideEvent() { + public _emitSlideEvent () { cc.Component.EventHandler.emitEvents(this.slideEvents, this); this.node.emit('slide', this); } - _updateProgress(touch: EventTouch) { + public _updateProgress (touch: EventTouch) { if (!this._handle) { return; } - var localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR((touch as EventTouch).getLocation()); + const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR((touch as EventTouch).getLocation()); if (this.direction === Direction.Horizontal) { this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width); - } - else { + } else { this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height); } } - _updateHandlePosition() { + public _updateHandlePosition () { if (!this._handle) { return; } - var handlelocalPos; + let handlelocalPos; if (this._direction === Direction.Horizontal) { handlelocalPos = cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0); - } - else { + } else { handlelocalPos = cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height); } - var worldSpacePos = this.node.uiTransfromComp!.convertToWorldSpaceAR(handlelocalPos); - let transform: UITransformComponent | null = this._handle.node.parent && this._handle.node.parent.getComponent(cc.UITransformComponent); - if(transform){ + const worldSpacePos = this.node.uiTransfromComp!.convertToWorldSpaceAR(handlelocalPos); + const transform: UITransformComponent | null = this._handle.node.parent && this._handle.node.parent.getComponent(cc.UITransformComponent); + if (transform) { this._handle.node.setPosition(transform.convertToNodeSpaceAR(worldSpacePos)); } } diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index ddbb45116d..e97251a0a0 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -35,11 +35,11 @@ import { import macro from '../../../core/platform/CCMacro'; import { Color } from '../../../core/value-types/index'; import { RenderData } from '../../../renderer/ui/renderData'; +import { UI } from '../../../renderer/ui/ui'; +import { IAssembler } from '../assembler/assembler'; +import { MeshBuffer } from '../mesh-buffer'; import { CanvasComponent } from './canvas-component'; import { UITransformComponent } from './ui-transfrom-component'; -import { MeshBuffer } from '../mesh-buffer'; -import { IAssembler } from '../assembler/assembler'; -import { UI } from '../../../renderer/ui/ui'; /** * !#en @@ -107,8 +107,8 @@ export class UIRenderComponent extends RenderableComponent { this._color = value; } - get viewID () { - return this._viewID; + get visibility () { + return this._visibility; } get renderData () { @@ -121,7 +121,7 @@ export class UIRenderComponent extends RenderableComponent { protected _postAssembler: IAssembler | null = null; protected _renderDataPoolID: number = -1; - protected _viewID: number = -1; + protected _visibility: number = -1; protected _srcBlendFactor: number = macro.BlendFactor.SRC_ALPHA; protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA; @@ -144,7 +144,7 @@ export class UIRenderComponent extends RenderableComponent { if (parent) { const canvasComp = parent.getComponent(CanvasComponent); if (canvasComp) { - this._viewID = canvasComp.visibility; + this._visibility = canvasComp.visibility; break; } } @@ -160,7 +160,7 @@ export class UIRenderComponent extends RenderableComponent { } public onDisable () { - this._viewID = -1; + this._visibility = -1; // this.node._renderComponent = null; // this.disableRender(); } diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index aa94af48ca..bc113e7d4f 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -1,10 +1,10 @@ import { Component} from '../../../components/component'; -import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; +import { ccclass, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator'; +import Event from '../../../core/event/event'; +import { Enum, Mat4 } from '../../../core/value-types'; import Size from '../../../core/value-types/size'; import Vec2 from '../../../core/value-types/vec2'; import * as math from '../../../core/vmath/index'; -import { Enum, Mat4 } from '../../../core/value-types'; -import Event from '../../../core/event/event'; const _vec2a = cc.v2(); const _vec2b = cc.v2(); @@ -36,6 +36,7 @@ const EventType = Enum({ @ccclass('cc.UITransformComponent') @executionOrder(100) +@executeInEditMode export class UITransformComponent extends Component { @property @@ -124,11 +125,11 @@ export class UITransformComponent extends Component { @property public _anchorPoint = cc.v2(0.5, 0.5); - public onEnable () { + public __preload () { this.node.uiTransfromComp = this; } - public onDisable () { + public onDestroy () { this.node.uiTransfromComp = null; } @@ -297,11 +298,11 @@ export class UITransformComponent extends Component { * @example * var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); */ - convertToNodeSpaceAR(worldPoint) { - let matrix = new Mat4(); + public convertToNodeSpaceAR (worldPoint) { + const matrix = new Mat4(); this.node.getWorldMatrix(matrix); math.mat4.invert(_mat4_temp, matrix); - let out = new cc.Vec2(); + const out = new cc.Vec2(); return math.vec2.transformMat4(out, worldPoint, _mat4_temp); } @@ -316,9 +317,9 @@ export class UITransformComponent extends Component { * @example * var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); */ - convertToWorldSpaceAR(nodePoint) { + public convertToWorldSpaceAR (nodePoint) { this.node.getWorldMatrix(_worldMatrix); - let out = new cc.Vec2(); + const out = new cc.Vec2(); return math.vec2.transformMat4(out, nodePoint, _worldMatrix); } } diff --git a/cocos/2d/ui/CCViewGroup.js b/cocos/3d/ui/components/view-group-component.ts similarity index 94% rename from cocos/2d/ui/CCViewGroup.js rename to cocos/3d/ui/components/view-group-component.ts index 04b7b2f79f..9317c26127 100644 --- a/cocos/2d/ui/CCViewGroup.js +++ b/cocos/3d/ui/components/view-group-component.ts @@ -39,11 +39,9 @@ * @class ViewGroup * @extends Component */ -var ViewGroup = cc.Class({ - name: 'cc.ViewGroup', - extends: require('./CCComponent') -}); +import { Component } from "../../../components/component"; +export class ViewGroupComponent extends Component{ -cc.ViewGroup = module.exports = ViewGroup; +} diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts index 59086ceba9..24c9160a1d 100644 --- a/cocos/3d/ui/components/widget-component.ts +++ b/cocos/3d/ui/components/widget-component.ts @@ -24,10 +24,9 @@ THE SOFTWARE. ****************************************************************************/ -// var WidgetManager = require('../base-ui/CCWidgetManager'); -import WidgetManager from '../../../2d/base-ui/CCWidgetManager'; +import { widgetManager } from '../../../2d/base-ui/widget-manager'; import { Component} from '../../../components/component'; -import { ccclass, property, executeInEditMode, menu, executionOrder } from '../../../core/data/class-decorator'; +import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; import { Node } from '../../../scene-graph/index'; /** * !#en Enum for Widget's alignment mode, indicating when the widget should refresh. @@ -55,17 +54,17 @@ import { Node } from '../../../scene-graph/index'; * !#zh 始终保持对齐。 * @property {Number} ALWAYS */ -var AlignMode = WidgetManager.AlignMode; +const AlignMode = widgetManager.AlignMode; -var AlignFlags = WidgetManager._AlignFlags; -var TOP = AlignFlags.TOP; -var MID = AlignFlags.MID; -var BOT = AlignFlags.BOT; -var LEFT = AlignFlags.LEFT; -var CENTER = AlignFlags.CENTER; -var RIGHT = AlignFlags.RIGHT; -var TOP_BOT = TOP | BOT; -var LEFT_RIGHT = LEFT | RIGHT; +const AlignFlags = widgetManager._AlignFlags; +const TOP = AlignFlags.TOP; +const MID = AlignFlags.MID; +const BOT = AlignFlags.BOT; +const LEFT = AlignFlags.LEFT; +const CENTER = AlignFlags.CENTER; +const RIGHT = AlignFlags.RIGHT; +const TOP_BOT = TOP | BOT; +const LEFT_RIGHT = LEFT | RIGHT; /** * !#en @@ -84,57 +83,6 @@ var LEFT_RIGHT = LEFT | RIGHT; @menu('UI/Widget') @executeInEditMode export class WidgetComponent extends Component { - /** - * !#zh: 对齐开关,由 AlignFlags 组成 - * - * @property _alignFlags - * @type {Number} - * @default 0 - * @private - */ - _alignFlags: number = 0; - _wasAlignOnce: boolean = false; - @property - _target: Node | null = null; - @property - _isAlignTop: boolean = false; - @property - _isAlignBottom: boolean = false; - @property - _isAlignLeft: boolean = false; - @property - _isAlignRight: boolean = false; - @property - _left: number = 0; - @property - _right: number = 0; - @property - _top: number = 0; - @property - _bottom: number = 0; - @property - _horizontalCenter: number = 0; - @property - _verticalCenter: number = 0; - @property - _isAbsLeft: boolean = true; - @property - _isAbsRight: boolean = true; - @property - _isAbsTop: boolean = true; - @property - _isAbsBottom: boolean = true; - @property - _isAbsHorizontalCenter: boolean = true; - @property - _isAbsVerticalCenter: boolean = true; - // original size before align - @property - _originalWidth: number = 0; - @property - _originalHeight: number = 0; - @property - _alignMode: number = AlignMode.ON_WINDOW_RESIZE; /** * !#en Specifies an alignment target that can only be one of the parent nodes of the current node. @@ -144,17 +92,17 @@ export class WidgetComponent extends Component { * @default null */ @property({ - type: Node + type: Node, }) - get target() { + get target () { return this._target; } - set target(value) { + set target (value) { this._target = value; if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) { // adjust the offsets to keep the size and position unchanged after target chagned - WidgetManager.updateOffsetsToStayPut(this); + // widgetManager.updateOffsetsToStayPut(this); } } @@ -168,11 +116,10 @@ export class WidgetComponent extends Component { * @default false */ @property - get isAlignTop() { + get isAlignTop () { return (this._alignFlags & TOP) > 0; } - set isAlignTop(value) { - this._isAlignTop = value; + set isAlignTop (value) { this._setAlign(TOP, value); } @@ -184,10 +131,10 @@ export class WidgetComponent extends Component { * @default false */ @property - get isAlignBottom() { + get isAlignBottom () { return (this._alignFlags & BOT) > 0; } - set isAlignBottom(value) { + set isAlignBottom (value) { this._setAlign(BOT, value); } @@ -199,10 +146,10 @@ export class WidgetComponent extends Component { * @default false */ @property - get isAlignLeft() { + get isAlignLeft () { return (this._alignFlags & LEFT) > 0; } - set isAlignLeft(value) { + set isAlignLeft (value) { this._setAlign(LEFT, value); } @@ -214,15 +161,13 @@ export class WidgetComponent extends Component { * @default false */ @property - get isAlignRight() { + get isAlignRight () { return (this._alignFlags & RIGHT) > 0; } - set isAlignRight(value) { + set isAlignRight (value) { this._setAlign(RIGHT, value); } - - /** * !#en * Vertically aligns the midpoint, This will open the other vertical alignment options cancel. @@ -233,16 +178,15 @@ export class WidgetComponent extends Component { * @default false */ @property - get isAlignVerticalCenter() { + get isAlignVerticalCenter () { return (this._alignFlags & MID) > 0; } - set isAlignVerticalCenter(value) { + set isAlignVerticalCenter (value) { if (value) { this.isAlignTop = false; this.isAlignBottom = false; this._alignFlags |= MID; - } - else { + } else { this._alignFlags &= ~MID; } } @@ -257,16 +201,15 @@ export class WidgetComponent extends Component { * @default false */ @property - get isAlignHorizontalCenter() { + get isAlignHorizontalCenter () { return (this._alignFlags & CENTER) > 0; } - set isAlignHorizontalCenter(value) { + set isAlignHorizontalCenter (value) { if (value) { this.isAlignLeft = false; this.isAlignRight = false; this._alignFlags |= CENTER; - } - else { + } else { this._alignFlags &= ~CENTER; } } @@ -283,9 +226,9 @@ export class WidgetComponent extends Component { * @readOnly */ @property({ - visible: false + visible: false, }) - get isStretchWidth() { + get isStretchWidth () { return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT; } @@ -301,9 +244,9 @@ export class WidgetComponent extends Component { * @readOnly */ @property({ - visible: false + visible: false, }) - get isStretchHeight() { + get isStretchHeight () { return (this._alignFlags & TOP_BOT) === TOP_BOT; } @@ -320,10 +263,10 @@ export class WidgetComponent extends Component { * @default 0 */ @property - get top() { + get top () { return this._top; } - set top(value) { + set top (value) { this._top = value; } @@ -338,10 +281,10 @@ export class WidgetComponent extends Component { * @default 0 */ @property - get bottom() { + get bottom () { return this._bottom; } - set bottom(value) { + set bottom (value) { this._bottom = value; } @@ -356,10 +299,10 @@ export class WidgetComponent extends Component { * @default 0 */ @property - get left() { + get left () { return this._left; } - set left(value) { + set left (value) { this._left = value; } @@ -374,10 +317,10 @@ export class WidgetComponent extends Component { * @default 0 */ @property - get right() { + get right () { return this._right; } - set right(value) { + set right (value) { this._right = value; } @@ -391,10 +334,10 @@ export class WidgetComponent extends Component { * @default 0 */ @property - get horizontalCenter() { + get horizontalCenter () { return this._horizontalCenter; } - set horizontalCenter(value) { + set horizontalCenter (value) { this._horizontalCenter = value; } @@ -408,10 +351,10 @@ export class WidgetComponent extends Component { * @default 0 */ @property - get verticalCenter() { + get verticalCenter () { return this._verticalCenter; } - set verticalCenter(value) { + set verticalCenter (value) { this._verticalCenter = value; } @@ -425,10 +368,10 @@ export class WidgetComponent extends Component { * @default true */ @property - get isAbsoluteTop() { + get isAbsoluteTop () { return this._isAbsTop; } - set isAbsoluteTop(value) { + set isAbsoluteTop (value) { this._isAbsTop = value; } @@ -442,10 +385,10 @@ export class WidgetComponent extends Component { * @default true */ @property - get isAbsoluteBottom() { + get isAbsoluteBottom () { return this._isAbsBottom; } - set isAbsoluteBottom(value) { + set isAbsoluteBottom (value) { this._isAbsBottom = value; } @@ -459,10 +402,10 @@ export class WidgetComponent extends Component { * @default true */ @property - get isAbsoluteLeft() { + get isAbsoluteLeft () { return this._isAbsLeft; } - set isAbsoluteLeft(value) { + set isAbsoluteLeft (value) { this._isAbsLeft = value; } @@ -476,10 +419,10 @@ export class WidgetComponent extends Component { * @default true */ @property - get isAbsoluteRight() { + get isAbsoluteRight () { return this._isAbsRight; } - set isAbsoluteRight(value) { + set isAbsoluteRight (value) { this._isAbsRight = value; } @@ -491,13 +434,13 @@ export class WidgetComponent extends Component { * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE; */ @property({ - type: AlignMode + type: AlignMode, }) - get alignMode() { + get alignMode () { return this._alignMode; } - set alignMode(value) { + set alignMode (value) { this._alignMode = value; } @@ -509,15 +452,14 @@ export class WidgetComponent extends Component { * @default true */ @property - get isAbsoluteHorizontalCenter() { + get isAbsoluteHorizontalCenter () { return this._isAbsHorizontalCenter; } - set isAbsoluteHorizontalCenter(value) { + set isAbsoluteHorizontalCenter (value) { this._isAbsHorizontalCenter = value; } - /** * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin. * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。 @@ -526,85 +468,57 @@ export class WidgetComponent extends Component { * @default true */ @property - get isAbsoluteVerticalCenter() { + get isAbsoluteVerticalCenter () { return this._isAbsVerticalCenter; } - set isAbsoluteVerticalCenter(value) { + set isAbsoluteVerticalCenter (value) { this._isAbsVerticalCenter = value; } - static AlignMode = AlignMode; - - onLoad() { - if (this._wasAlignOnce) { - // migrate for old version - this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; - this._wasAlignOnce = false; - } - } - - onEnable() { - WidgetManager.add(this); - } - - onDisable() { - WidgetManager.remove(this); - } - - _setAlign(flag: number, isAlign: boolean) { - var current = (this._alignFlags & flag) > 0; - if (isAlign == current) { - return; - } - var isHorizontal = (flag & LEFT_RIGHT) > 0; - if (isAlign) { - this._alignFlags |= flag; - - if (isHorizontal) { - this.isAlignHorizontalCenter = false; - if (this.isStretchWidth) { - // become stretch - this._originalWidth = this.node.width; - // test check conflict - if (CC_EDITOR && !cc.engine.isPlaying) { - _Scene.DetectConflict.checkConflict_Widget(this); - } - } - } - else { - this.isAlignVerticalCenter = false; - if (this.isStretchHeight) { - // become stretch - this._originalHeight = this.node.height; - // test check conflict - if (CC_EDITOR && !cc.engine.isPlaying) { - _Scene.DetectConflict.checkConflict_Widget(this); - } - } - } - - if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) { - // adjust the offsets to keep the size and position unchanged after alignment chagned - WidgetManager.updateOffsetsToStayPut(this, flag); - } - } - else { - if (isHorizontal) { - if (this.isStretchWidth) { - // will cancel stretch - this.node.width = this._originalWidth; - } - } - else { - if (this.isStretchHeight) { - // will cancel stretch - this.node.height = this._originalHeight; - } - } - - this._alignFlags &= ~flag; - } - } + public static AlignMode = AlignMode; + /** + * !#zh: 对齐开关,由 AlignFlags 组成 + * + * @property _alignFlags + * @type {Number} + * @default 0 + * @private + */ + private _alignFlags = 0; + private _wasAlignOnce = false; + @property + private _target: Node | null = null; + @property + private _left = 0; + @property + private _right = 0; + @property + private _top = 0; + @property + private _bottom = 0; + @property + private _horizontalCenter = 0; + @property + private _verticalCenter = 0; + @property + private _isAbsLeft = true; + @property + private _isAbsRight = true; + @property + private _isAbsTop = true; + @property + private _isAbsBottom = true; + @property + private _isAbsHorizontalCenter = true; + @property + private _isAbsVerticalCenter = true; + // original size before align + @property + private _originalWidth = 0; + @property + private _originalHeight = 0; + @property + private _alignMode = AlignMode.ON_WINDOW_RESIZE; /** * !#en @@ -622,8 +536,80 @@ export class WidgetComponent extends Component { * widget.updateAlignment(); * cc.log(widget.node.y); // changed */ - updateAlignment() { - WidgetManager.updateAlignment(this.node); + public updateAlignment () { + widgetManager.updateAlignment(this.node); + } + + protected onLoad () { + // TODO: + // if (this._wasAlignOnce) { + // // migrate for old version + // this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS; + // this._wasAlignOnce = false; + // } + if(this._alignMode === AlignMode.ONCE){ + this._wasAlignOnce = true; + } + } + + protected onEnable () { + widgetManager.add(this); + } + + protected onDisable () { + widgetManager.remove(this); + } + + private _setAlign (flag, isAlign) { + const current = (this._alignFlags & flag) > 0; + if (isAlign === current) { + return; + } + const isHorizontal = (flag & LEFT_RIGHT) > 0; + if (isAlign) { + this._alignFlags |= flag; + + if (isHorizontal) { + this.isAlignHorizontalCenter = false; + if (this.isStretchWidth) { + // become stretch + this._originalWidth = this.node.width; + // test check conflict + if (CC_EDITOR && !cc.engine.isPlaying) { + // _Scene.DetectConflict.checkConflict_Widget(this); + } + } + } else { + this.isAlignVerticalCenter = false; + if (this.isStretchHeight) { + // become stretch + this._originalHeight = this.node.height; + // test check conflict + if (CC_EDITOR && !cc.engine.isPlaying) { + // _Scene.DetectConflict.checkConflict_Widget(this); + } + } + } + + if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) { + // adjust the offsets to keep the size and position unchanged after alignment chagned + // widgetManager.updateOffsetsToStayPut(this, flag); + } + } else { + if (isHorizontal) { + if (this.isStretchWidth) { + // will cancel stretch + this.node.width = this._originalWidth; + } + } else { + if (this.isStretchHeight) { + // will cancel stretch + this.node.height = this._originalHeight; + } + } + + this._alignFlags &= ~flag; + } } } @@ -656,5 +642,4 @@ export class WidgetComponent extends Component { // } // }); - // cc.Widget = module.exports = Widget; diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts index 8a62222931..9ff479d8fc 100644 --- a/cocos/3d/ui/index.ts +++ b/cocos/3d/ui/index.ts @@ -1,8 +1,8 @@ import { CanvasComponent } from './components/canvas-component'; import { UIRenderComponent } from './components/ui-render-component'; -import { SpriteComponent } from './components/sprite-component'; import './components/ui-transfrom-component'; +import { SpriteComponent } from './components/sprite-component'; import { LabelComponent } from './components/label-component'; import { ButtonComponent } from './components/button-component'; import { ToggleGroupComponent } from './components/toggle-group-component'; @@ -13,6 +13,10 @@ import { ProgressBarComponent } from './components/progress-bar-component'; import { WidgetComponent } from './components/widget-component'; import { EditBoxComponent } from './components/editbox/edit-box-component'; import './assembler/index'; +import { ScrollBarComponent } from './components/scroll-bar-component'; +import { ViewGroupComponent } from './components/view-group-component'; +import { ScrollViewComponent } from './components/scroll-view-component'; +import { LayoutComponent } from './components/layout-component'; cc.CanvasComponent = CanvasComponent; cc.UIRenderComponent = UIRenderComponent; @@ -26,3 +30,8 @@ cc.SliderComponent = SliderComponent; cc.ProgressBarComponent = ProgressBarComponent; cc.WidgetComponent = WidgetComponent; cc.EditBoxComponent = EditBoxComponent; +cc.ViewGroupComponent = ViewGroupComponent; +cc.ScrollBarComponent = ScrollBarComponent; +cc.ScrollViewComponent = ScrollViewComponent; +cc.LayoutComponent = LayoutComponent; + diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 304a99aa71..058a9d3bbf 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -7,6 +7,7 @@ import Vec2 from '../core/value-types/vec2'; import { mat4, quat, vec3 } from '../core/vmath'; import { BaseNode } from './base-node'; import { Layers } from './layers'; +import { WidgetComponent } from '../3d/ui/components/widget-component'; const v3_a = new Vec3(); const q_a = new Quat(); @@ -227,6 +228,7 @@ class Node extends EventTarget(BaseNode) { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); } public uiTransfromComp: UITransformComponent | null = null; + public uiWidgetComp: WidgetComponent | null = null; // local transform @property @@ -938,12 +940,12 @@ class Node extends EventTarget(BaseNode) { return this.uiTransfromComp.contentSize; } - public setContentSize (size: Size, height: number = 0) { + public setContentSize (size: Size, height?: number) { if (!this.uiTransfromComp) { return; } - this.uiTransfromComp.setContentSize(size.height); + this.uiTransfromComp.setContentSize(size, height); } // EVENT TARGET @@ -1039,7 +1041,7 @@ class Node extends EventTarget(BaseNode) { * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this); * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); */ - public on (type, callback, target, useCapture) { + public on (type, callback, target, useCapture?: number) { const forDispatch = this._checknSetupSysEvent(type); if (forDispatch) { return this._onDispatch(type, callback, target, useCapture); @@ -1159,7 +1161,7 @@ class Node extends EventTarget(BaseNode) { * node.off(cc.Node.EventType.TOUCH_START, callback, this.node); * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this); */ - public off (type, callback, target, useCapture) { + public off (type, callback, target, useCapture?: number) { const touchEvent = _touchEvents.indexOf(type) !== -1; const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1; if (touchEvent || mouseEvent) { From 0351dec2264b6af2cfd2775f207e50dfe1fe2913 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 24 Jan 2019 16:39:40 +0800 Subject: [PATCH 257/267] fixed light pipeline --- cocos/3d/builtin/effects.js | 148 +--------------------- cocos/3d/framework/light-component.ts | 8 +- cocos/pipeline/render-pipeline.ts | 61 ++++++--- cocos/renderer/core/program-lib.ts | 1 - cocos/renderer/scene/directional-light.ts | 15 ++- cocos/renderer/scene/light.ts | 12 +- cocos/renderer/scene/point-light.ts | 11 +- cocos/renderer/scene/render-scene.ts | 27 ++-- cocos/renderer/scene/spot-light.ts | 20 ++- playground/simple.html | 4 +- tslint.json | 5 +- 11 files changed, 119 insertions(+), 193 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 07d0cf0621..fb49be5870 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,142 +1,12 @@ // absolute essential effects export default [ - { - "name": "builtin-effect-pbr", - "techniques": [{"passes":[{"program":"builtin-effect-pbr|pbr-vs:vert|pbr-fs:frag", "properties":{"albedo":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "albedo_texture":{"type":29, "value":"grey"}, "metallic":{"type":13, "value":[0.5]}, "metallic_texture":{"type":29, "value":"grey"}, "roughness":{"type":13, "value":[0.7]}, "roughness_texture":{"type":29, "value":"grey"}, "ao":{"type":13, "value":[0.2]}, "ao_texture":{"type":29, "value":"grey"}, "mra_texture":{"type":29, "value":"grey"}, "emissive":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "normal_texture":{"type":29, "value":"normal"}, "diffuseEnvTexture":{"type":32, "value":"white-cube"}, "specularEnvTexture":{"type":32, "value":"white-cube"}, "brdfLUT":{"type":29, "value":"grey"}, "maxReflectionLod":{"type":13, "value":[9]}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-pbr|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], - "shaders": [ - { - "name": "builtin-effect-pbr|pbr-vs:vert|pbr-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\nvarying vec3 pos_w;\nvarying vec3 normal_w;\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 uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_MRA_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\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\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_MRA_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#if USE_TEX_LOD\n#extension GL_EXT_shader_texture_lod: enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\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 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;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\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#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 pos_w;\nvarying vec3 normal_w;\n#if USE_ALBEDO_TEXTURE || USE_NORMAL_TEXTURE || USE_MRA_TEXTURE || USE_METALLIC_TEXTURE || USE_ROUGHNESS_TEXTURE || USE_AO_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\n#if USE_IBL\n uniform samplerCube diffuseEnvTexture;\n uniform samplerCube specularEnvTexture;\n uniform sampler2D brdfLUT;\n#endif\n uniform vec4 albedo;\n uniform float metallic;\n uniform float roughness;\n uniform float ao;\n uniform float maxReflectionLod;\n uniform vec4 emissive;\n uniform float alphaTestThreshold;\n#if USE_ALBEDO_TEXTURE\n uniform sampler2D albedo_texture;\n#endif\n#if USE_MRA_TEXTURE\n uniform sampler2D mra_texture;\n#endif\n#if USE_METALLIC_TEXTURE\n uniform sampler2D metallic_texture;\n#endif\n#if USE_ROUGHNESS_TEXTURE\n uniform sampler2D roughness_texture;\n#endif\n#if USE_AO_TEXTURE\n uniform sampler2D ao_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n \n vec3 getNormalFromTexture() {\n vec3 tangentNormal = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n vec3 q1 = dFdx(pos_w);\n vec3 q2 = dFdy(pos_w);\n vec2 st1 = dFdx(uv0);\n vec2 st2 = dFdy(uv0);\n vec3 N = normalize(normal_w);\n vec3 T = normalize(q1*st2.t - q2*st1.t);\n vec3 B = -normalize(cross(N, T));\n mat3 TBN = mat3(T, B, N);\n return normalize(TBN * tangentNormal);\n }\n#endif\nfloat distributionGGX(vec3 N, vec3 H, float roughness) {\n float a = roughness * roughness;\n float a2 = a * a;\n float NdotH = max(dot(N, H), 0.0);\n float NdotH2 = NdotH * NdotH;\n float nom = a2;\n float denom = (NdotH2 * (a2 - 1.0) + 1.0);\n denom = 3.14159265359 * denom * denom;\n return nom / denom;\n}\nfloat geometrySchlickGGX(float NdotV, float roughness) {\n float r = (roughness + 1.0);\n float k = (r * r) / 8.0;\n float nom = NdotV;\n float denom = NdotV * (1.0 - k) + k;\n return nom / denom;\n}\nfloat geometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {\n float NdotV = max(dot(N, V), 0.0);\n float NdotL = max(dot(N, L), 0.0);\n float ggx2 = geometrySchlickGGX(NdotV, roughness);\n float ggx1 = geometrySchlickGGX(NdotL, roughness);\n return ggx1 * ggx2;\n}\nvec3 fresnelSchlick(float cosTheta, vec3 F0) {\n float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta);\n return F0 + (1.0 - F0) * fresnel;\n}\nvec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) {\n float fresnel = exp2((-5.55473 * cosTheta - 6.98316) * cosTheta);\n return F0 + (max(vec3(1.0 - roughness), F0) - F0) * fresnel;\n}\nvec3 brdf(LightInfo lightInfo, vec3 N, vec3 V, vec3 F0, vec3 albedo, float metallic, float roughness) {\n vec3 H = normalize(V + lightInfo.lightDir);\n float NDF = distributionGGX(N, H, roughness);\n float G = geometrySmith(N, V, lightInfo.lightDir, roughness);\n vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0);\n vec3 nominator = NDF * G * F;\n float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, lightInfo.lightDir), 0.0) + 0.001; \n vec3 specular = nominator / denominator;\n \n vec3 kS = F;\n \n \n \n vec3 kD = vec3(1.0) - kS;\n \n \n \n kD *= 1.0 - metallic;\n float NdotL = max(dot(N, lightInfo.lightDir), 0.0);\n return (kD * albedo / 3.14159265359 + specular) * lightInfo.radiance * NdotL;\n}\nvec4 frag() {\n float opacity = 1.0;\n #if USE_ALBEDO_TEXTURE\n vec4 baseColor = albedo * gammaToLinearSpaceRGBA(texture2D(albedo_texture, uv0));\n vec3 albedo = baseColor.rgb;\n opacity = baseColor.a;\n #else\n opacity = albedo.a;\n vec3 albedo = albedo.rgb;\n #endif\n #if USE_ALPHA_TEST\n if(opacity < alphaTestThreshold) discard;\n #endif\n #if USE_MRA_TEXTURE\n vec3 metalRoughness = texture2D(mra_texture, uv0).rgb;\n float metallic = metalRoughness.r;\n float roughness = metalRoughness.g;\n float ao = metalRoughness.b;\n #else\n #if USE_METALLIC_TEXTURE\n float metallic = texture2D(metallic_texture, uv0).r;\n #endif\n #if USE_ROUGHNESS_TEXTURE\n float roughness = texture2D(roughness_texture, uv0).r;\n #endif\n #if USE_AO_TEXTURE\n float ao = texture2D(ao_texture, uv0).r;\n #endif\n #endif\n vec3 N = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n N = getNormalFromTexture();\n #endif\n vec3 V = normalize(cc_cameraPos.xyz - pos_w);\n \n \n vec3 F0 = vec3(0.04);\n F0 = mix(F0, albedo, metallic);\n \n vec3 Lo = vec3(0.0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n LightInfo info = computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n LightInfo info = computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n LightInfo info = computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]);\n Lo += brdf(info, N, V, F0, albedo, metallic, roughness);\n }\n #endif\n #if USE_EMISSIVE\n vec3 emissiveColor = emissive.rgb;\n #if USE_EMISSIVE_TEXTURE\n emissiveColor *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n Lo += emissiveColor;\n #endif\n \n vec3 ambient = vec3(0.03) * albedo * ao;\n #if USE_IBL\n \n vec3 F = fresnelSchlickRoughness(max(dot(N, V), 0.0), F0, roughness);\n vec3 kS = F;\n vec3 kD = vec3(1.0) - kS;\n kD *= 1.0 - metallic;\n #if USE_RGBE_IBL_DIFFUSE\n vec3 diffuseEnv = unpackRGBE(textureCube(diffuseEnvTexture, N));\n #else\n vec3 diffuseEnv = textureCube(diffuseEnvTexture, N).rgb;\n #endif\n vec3 diffuse = diffuseEnv * albedo;\n \n vec3 R = reflect(-V, N);\n #if USE_TEX_LOD\n #if USE_RGBE_IBL_SPECULAR\n vec3 specularEnv = unpackRGBE(textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod));\n #else\n vec3 specularEnv = textureCubeLodEXT(specularEnvTexture, R, roughness * maxReflectionLod).rgb;\n #endif\n #else\n #if USE_RGBE_IBL_SPECULAR\n vec3 specularEnv = unpackRGBE(textureCube(specularEnvTexture, R));\n #else\n vec3 specularEnv = textureCube(specularEnvTexture, R).rgb;\n #endif\n #endif\n vec2 brdf = texture2D(brdfLUT, vec2(max(dot(N, V), 0.0), 1.0 - roughness)).rg;\n vec3 specular = specularEnv * (F * brdf.x + brdf.y);\n ambient = (kD * diffuse + specular) * ao;\n #endif\n vec3 color = ambient + Lo;\n #if CC_USE_SHADOW_MAP\n color *= computeShadow();\n #endif\n \n color = color / (color + vec3(1.0));\n \n vec4 finalColor = vec4(color, opacity);\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", - "defines": [ - {"name":"USE_ALBEDO_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, - {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, - {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"USE_TEX_LOD", "type":"boolean", "defines":[]}, - {"name":"USE_IBL", "type":"boolean", "defines":[]}, - {"name":"USE_MRA_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"USE_METALLIC_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"USE_ROUGHNESS_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"USE_AO_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, - {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, - {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]}, - {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, - {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, - {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, - {"name":"USE_RGBE_IBL_DIFFUSE", "type":"boolean", "defines":["USE_IBL"]}, - {"name":"USE_RGBE_IBL_SPECULAR", "type":"boolean", "defines":["USE_IBL"]} - ], - "blocks": [ - {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ - {"name":"mainTiling", "type":14, "count":1, "size":8}, - {"name":"mainOffset", "type":14, "count":1, "size":8} - ]}, - {"name": "Constants", "size": 52, "defines": [], "binding": 1, "members": [ - {"name":"albedo", "type":16, "count":1, "size":16}, - {"name":"metallic", "type":13, "count":1, "size":4}, - {"name":"roughness", "type":13, "count":1, "size":4}, - {"name":"ao", "type":13, "count":1, "size":4}, - {"name":"maxReflectionLod", "type":13, "count":1, "size":4}, - {"name":"emissive", "type":16, "count":1, "size":16}, - {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} - ]} - ], - "samplers": [ - {"name":"diffuseEnvTexture", "type":32, "count":1, "defines":["USE_IBL"], "binding":2}, - {"name":"specularEnvTexture", "type":32, "count":1, "defines":["USE_IBL"], "binding":3}, - {"name":"brdfLUT", "type":29, "count":1, "defines":["USE_IBL"], "binding":4}, - {"name":"albedo_texture", "type":29, "count":1, "defines":["USE_ALBEDO_TEXTURE"], "binding":5}, - {"name":"mra_texture", "type":29, "count":1, "defines":["USE_MRA_TEXTURE"], "binding":6}, - {"name":"metallic_texture", "type":29, "count":1, "defines":["USE_METALLIC_TEXTURE"], "binding":7}, - {"name":"roughness_texture", "type":29, "count":1, "defines":["USE_ROUGHNESS_TEXTURE"], "binding":8}, - {"name":"ao_texture", "type":29, "count":1, "defines":["USE_AO_TEXTURE"], "binding":9}, - {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":10}, - {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":11} - ], - "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives", "USE_TEX_LOD":"EXT_shader_texture_lod"} - }, - { - "name": "builtin-effect-pbr|shadow-depth-vs:vert|shadow-depth-fs:frag", - "vert": "\nattribute vec3 a_position;\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 float vDepth;\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 mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", - "defines": [ - {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} - ], - "blocks": [], - "samplers": [], - "dependencies": {} - } - ] - }, - { - "name": "builtin-effect-phong", - "techniques": [{"passes":[{"program":"builtin-effect-phong|phong-vs:vert|phong-fs:frag", "properties":{"diffuseColor":{"type":17, "value":[0.3, 0.3, 0.3, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "diffuse_texture":{"type":29, "value":"grey"}, "specularColor":{"type":17, "value":[0, 0, 0, 0]}, "specular_texture":{"type":29, "value":"grey"}, "emissiveColor":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "glossiness":{"type":13, "value":[10]}, "normal_texture":{"type":29, "value":"normal"}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], - "shaders": [ - { - "name": "builtin-effect-phong|phong-vs:vert|phong-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\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 vec3 normal_w;\nvarying vec3 pos_w;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\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\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n #if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\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 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;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\n}\nstruct Lighting {\n vec3 diffuse;\n vec3 specular;\n};\nLighting brdf(LightInfo info, vec3 N, vec3 V, float glossiness) {\n Lighting res;\n res.diffuse = info.radiance * max(0.0, dot(N, info.lightDir));\n vec3 H = normalize(V + info.lightDir);\n float NdotH = max(0.0, dot(N, H));\n NdotH = pow(NdotH, max(1.0, glossiness * 128.0));\n res.specular = info.radiance * NdotH;\n return res;\n}\nLighting getPhongLighting(vec3 pos_w, vec3 N, vec3 V, float glossiness) {\n Lighting result;\n result.diffuse = vec3(0, 0, 0);\n result.specular = vec3(0, 0, 0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n Lighting info = brdf(computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n Lighting info = brdf(computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n Lighting info = brdf(computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n return result;\n}\n#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 normal_w;\nvarying vec3 pos_w;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\nstruct phongMaterial\n{\n vec3 diffuse;\n vec3 emissive;\n vec3 specular;\n float glossiness;\n float opacity;\n};\n uniform vec4 diffuseColor;\n uniform vec4 emissiveColor;\n uniform vec4 specularColor;\n uniform float glossiness;\n uniform float alphaTestThreshold;\n#if USE_DIFFUSE_TEXTURE\n uniform sampler2D diffuse_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_SPECULAR && USE_SPECULAR_TEXTURE\n uniform sampler2D specular_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( uv0.st );\n vec2 st1 = dFdy( uv0.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nphongMaterial getPhongMaterial() {\n phongMaterial result;\n #if USE_DIFFUSE_TEXTURE\n vec4 baseColor = diffuseColor * gammaToLinearSpaceRGBA(texture2D(diffuse_texture, uv0));\n result.diffuse = baseColor.rgb;\n result.opacity = baseColor.a;\n #else\n result.diffuse = diffuseColor.rgb;\n result.opacity = diffuseColor.a;\n #endif\n #if USE_EMISSIVE\n result.emissive = emissiveColor.rgb;\n #if USE_EMISSIVE_TEXTURE\n result.emissive *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n #endif\n #if USE_SPECULAR\n result.specular = specularColor.rgb;\n #if USE_SPECULAR_TEXTURE\n result.specular = gammaToLinearSpaceRGB(texture2D(specular_texture, uv0).rgb);\n #endif\n result.glossiness = glossiness;\n #endif\n return result;\n}\nvec4 composePhongShading(Lighting lighting, phongMaterial mtl, float shadow) {\n vec4 o = vec4(0.0, 0.0, 0.0, 1.0);\n \n o.xyz = lighting.diffuse * mtl.diffuse;\n #if USE_EMISSIVE\n o.xyz += mtl.emissive;\n #endif\n #if USE_SPECULAR\n o.xyz += lighting.specular * mtl.specular;\n #endif\n o.xyz *= shadow;\n o.w = mtl.opacity;\n return o;\n}\nvec4 frag () {\n Lighting phongLighting;\n vec3 viewDirection = normalize(cc_cameraPos.xyz - pos_w);\n phongMaterial mtl = getPhongMaterial();\n #if USE_ALPHA_TEST\n if(mtl.opacity < alphaTestThreshold) discard;\n #endif\n vec3 normal = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n normal = getNormal(pos_w, normal);\n #endif\n phongLighting = getPhongLighting(pos_w, normal, viewDirection, mtl.glossiness);\n phongLighting.diffuse += vec3(0.5); \n #if CC_USE_SHADOW_MAP\n vec4 finalColor = composePhongShading(phongLighting, mtl, computeShadow());\n #else\n vec4 finalColor = composePhongShading(phongLighting, mtl, 1.0);\n #endif\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", - "defines": [ - {"name":"USE_DIFFUSE_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, - {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, - {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, - {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, - {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, - {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, - {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, - {"name":"USE_SPECULAR", "type":"boolean", "defines":[]}, - {"name":"USE_SPECULAR_TEXTURE", "type":"boolean", "defines":["USE_SPECULAR"]}, - {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]} - ], - "blocks": [ - {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ - {"name":"mainTiling", "type":14, "count":1, "size":8}, - {"name":"mainOffset", "type":14, "count":1, "size":8} - ]}, - {"name": "Constants", "size": 56, "defines": [], "binding": 1, "members": [ - {"name":"diffuseColor", "type":16, "count":1, "size":16}, - {"name":"emissiveColor", "type":16, "count":1, "size":16}, - {"name":"specularColor", "type":16, "count":1, "size":16}, - {"name":"glossiness", "type":13, "count":1, "size":4}, - {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} - ]} - ], - "samplers": [ - {"name":"diffuse_texture", "type":29, "count":1, "defines":["USE_DIFFUSE_TEXTURE"], "binding":2}, - {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":3}, - {"name":"specular_texture", "type":29, "count":1, "defines":["USE_SPECULAR", "USE_SPECULAR_TEXTURE"], "binding":4}, - {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":5} - ], - "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives"} - }, - { - "name": "builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag", - "vert": "\nattribute vec3 a_position;\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 float vDepth;\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 mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", - "defines": [ - {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} - ], - "blocks": [], - "samplers": [], - "dependencies": {} - } - ] - }, { "name": "builtin-effect-skybox", "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], "shaders": [ { "name": "builtin-effect-skybox|sky-vs|sky-fs", - "vert": "\n attribute vec3 a_position;\n \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.xyww;\n viewDir = a_position;\n }\n", + "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.xyww;\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":[]} @@ -151,20 +21,16 @@ export default [ }, { "name": "builtin-effect-sprite", - "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":{"u_texSampler":{"type":29, "value":"default", "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0, "addressU":2, "addressV":2}}}}]}], + "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":"default"}}}]}], "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matViewProj;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 vert () {\n vec4 pos = cc_matViewProj * vec4(a_position, 1);\n v_uv0 = a_texCoord;\n v_color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n return texture2D(u_texSampler, v_uv0) * v_color;\n}\nvoid main() { gl_FragColor = frag(); }\n", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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": [ - {"name":"cc_matViewProj", "type":26, "count":1, "size":64} - ]} - ], + "blocks": [], "samplers": [ - {"name":"u_texSampler", "type":29, "count":1, "defines":[], "binding":1} + {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":0} ], "dependencies": {} } @@ -176,7 +42,7 @@ export default [ "shaders": [ { "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", - "vert": "\nattribute vec3 a_position;\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", + "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":[]}, diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts index 361d058cf6..ba271c4f83 100644 --- a/cocos/3d/framework/light-component.ts +++ b/cocos/3d/framework/light-component.ts @@ -251,8 +251,8 @@ export default class LightComponent extends Component { } public onEnable () { - if (this._light) { this._light.enabled = true; return; } this._createLight(); + if (this._light) { this._light.enabled = true; return; } } public onDisable () { @@ -268,14 +268,14 @@ export default class LightComponent extends Component { const scene = this._getRenderScene(); switch (this._type) { case Type.DIRECTIONAL: - this._light = scene.createDirectionalLight(this.name); + this._light = scene.createDirectionalLight(this.name, this.node); break; case Type.POINT: - this._light = scene.createPointLight(this.name); + this._light = scene.createPointLight(this.name, this.node); this.range = this._range; break; case Type.SPOT: - this._light = scene.createSpotLight(this.name); + this._light = scene.createSpotLight(this.name, this.node); this.range = this._range; this.spotAngle = this._spotAngle; break; diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index fc3c6c12d7..901713962f 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -15,6 +15,10 @@ import { RenderQueue } from './render-queue'; import { RenderView } from './render-view'; 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; @@ -50,13 +54,13 @@ export class UBOGlobal { { name: 'cc_matViewProjInv', type: GFXType.MAT4, count: 1 }, { name: 'cc_cameraPos', type: GFXType.FLOAT4, count: 1 }, // lights - { name: 'cc_dirLightDirection', type: GFXType.FLOAT4, count: 4 }, - { name: 'cc_dirLightColor', type: GFXType.FLOAT4, count: 4 }, - { name: 'cc_pointLightPositionAndRange', type: GFXType.FLOAT4, count: 4 }, - { name: 'cc_pointLightColor', type: GFXType.FLOAT4, count: 4 }, - { name: 'cc_spotLightPositionAndRange', type: GFXType.FLOAT4, count: 4 }, - { name: 'cc_spotLightDirection', type: GFXType.FLOAT4, count: 4 }, - { name: 'cc_spotLightColor', type: GFXType.FLOAT4, count: 4 }, + { 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 }, ], }; @@ -79,6 +83,7 @@ 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(); @@ -354,20 +359,42 @@ export abstract class RenderPipeline { const scene = view.camera.scene; const dLights = scene.directionalLights; - for (let i = 0; i < dLights.length; i++) { - this._uboGlobal.view.set(dLights[i].directionArray, UBOGlobal.DIR_LIGHT_DIR_OFFSET + 4 * i); - this._uboGlobal.view.set(dLights[i].colorData, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 4 * i); + 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 + 4 * i); + this._uboGlobal.view.set(light.colorData, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 4 * i); + } else { + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_DIR_OFFSET + 4 * i); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 4 * i); + } } const pLights = scene.pointLights; - for (let i = 0; i < pLights.length; i++) { - this._uboGlobal.view.set(pLights[i].positionAndRange, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + 4 * i); - this._uboGlobal.view.set(pLights[i].colorData, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 4 * i); + 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 + 4 * i); + this._uboGlobal.view.set(light.colorData, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 4 * i); + } else { + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + 4 * i); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 4 * i); + } } const sLights = scene.spotLights; - for (let i = 0; i < sLights.length; i++) { - this._uboGlobal.view.set(sLights[i].positionAndRange, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + 4 * i); - this._uboGlobal.view.set(sLights[i].directionArray, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 4 * i); - this._uboGlobal.view.set(sLights[i].colorData, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 4 * i); + 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 + 4 * i); + this._uboGlobal.view.set(light.directionArray, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 4 * i); + this._uboGlobal.view.set(light.colorData, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 4 * i); + } else { + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + 4 * i); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 4 * i); + this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 4 * i); + } } // update ubos diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index 7945b1bf94..2bfc0a874f 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -125,7 +125,6 @@ class ProgramLib { if (program !== undefined) { return program; } - defines.CC_NUM_DIR_LIGHTS = 1; // get template const tmpl = this._templates[name]; diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/renderer/scene/directional-light.ts index c58f678aba..0072aa447b 100644 --- a/cocos/renderer/scene/directional-light.ts +++ b/cocos/renderer/scene/directional-light.ts @@ -1,7 +1,12 @@ -import { Vec3 } from '../../core/value-types'; +import { Vec3, Quat } from '../../core/value-types'; import { vec3 } from '../../core/vmath'; import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +const _forward = new Vec3(0, 0, 1); +const _v3 = new Vec3(); +const _qt = new Quat(); export class DirectionalLight extends Light { protected _direction = Float32Array.from([0, 0, 1, 0]); @@ -13,8 +18,12 @@ export class DirectionalLight extends Light { return this._direction; } - constructor (scene: RenderScene, name: string) { - super(scene, name); + constructor (scene: RenderScene, node: Node, name: string) { + super(scene, node, name); this._type = LightType.DIRECTIONAL; } + + public update () { + this.direction = vec3.transformQuat(_v3, _forward, this._node.getWorldRotation(_qt)); + } } diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts index 526b708991..0c706a24a1 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/renderer/scene/light.ts @@ -1,4 +1,5 @@ import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; export enum LightType { UNKNOWN, @@ -10,6 +11,10 @@ export enum LightType { export class Light { protected _color = Float32Array.from([1, 1, 1, 1]); protected _enabled = false; + protected _scene: RenderScene; + protected _node: Node; + protected _type: LightType; + protected _name: string; set enabled (val) { this._enabled = val; @@ -32,12 +37,11 @@ export class Light { return this._name; } - protected _scene: RenderScene; - protected _type: LightType; - protected _name: string; + public update () {} - constructor (scene: RenderScene, name: string) { + constructor (scene: RenderScene, node: Node, name: string) { this._scene = scene; + this._node = node; this._name = name; this._type = LightType.UNKNOWN; } diff --git a/cocos/renderer/scene/point-light.ts b/cocos/renderer/scene/point-light.ts index bfd677c175..a7b52f3c2d 100644 --- a/cocos/renderer/scene/point-light.ts +++ b/cocos/renderer/scene/point-light.ts @@ -2,6 +2,9 @@ import { Vec3 } from '../../core/value-types'; import { vec3 } from '../../core/vmath'; import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +const _v3 = new Vec3(); export class PointLight extends Light { protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); @@ -17,8 +20,12 @@ export class PointLight extends Light { return this._positionAndRange; } - constructor (scene: RenderScene, name: string) { - super(scene, name); + constructor (scene: RenderScene, node: Node, name: string) { + super(scene, node, name); this._type = LightType.POINT; } + + public update () { + this.position = this._node.getWorldPosition(_v3); + } } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 9be39b8f7c..258c907ffc 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -13,6 +13,7 @@ import { Light } from './light'; import { Model } from './model'; import { PointLight } from './point-light'; import { SpotLight } from './spot-light'; +import { UBOGlobal } from '../../pipeline/render-pipeline'; export interface IRenderSceneInfo { name: string; @@ -97,7 +98,7 @@ export class RenderScene { public destroyCamera (camera: Camera) { for (let i = 0; i < this._cameras.length; ++i) { if (this._cameras[i] === camera) { - this._cameras.slice(i); + this._cameras.splice(i, 1); return; } } @@ -117,9 +118,9 @@ export class RenderScene { return null; } - public createPointLight (name: string): Light | null { - if (this._pointLights.length >= 4) { return null; } - const light = new PointLight(this, name); + public createPointLight (name: string, node: Node): Light | null { + if (this._pointLights.length >= UBOGlobal.MAX_POINT_LIGHTS) { return null; } + const light = new PointLight(this, node, name); this._pointLights.push(light); return light; } @@ -127,15 +128,15 @@ export class RenderScene { public destroyPointLight (light: Light) { for (let i = 0; i < this._pointLights.length; ++i) { if (this._pointLights[i] === light) { - this._pointLights.slice(i); + this._pointLights.splice(i, 1); return; } } } - public createDirectionalLight (name: string): Light | null { - if (this._directionalLights.length >= 4) { return null; } - const light = new DirectionalLight(this, name); + public createDirectionalLight (name: string, node: Node): Light | null { + if (this._directionalLights.length >= UBOGlobal.MAX_DIR_LIGHTS) { return null; } + const light = new DirectionalLight(this, node, name); this._directionalLights.push(light); return light; } @@ -143,15 +144,15 @@ export class RenderScene { public destroyDirectionalLight (light: Light) { for (let i = 0; i < this._directionalLights.length; ++i) { if (this._directionalLights[i] === light) { - this._directionalLights.slice(i); + this._directionalLights.splice(i, 1); return; } } } - public createSpotLight (name: string): Light | null { - if (this._spotLights.length >= 4) { return null; } - const light = new SpotLight(this, name); + public createSpotLight (name: string, node: Node): Light | null { + if (this._spotLights.length >= UBOGlobal.MAX_SPOT_LIGHTS) { return null; } + const light = new SpotLight(this, node, name); this._spotLights.push(light); return light; } @@ -159,7 +160,7 @@ export class RenderScene { public destroySpotLight (light: Light) { for (let i = 0; i < this._spotLights.length; ++i) { if (this._spotLights[i] === light) { - this._spotLights.slice(i); + this._spotLights.splice(i, 1); return; } } diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts index dd56fd8c1f..f741b94093 100644 --- a/cocos/renderer/scene/spot-light.ts +++ b/cocos/renderer/scene/spot-light.ts @@ -1,10 +1,15 @@ -import { Vec3 } from '../../core/value-types'; +import { Vec3, Quat } from '../../core/value-types'; import { vec3 } from '../../core/vmath'; import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; + +const _forward = new Vec3(0, 0, 1); +const _v3 = new Vec3(); +const _qt = new Quat(); export class SpotLight extends Light { - protected _direction = Float32Array.from([0, 0, 1, 0]); + protected _direction = Float32Array.from([0, 0, 1, Math.cos(Math.PI / 6)]); protected _positionAndRange = Float32Array.from([0, 0, 0, 10]); set position (val: Vec3) { @@ -17,7 +22,7 @@ export class SpotLight extends Light { vec3.array(this._direction, val); } set spotAngle (val: number) { - this._direction[3] = val; + this._direction[3] = Math.cos(val * 0.5); } get positionAndRange () { @@ -27,8 +32,13 @@ export class SpotLight extends Light { return this._direction; } - constructor (scene: RenderScene, name: string) { - super(scene, name); + constructor (scene: RenderScene, node: Node, name: string) { + super(scene, node, name); this._type = LightType.DIRECTIONAL; } + + public update () { + this.position = this._node.getWorldPosition(_v3); + this.direction = vec3.transformQuat(_v3, _forward, this._node.getWorldRotation(_qt)); + } } diff --git a/playground/simple.html b/playground/simple.html index b02fcdb872..93fcfb7096 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -68,7 +68,7 @@ const material = new cc.Material(); material.setDefines({ USE_COLOR: true }); // parsed effect file is embedded in cocos/3d/builtin/effects.js - material.effectName = 'builtin-effect-pbr'; + material.effectName = 'builtin-effect-unlit'; const len = 50; const models = [], passes = []; @@ -84,7 +84,7 @@ // material instance initialized here passes.push(modelCom.material.passes[0]); } - const handle = passes[0].getHandle('albedo'); + const handle = passes[0].getHandle('color'); { const material = new cc.Material(); diff --git a/tslint.json b/tslint.json index 8f4d116805..605e6fb73e 100644 --- a/tslint.json +++ b/tslint.json @@ -9,6 +9,10 @@ true, "single" ], + "one-line": [ + true, + "check-open-brace" + ], "no-console": false, "space-before-function-paren": true, "max-classes-per-file": false, @@ -18,7 +22,6 @@ "no-bitwise": false, "no-empty": false, "radix": false, - "one-line": false, }, "rulesDirectory": [] } From fada40faa0ce29c9ed05f176b3ff975492fad5cd Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 19:06:05 +0800 Subject: [PATCH 258/267] complete ui render pipeline --- cocos/gfx/webgl/webgl-device.ts | 2 ++ cocos/renderer/ui/ui.ts | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/cocos/gfx/webgl/webgl-device.ts b/cocos/gfx/webgl/webgl-device.ts index ae5a1230c4..262cbde641 100644 --- a/cocos/gfx/webgl/webgl-device.ts +++ b/cocos/gfx/webgl/webgl-device.ts @@ -254,9 +254,11 @@ export class WebGLGFXDevice extends GFXDevice { }; this._webGLRC = this._canvas.getContext('webgl', webGLCtxAttribs); + /* if (this._webGLRC && info.debug) { this._webGLRC = WebGLDeveloperTools.makeDebugContext(this._webGLRC, this._onWebGLError.bind(this)); } + */ } catch (err) { console.error(err); return false; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 0d64621502..8af839ef2e 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -279,8 +279,8 @@ export class UI { if (curCamera) { cmdBuff.endRenderPass(); } - this._renderArea.width = camera.width; - this._renderArea.height = camera.height; + this._renderArea.width = camera.orthoHeight * camera.aspect; + this._renderArea.height = camera.orthoHeight; camera.update(); @@ -292,7 +292,7 @@ export class UI { curCamera = camera; - cmdBuff.beginRenderPass(framebuffer, this._renderArea, [camera.clearColor], camera.clearDepth, camera.clearStencil); + cmdBuff.beginRenderPass(framebuffer, this._renderArea, [], camera.clearDepth, camera.clearStencil); } material.bindingLayout.bindBuffer(0, this._uiUBO!); From 50f057a901421f99d675edc36a0b2031aeabe29e Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Thu, 24 Jan 2019 20:03:59 +0800 Subject: [PATCH 259/267] fix ui bugs --- cocos/3d/builtin/effects.js | 110 +++++++++++++++++-- cocos/3d/ui/components/sprite-component.ts | 2 +- cocos/renderer/ui/ui.ts | 116 ++++++++++++--------- 3 files changed, 169 insertions(+), 59 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index fb49be5870..c8541e62de 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -1,12 +1,104 @@ // absolute essential effects export default [ + { + "name": "builtin-effect-particle-add", + "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":1, "blendSrcAlpha":2, "blendDstAlpha":1}]}, "program":"builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", "properties":{"mainTexture":{"type":29, "value":"grey"}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "frameTile":{"type":14, "value":[1, 1]}, "velocityScale":{"type":13, "value":[0]}, "lengthScale":{"type":13, "value":[0]}, "tintColor":{"type":17, "value":[0.5, 0.5, 0.5, 0.5]}}}]}], + "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 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\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":[]}, + {"name":"USE_HORIZONTAL_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_VERTICAL_BILLBOARD", "type":"boolean", "defines":[]}, + {"name":"USE_WORLD_SPACE", "type":"boolean", "defines":[]} + ], + "blocks": [ + {"name": "Constants", "size": 32, "defines": [], "binding": 0, "members": [ + {"name":"frameTile", "type":14, "count":1, "size":8}, + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8}, + {"name":"velocityScale", "type":13, "count":1, "size":4}, + {"name":"lengthScale", "type":13, "count":1, "size":4} + ]}, + {"name": "FragConstants", "size": 16, "defines": [], "binding": 1, "members": [ + {"name":"tintColor", "type":16, "count":1, "size":16} + ]} + ], + "samplers": [ + {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":2} + ], + "dependencies": {} + } + ] + }, + { + "name": "builtin-effect-phong", + "techniques": [{"passes":[{"program":"builtin-effect-phong|phong-vs:vert|phong-fs:frag", "properties":{"diffuseColor":{"type":17, "value":[0.3, 0.3, 0.3, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "diffuse_texture":{"type":29, "value":"grey"}, "specularColor":{"type":17, "value":[0, 0, 0, 0]}, "specular_texture":{"type":29, "value":"grey"}, "emissiveColor":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "glossiness":{"type":13, "value":[10]}, "normal_texture":{"type":29, "value":"normal"}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], + "shaders": [ + { + "name": "builtin-effect-phong|phong-vs:vert|phong-fs:frag", + "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\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 vec3 normal_w;\nvarying vec3 pos_w;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\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\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n #if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\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 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;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\n}\nstruct Lighting {\n vec3 diffuse;\n vec3 specular;\n};\nLighting brdf(LightInfo info, vec3 N, vec3 V, float glossiness) {\n Lighting res;\n res.diffuse = info.radiance * max(0.0, dot(N, info.lightDir));\n vec3 H = normalize(V + info.lightDir);\n float NdotH = max(0.0, dot(N, H));\n NdotH = pow(NdotH, max(1.0, glossiness * 128.0));\n res.specular = info.radiance * NdotH;\n return res;\n}\nLighting getPhongLighting(vec3 pos_w, vec3 N, vec3 V, float glossiness) {\n Lighting result;\n result.diffuse = vec3(0, 0, 0);\n result.specular = vec3(0, 0, 0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n Lighting info = brdf(computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n Lighting info = brdf(computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n Lighting info = brdf(computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n return result;\n}\n#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 normal_w;\nvarying vec3 pos_w;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\nstruct phongMaterial\n{\n vec3 diffuse;\n vec3 emissive;\n vec3 specular;\n float glossiness;\n float opacity;\n};\n uniform vec4 diffuseColor;\n uniform vec4 emissiveColor;\n uniform vec4 specularColor;\n uniform float glossiness;\n uniform float alphaTestThreshold;\n#if USE_DIFFUSE_TEXTURE\n uniform sampler2D diffuse_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_SPECULAR && USE_SPECULAR_TEXTURE\n uniform sampler2D specular_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( uv0.st );\n vec2 st1 = dFdy( uv0.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nphongMaterial getPhongMaterial() {\n phongMaterial result;\n #if USE_DIFFUSE_TEXTURE\n vec4 baseColor = diffuseColor * gammaToLinearSpaceRGBA(texture2D(diffuse_texture, uv0));\n result.diffuse = baseColor.rgb;\n result.opacity = baseColor.a;\n #else\n result.diffuse = diffuseColor.rgb;\n result.opacity = diffuseColor.a;\n #endif\n #if USE_EMISSIVE\n result.emissive = emissiveColor.rgb;\n #if USE_EMISSIVE_TEXTURE\n result.emissive *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n #endif\n #if USE_SPECULAR\n result.specular = specularColor.rgb;\n #if USE_SPECULAR_TEXTURE\n result.specular = gammaToLinearSpaceRGB(texture2D(specular_texture, uv0).rgb);\n #endif\n result.glossiness = glossiness;\n #endif\n return result;\n}\nvec4 composePhongShading(Lighting lighting, phongMaterial mtl, float shadow) {\n vec4 o = vec4(0.0, 0.0, 0.0, 1.0);\n \n o.xyz = lighting.diffuse * mtl.diffuse;\n #if USE_EMISSIVE\n o.xyz += mtl.emissive;\n #endif\n #if USE_SPECULAR\n o.xyz += lighting.specular * mtl.specular;\n #endif\n o.xyz *= shadow;\n o.w = mtl.opacity;\n return o;\n}\nvec4 frag () {\n Lighting phongLighting;\n vec3 viewDirection = normalize(cc_cameraPos.xyz - pos_w);\n phongMaterial mtl = getPhongMaterial();\n #if USE_ALPHA_TEST\n if(mtl.opacity < alphaTestThreshold) discard;\n #endif\n vec3 normal = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n normal = getNormal(pos_w, normal);\n #endif\n phongLighting = getPhongLighting(pos_w, normal, viewDirection, mtl.glossiness);\n phongLighting.diffuse += vec3(0.5); \n #if CC_USE_SHADOW_MAP\n vec4 finalColor = composePhongShading(phongLighting, mtl, computeShadow());\n #else\n vec4 finalColor = composePhongShading(phongLighting, mtl, 1.0);\n #endif\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"USE_DIFFUSE_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, + {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, + {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, + {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, + {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, + {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, + {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, + {"name":"USE_SPECULAR", "type":"boolean", "defines":[]}, + {"name":"USE_SPECULAR_TEXTURE", "type":"boolean", "defines":["USE_SPECULAR"]}, + {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]} + ], + "blocks": [ + {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ + {"name":"mainTiling", "type":14, "count":1, "size":8}, + {"name":"mainOffset", "type":14, "count":1, "size":8} + ]}, + {"name": "Constants", "size": 56, "defines": [], "binding": 1, "members": [ + {"name":"diffuseColor", "type":16, "count":1, "size":16}, + {"name":"emissiveColor", "type":16, "count":1, "size":16}, + {"name":"specularColor", "type":16, "count":1, "size":16}, + {"name":"glossiness", "type":13, "count":1, "size":4}, + {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} + ]} + ], + "samplers": [ + {"name":"diffuse_texture", "type":29, "count":1, "defines":["USE_DIFFUSE_TEXTURE"], "binding":2}, + {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":3}, + {"name":"specular_texture", "type":29, "count":1, "defines":["USE_SPECULAR", "USE_SPECULAR_TEXTURE"], "binding":4}, + {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":5} + ], + "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives"} + }, + { + "name": "builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag", + "vert": "\nattribute vec3 a_position;\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 float vDepth;\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 mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", + "defines": [ + {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, + {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} + ], + "blocks": [], + "samplers": [], + "dependencies": {} + } + ] + }, { "name": "builtin-effect-skybox", "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], "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.xyww;\n viewDir = a_position;\n }\n", + "vert": "\n attribute vec3 a_position;\n \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.xyww;\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":[]} @@ -21,16 +113,20 @@ export default [ }, { "name": "builtin-effect-sprite", - "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":"default"}}}]}], + "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":{"u_texSampler":{"type":29, "value":"default", "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0, "addressU":2, "addressV":2}}}}]}], "shaders": [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\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 uv0;\nvarying vec4 color;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n pos = cc_matViewProj * cc_matWorld * 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", + "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matViewProj;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 vert () {\n vec4 pos = cc_matViewProj * vec4(a_position, 1);\n v_uv0 = a_texCoord;\n v_color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", + "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n \n return vec4(0.0, 1.0, 0.0, 1.0);\n}\nvoid main() { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }\n", "defines": [], - "blocks": [], + "blocks": [ + {"name": "UI", "size": 64, "defines": [], "binding": 0, "members": [ + {"name":"cc_matViewProj", "type":26, "count":1, "size":64} + ]} + ], "samplers": [ - {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":0} + {"name":"u_texSampler", "type":29, "count":1, "defines":[], "binding":1} ], "dependencies": {} } @@ -42,7 +138,7 @@ 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", + "vert": "\nattribute vec3 a_position;\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":[]}, diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts index 88ad58b727..b819f2d84b 100644 --- a/cocos/3d/ui/components/sprite-component.ts +++ b/cocos/3d/ui/components/sprite-component.ts @@ -451,7 +451,7 @@ export class SpriteComponent extends UIRenderComponent { this.material = cc.builtinResMgr.get('sprite-material'); material = this.material; if (spriteFrame && spriteFrame.textureLoaded()) { - material!.setProperty('mainTexture', spriteFrame); + material!.setProperty('u_texSampler', spriteFrame); this.markForUpdateRenderData(true); } } diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 8af839ef2e..3ea23b5937 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -46,21 +46,30 @@ export class UBOUI { const _mat4Array = new Float32Array(16); -export interface IUIBufferBatch { - vf32: Float32Array; - vui16: Uint16Array; - vbSize: number; - ibSize: number; - vb: GFXBuffer; - ib: GFXBuffer; - ia: GFXInputAssembler; +export class UIBufferBatch { + public vf32: Float32Array | null = null; + public vui16: Uint16Array | null = null; + public vb: GFXBuffer | null = null; + public ib: GFXBuffer | null = null; + public ia: GFXInputAssembler | null = null; + public vbSize: number = 0; + public ibSize: number = 0; } -export interface IUIDrawBatch { - camera: Camera; - bufferBatch: IUIBufferBatch; - uiMaterial: UIMaterial; - texView: GFXTextureView; +export class UIDrawBatch { + public camera: Camera | null = null; + public bufferBatch: UIBufferBatch | null = null; + public uiMaterial: UIMaterial | null = null; + public texView: GFXTextureView | null = null; + public idxCount: number = 0; + + clear() { + this.camera = null; + this.bufferBatch = null; + this.uiMaterial = null; + this.texView = null; + this.idxCount = 0; + } } export interface IUIRenderData { @@ -79,23 +88,23 @@ export class UI { private _bufferPool: RecyclePool = new RecyclePool(() => { return new MeshBuffer(); }, 128); - private _bufferBatchPool: RecyclePool = new RecyclePool(() => { - return new Object() as IUIBufferBatch; + private _bufferBatchPool: RecyclePool = new RecyclePool(() => { + return new UIBufferBatch(); }, 128); - private _drawBatchPool: RecyclePool = new RecyclePool(() => { - return new Object() as IUIDrawBatch; + private _drawBatchPool: RecyclePool = new RecyclePool(() => { + return new UIDrawBatch(); }, 128); private _device: GFXDevice; private _cmdBuff: GFXCommandBuffer | null = null; private _renderArea: IGFXRect = { x: 0, y: 0, width: 0, height: 0 }; private _scene: RenderScene; private _attributes: IGFXInputAttribute[] = []; - private _bufferBatches: IUIBufferBatch[] = []; + private _bufferBatches: UIBufferBatch[] = []; private _uiMaterial: UIMaterial | null = null; private _uiMaterials: UIMaterial[] = []; private _uboUI: UBOUI = new UBOUI(); private _uiUBO: GFXBuffer | null = null; - private _batches: CachedArray; + private _batches: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; @@ -228,8 +237,10 @@ export class UI { public update (dt: number) { - for (let i = 0; i < this._batches.array.length; ++i) { - this._drawBatchPool.remove(this._batches.array[i]); + for (let i = 0; i < this._batches.length; ++i) { + const batch = this._batches.array[i]; + batch.clear(); + this._drawBatchPool.remove(batch); } this._batches.clear(); @@ -243,18 +254,15 @@ export class UI { // update buffers for (const bufferBatch of this._bufferBatches) { - if (bufferBatch.vbSize > bufferBatch.vb.size) { - bufferBatch.vb.resize(bufferBatch.vbSize); + if (bufferBatch.vbSize > bufferBatch.vb!.size) { + bufferBatch.vb!.resize(bufferBatch.vbSize); } - bufferBatch.vb.update(bufferBatch.vf32); + bufferBatch.vb!.update(bufferBatch.vf32!); - if (bufferBatch.ibSize > bufferBatch.ib.size) { - bufferBatch.ib.resize(bufferBatch.ibSize); + if (bufferBatch.ibSize > bufferBatch.ib!.size) { + bufferBatch.ib!.resize(bufferBatch.ibSize); } - bufferBatch.ib.update(bufferBatch.vui16); - - bufferBatch.ia.vertexCount = bufferBatch.vf32.length; - bufferBatch.ia.indexCount = bufferBatch.vui16.length; + bufferBatch.ib!.update(bufferBatch.vui16!); } } } @@ -296,13 +304,16 @@ export class UI { } material.bindingLayout.bindBuffer(0, this._uiUBO!); - material.bindingLayout.bindTextureView(1, batch.texView); + material.bindingLayout.bindTextureView(1, batch.texView!); material.bindingLayout.update(); + let ia = batch.bufferBatch!.ia! + ia.indexCount = batch.idxCount; + cmdBuff.bindPipelineState(material.pipelineState); cmdBuff.bindBindingLayout(material.bindingLayout); - cmdBuff.bindInputAssembler(batch.bufferBatch.ia); - cmdBuff.draw(batch.bufferBatch.ia); + cmdBuff.bindInputAssembler(batch.bufferBatch!.ia!); + cmdBuff.draw(batch.bufferBatch!.ia!); } cmdBuff.endRenderPass(); @@ -369,9 +380,10 @@ export class UI { let curCamera: Camera | null = null; let curTexView: GFXTextureView | null = null; let bufferBatchIdx = 0; - let curBufferBatch: IUIBufferBatch = this._bufferBatches[bufferBatchIdx++]; - let vOffset = 0; - let iOffset = 0; + let curBufferBatch: UIBufferBatch = this._bufferBatches[bufferBatchIdx++]; + let idxCount = 0; + let vertCount = 0; + let vf32: Float32Array; let vui16: Uint16Array; let vbSize = 0; @@ -380,14 +392,14 @@ export class UI { for (const uiRenderData of this._commitUIRenderDatas) { - if (iOffset + uiRenderData.meshBuffer.vData!.length > 65535) { + if (idxCount + uiRenderData.meshBuffer.vData!.length > 65535) { if (bufferBatchIdx >= this._bufferBatches.length) { this.createBufferBatch(); } curBufferBatch = this._bufferBatches[bufferBatchIdx++]; - vOffset = 0; - iOffset = 0; + vertCount = 0; + idxCount = 0; isNewBatch = true; } else { isNewBatch = false; @@ -395,34 +407,34 @@ export class UI { // merge vertices vf32 = uiRenderData.meshBuffer.vData!; - vbSize = (vf32.length + vOffset) * 4; + vbSize = (vf32.length + vertCount) * 4; if (vbSize > curBufferBatch.vbSize) { curBufferBatch.vbSize = vbSize; const lastVF32 = curBufferBatch.vf32; - curBufferBatch.vf32 = new Float32Array(vf32.length + vOffset); - curBufferBatch.vf32.set(lastVF32, 0); + curBufferBatch.vf32 = new Float32Array(vf32.length + vertCount); + curBufferBatch.vf32.set(lastVF32!, 0); } - curBufferBatch.vf32.set(vf32, vOffset); + curBufferBatch.vf32!.set(vf32, vertCount); // merge indices vui16 = uiRenderData.meshBuffer.iData!; - ibSize = (vui16.length + iOffset) * 2; + ibSize = (vui16.length + idxCount) * 2; if (ibSize > curBufferBatch.ibSize) { curBufferBatch.ibSize = ibSize; - const lastVUI16 = curBufferBatch.vui16; - curBufferBatch.vui16 = new Uint16Array(vui16.length + iOffset); + const lastVUI16 = curBufferBatch.vui16!; + curBufferBatch.vui16 = new Uint16Array(vui16.length + idxCount); curBufferBatch.vui16.set(lastVUI16, 0); } for (let n = 0; n < vui16.length; ++n) { - curBufferBatch.vui16[iOffset + n] = vui16[n] + vOffset; + curBufferBatch.vui16![idxCount + n] = vui16[n] + vertCount; } - curBufferBatch.vui16.set(vui16, iOffset); + curBufferBatch.vui16!.set(vui16, idxCount); - vOffset += vf32.length; - iOffset += vui16.length; + vertCount += vf32.length; + idxCount += vui16.length; if (curCamera !== uiRenderData.camera) { isNewBatch = true; @@ -440,12 +452,14 @@ export class UI { batch.bufferBatch = curBufferBatch; batch.uiMaterial = this._uiMaterial!; batch.texView = curTexView!; + batch.idxCount = idxCount; + this._batches.push(batch); } } // for } - private createBufferBatch (): IUIBufferBatch { + private createBufferBatch (): UIBufferBatch { const vbStride = Float32Array.BYTES_PER_ELEMENT * 9; const vbCount = 128; From c376fb8dce2303e083e4427661e9ffc3589974dc Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 25 Jan 2019 11:37:32 +0800 Subject: [PATCH 260/267] fix ui render view --- cocos/3d/builtin/effects.js | 2 +- cocos/3d/ui/components/canvas-component.ts | 3 ++- cocos/core/root.ts | 12 +++++++----- cocos/pipeline/render-view.ts | 15 +++++++++++---- cocos/renderer/scene/camera.ts | 4 +++- cocos/renderer/ui/ui.ts | 5 +++-- 6 files changed, 27 insertions(+), 14 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index c8541e62de..4307d6165c 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -118,7 +118,7 @@ export default [ { "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matViewProj;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 vert () {\n vec4 pos = cc_matViewProj * vec4(a_position, 1);\n v_uv0 = a_texCoord;\n v_color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n \n return vec4(0.0, 1.0, 0.0, 1.0);\n}\nvoid main() { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }\n", + "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n return texture2D(u_texSampler, v_uv0) * v_color;\n \n}\nvoid main() { gl_FragColor = frag(); }\n", "defines": [], "blocks": [ {"name": "UI", "size": 64, "defines": [], "binding": 0, "members": [ diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 5fe53c1206..7edfa6e1b2 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -201,10 +201,11 @@ export class CanvasComponent extends Component { orthoHeight: 10, far: 4096, near: -0.1, - color: cc.color(255, 0, 0, 1), + color: cc.color(0, 0, 0, 255), clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL, rect: new Rect(0, 0, 1, 1), depth: 1, + isUI: true, } as ICameraInfo; this._camera = this._getRenderScene().createCamera(this._cameraInfo); cc.director.root.ui.addScreen(this); diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 84147d7e31..cfd9c400bf 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -150,7 +150,7 @@ export class Root { this._frameTime = deltaTime; for (const view of this._views) { - if (view.isEnable() && view.window === this._mainWindow) { + if (view.isEnable && view.window === this._mainWindow) { this._pipeline!.render(view); } } @@ -218,10 +218,12 @@ export class Root { const view: RenderView = this._createViewFun(this, info.camera); view.initialize(info); - this._views.push(view); - this._views.sort((a: RenderView, b: RenderView) => { - return a.priority - b.priority; - }); + if (!info.isUI) { + this._views.push(view); + this._views.sort((a: RenderView, b: RenderView) => { + return a.priority - b.priority; + }); + } return view; } diff --git a/cocos/pipeline/render-view.ts b/cocos/pipeline/render-view.ts index ca1538088b..64e142bb0f 100644 --- a/cocos/pipeline/render-view.ts +++ b/cocos/pipeline/render-view.ts @@ -10,6 +10,7 @@ export interface IRenderViewInfo { camera: Camera; name: string; priority: number; + isUI: boolean; } export class RenderView { @@ -41,6 +42,14 @@ export class RenderView { return this._camera!; } + public get isEnable (): boolean { + return this._isEnable; + } + + public get isUI (): boolean { + return this._isUI; + } + public static registerCreateFunc (root: Root) { root._createViewFun = (_root: Root, _camera: Camera): RenderView => new RenderView(_root, _camera); } @@ -52,6 +61,7 @@ export class RenderView { private _visibility: number = 0; private _camera: Camera; private _isEnable: boolean = true; + private _isUI: boolean = false; private constructor (root: Root, camera: Camera) { this._root = root; @@ -62,6 +72,7 @@ export class RenderView { this._name = info.name; this._priority = info.priority; + this._isUI = info.isUI; return true; } @@ -78,8 +89,4 @@ export class RenderView { public enable (isEnable: boolean) { this._isEnable = isEnable; } - - public isEnable (): boolean { - return this._isEnable; - } } diff --git a/cocos/renderer/scene/camera.ts b/cocos/renderer/scene/camera.ts index a67daf96a5..31698dab1d 100644 --- a/cocos/renderer/scene/camera.ts +++ b/cocos/renderer/scene/camera.ts @@ -25,6 +25,7 @@ export interface ICameraInfo { clearFlags: GFXClearFlag; rect: Rect; targetDisplay: number; + isUI?: boolean; } const v_a = cc.v3(); @@ -61,7 +62,7 @@ export class Camera { constructor (scene: RenderScene, info: ICameraInfo) { this._scene = scene; - this._name = name; + this._name = info.name; this._node = info.node; this._proj = info.projection; this._fov = toRadian(info.fov); @@ -82,6 +83,7 @@ export class Camera { camera: this, name: this._name, priority: RenderViewPriority.GENERAL, + isUI: (info.isUI !== undefined? info.isUI : false), }); this.changeTargetDisplay(info.targetDisplay); diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 3ea23b5937..86186efead 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -112,6 +112,7 @@ export class UI { this._device = _root.device; this._scene = this._root.createScene({ name: 'GUIScene', + isUIScene: true, }); this._batches = new CachedArray(64); @@ -287,8 +288,8 @@ export class UI { if (curCamera) { cmdBuff.endRenderPass(); } - this._renderArea.width = camera.orthoHeight * camera.aspect; - this._renderArea.height = camera.orthoHeight; + this._renderArea.width = camera.width; + this._renderArea.height = camera.height; camera.update(); From bbdead9c89d196bd88a4196133895db36986e05d Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Fri, 25 Jan 2019 11:44:56 +0800 Subject: [PATCH 261/267] restore 2D canvas components --- cocos/3d/ui/components/canvas-component.ts | 143 +++++++++------------ 1 file changed, 63 insertions(+), 80 deletions(-) diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 7edfa6e1b2..7841792d91 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -136,7 +136,7 @@ export class CanvasComponent extends Component { @property private _priority = 0; - private _thisOnResized: Function | null = null; + private _thisOnResized: ()=>void; private _camera: Camera | null = null; private _cameraInfo: ICameraInfo | null = null; @@ -161,37 +161,6 @@ export class CanvasComponent extends Component { } public __preload () { - // if (CC_DEV) { - // var Flags = cc.Object.Flags; - // this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked); - // } - - // if (CanvasComponent.instance) { - // return cc.errorID(6700, - // this.node.name, CanvasComponent.instance.node.name); - // } - // CanvasComponent.instance = this; - - // if (CC_EDITOR) { - // cc.engine.on('design-resolution-changed', this._thisOnResized); - // } - // else { - // TODO: Need to do editor initiative call - if (!CC_EDITOR) { - // if (cc.sys.isMobile) { - // window.addEventListener('resize', this._thisOnResized); - // } - // else { - // cc.view.on('canvas-resize', this._thisOnResized); - // } - cc.view.on('design-resolution-changed', this._thisOnResized); - } - - this.applySettings(); - this.alignWithScreen(); - } - - public onEnable () { this._cameraInfo = { name: 'ui', node: this.node, @@ -209,6 +178,33 @@ export class CanvasComponent extends Component { } as ICameraInfo; this._camera = this._getRenderScene().createCamera(this._cameraInfo); cc.director.root.ui.addScreen(this); + + // if (CC_DEV) { + // var Flags = cc.Object.Flags; + // this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked); + // } + + // if (CanvasComponent.instance) { + // return cc.errorID(6700, + // this.node.name, CanvasComponent.instance.node.name); + // } + // CanvasComponent.instance = this; + + if (CC_EDITOR) { + cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); + cc.engine.on('design-resolution-changed', this._thisOnResized); + } + else { + if (cc.sys.isMobile) { + window.addEventListener('resize', this._thisOnResized); + } + else { + cc.view.on('canvas-resize', this._thisOnResized); + } + } + + this.applySettings(); + this.alignWithScreen(); } public onDisable () { @@ -219,25 +215,20 @@ export class CanvasComponent extends Component { } public onDestroy () { - if (super.onDestroy) { - super.onDestroy(); + if (CC_EDITOR) { + cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this); + cc.engine.off('design-resolution-changed', this._thisOnResized); + } + else { + if (cc.sys.isMobile) { + window.removeEventListener('resize', this._thisOnResized); + } else { + cc.view.off('canvas-resize', this._thisOnResized); + } } - // if (CC_EDITOR) { - // cc.engine.off('design-resolution-changed', this._thisOnResized); - // } - // else { - // if (cc.sys.isMobile) { - // window.removeEventListener('resize', this._thisOnResized); - // } - // else { - // cc.view.off('canvas-resize', this._thisOnResized); - // } - // } cc.view.off('design-resolution-changed', this._thisOnResized); - // cc.director._uiSystem.removeScreen(this); - // if (CanvasComponent.instance === this) { // CanvasComponent.instance = null; // } @@ -245,35 +236,27 @@ export class CanvasComponent extends Component { // - public alignWithScreen () { - if (this._camera) { - this._camera.resize(cc.game.canvas.width, cc.game.canvas.height); - this._camera.orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2; - const viewport = this._camera.viewport; - viewport.x = viewport.y = 0; - viewport.width = cc.game.canvas.width; - viewport.height = cc.game.canvas.height; + public alignWithScreen() { + let nodeSize, designSize; + if (CC_EDITOR) { + // nodeSize = designSize = cc.engine.getDesignResolutionSize(); + nodeSize = designSize = this._designResolution; + this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1); } - // if (CC_EDITOR) { - // nodeSize = designSize = cc.engine.getDesignResolutionSize(); - // this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1); - // } - // else { - const canvasSize = cc.visibleRect; - const nodeSize = canvasSize; - const designSize = cc.view.getDesignResolutionSize(); - const clipTopRight = !this.fitHeight && !this.fitWidth; - let offsetX = 0; - let offsetY = 0; - if (clipTopRight) { - // offset the canvas to make it in the center of screen - offsetX = (designSize.width - canvasSize.width) * 0.5; - offsetY = (designSize.height - canvasSize.height) * 0.5; + else { + const canvasSize = cc.visibleRect; + nodeSize = canvasSize; + const designSize = cc.view.getDesignResolutionSize(); + const clipTopRight = !this.fitHeight && !this.fitWidth; + let offsetX = 0; + let offsetY = 0; + if (clipTopRight) { + // offset the canvas to make it in the center of screen + offsetX = (designSize.width - canvasSize.width) * 0.5; + offsetY = (designSize.height - canvasSize.height) * 0.5; + } + this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1); } - this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1); - // } - // let canvasSize = nodeSize = cc.visibleRect; - // this.node.setPosition(canvasSize.width / 2, canvasSize.height / 2, 1); this.node.width = nodeSize.width; this.node.height = nodeSize.height; } @@ -293,11 +276,11 @@ export class CanvasComponent extends Component { } const designRes = this._designResolution; - // if (CC_EDITOR) { - // cc.engine.setDesignResolutionSize(designRes.width, designRes.height); - // } - // else { - cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy); - // } + if (CC_EDITOR) { + // cc.engine.setDesignResolutionSize(designRes.width, designRes.height); + } + else { + cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy); + } } } From 393dfa91f6b5eac55ad6e05aac015eaab62cbc3c Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 25 Jan 2019 14:41:04 +0800 Subject: [PATCH 262/267] fix lights --- cocos/3d/builtin/effects.js | 58 ----------------------- cocos/3d/framework/light-component.ts | 5 +- cocos/3d/framework/model-component.ts | 34 ++++++------- cocos/pipeline/render-pipeline.ts | 44 ++++++++--------- cocos/renderer/scene/directional-light.ts | 2 +- cocos/renderer/scene/light.ts | 2 +- cocos/renderer/scene/spot-light.ts | 2 +- cocos/scene-graph/node.ts | 27 +++++------ 8 files changed, 58 insertions(+), 116 deletions(-) diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js index 4307d6165c..81f033dd9e 100644 --- a/cocos/3d/builtin/effects.js +++ b/cocos/3d/builtin/effects.js @@ -34,64 +34,6 @@ export default [ } ] }, - { - "name": "builtin-effect-phong", - "techniques": [{"passes":[{"program":"builtin-effect-phong|phong-vs:vert|phong-fs:frag", "properties":{"diffuseColor":{"type":17, "value":[0.3, 0.3, 0.3, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "diffuse_texture":{"type":29, "value":"grey"}, "specularColor":{"type":17, "value":[0, 0, 0, 0]}, "specular_texture":{"type":29, "value":"grey"}, "emissiveColor":{"type":17, "value":[0, 0, 0, 0]}, "emissive_texture":{"type":29, "value":"grey"}, "glossiness":{"type":13, "value":[10]}, "normal_texture":{"type":29, "value":"normal"}, "alphaTestThreshold":{"type":13, "value":[0]}}}, {"program":"builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag"}]}], - "shaders": [ - { - "name": "builtin-effect-phong|phong-vs:vert|phong-fs:frag", - "vert": "\nattribute vec3 a_position;\nattribute vec3 a_normal;\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 vec3 normal_w;\nvarying vec3 pos_w;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n attribute vec2 a_texCoord1;\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\n#if CC_USE_SHADOW_MAP\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nvoid prepareShadowData(vec3 pos_w) {\n posLightspace = cc_matViewProjLight * vec4(pos_w, 1.0);\n vDepth = (posLightspace.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y);\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n vec4 normal = vec4(a_normal, 0);\n #if CC_USE_SKINNING\n skinVertex(pos, normal);\n #endif\n pos_w = (cc_matWorld * pos).xyz;\n normal_w = (cc_matWorldIT * normal).xyz;\n #if CC_USE_SHADOW_MAP\n prepareShadowData(pos_w);\n #endif\n #if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n uv0 = a_texCoord1 * mainTiling + mainOffset;\n #endif\n return cc_matViewProj * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\n#if USE_NORMAL_TEXTURE\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define saturate(a) clamp( a, 0.0, 1.0 )\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 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;\nstruct LightInfo {\n vec3 lightDir;\n vec3 radiance;\n};\nLightInfo computeDirectionalLighting(\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n ret.lightDir = -normalize(lightDirection.xyz);\n ret.radiance = lightColor.rgb;\n return ret;\n}\nLightInfo computePointLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0.0, 1.0 - length(lightDir) / lightPositionAndRange.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation;\n return ret;\n}\nLightInfo computeSpotLighting(\n vec3 worldPosition,\n vec4 lightPositionAndRange,\n vec4 lightDirection,\n vec4 lightColor\n) {\n LightInfo ret;\n vec3 lightDir = lightPositionAndRange.xyz - worldPosition;\n float attenuation = max(0., 1.0 - length(lightDir) / lightPositionAndRange.w);\n float cosConeAngle = max(0., dot(lightDirection.xyz, -lightDir));\n cosConeAngle = cosConeAngle < lightDirection.w ? 0.0 : cosConeAngle;\n cosConeAngle = pow(cosConeAngle, lightColor.w);\n ret.lightDir = normalize(lightDir);\n ret.radiance = lightColor.rgb * attenuation * cosConeAngle;\n return ret;\n}\nstruct Lighting {\n vec3 diffuse;\n vec3 specular;\n};\nLighting brdf(LightInfo info, vec3 N, vec3 V, float glossiness) {\n Lighting res;\n res.diffuse = info.radiance * max(0.0, dot(N, info.lightDir));\n vec3 H = normalize(V + info.lightDir);\n float NdotH = max(0.0, dot(N, H));\n NdotH = pow(NdotH, max(1.0, glossiness * 128.0));\n res.specular = info.radiance * NdotH;\n return res;\n}\nLighting getPhongLighting(vec3 pos_w, vec3 N, vec3 V, float glossiness) {\n Lighting result;\n result.diffuse = vec3(0, 0, 0);\n result.specular = vec3(0, 0, 0);\n #if CC_NUM_DIR_LIGHTS > 0\n for (int i = 0; i < CC_NUM_DIR_LIGHTS; i++) {\n Lighting info = brdf(computeDirectionalLighting(cc_dirLightDirection[i], cc_dirLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_POINT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_POINT_LIGHTS; i++) {\n Lighting info = brdf(computePointLighting(pos_w, cc_pointLightPositionAndRange[i], cc_pointLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n #if CC_NUM_SPOT_LIGHTS > 0\n for (int i = 0; i < CC_NUM_SPOT_LIGHTS; i++) {\n Lighting info = brdf(computeSpotLighting(pos_w, cc_spotLightPositionAndRange[i], cc_spotLightDirection[i], cc_spotLightColor[i]), N, V, glossiness);\n result.diffuse += info.diffuse;\n result.specular += info.specular;\n }\n #endif\n return result;\n}\n#if CC_USE_SHADOW_MAP\n \nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\n \nvarying vec4 posLightspace;\nvarying float vDepth;\nuniform sampler2D cc_shadowMap;\nfloat computeShadow(sampler2D shadowMap, vec4 posLightspace, float bias) {\n vec3 projCoords = posLightspace.xyz / posLightspace.w;\n projCoords = projCoords * 0.5 + 0.5;\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, projCoords.xy));\n float currentDepth = projCoords.z;\n float shadow = (currentDepth - bias > closestDepth) ? 0.0 : 1.0;\n return shadow;\n}\nfloat computeFallOff(float esm, vec2 coords, float frustumEdgeFalloff) {\n float mask = smoothstep(1.0 - frustumEdgeFalloff, 1.0, clamp(dot(coords, coords), 0.0, 1.0));\n return mix(esm, 1.0, mask);\n}\nfloat computeShadowESM(sampler2D shadowMap, vec4 posLightspace, float vDepth, float depthScale, float darkness, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float closestDepth = unpackRGBAToDepth(texture2D(shadowMap, shadowUV));\n \n float esm = clamp(exp(-depthScale * (currentDepth - closestDepth)), 1.0 - darkness, 1.0);\n return computeFallOff(esm, projCoords, frustumEdgeFalloff);\n}\nfloat computeShadowPCF(sampler2D shadowMap, vec4 posLightspace, float vDepth, float darkness, vec2 texelSize, float frustumEdgeFalloff) {\n vec2 projCoords = posLightspace.xy / posLightspace.w;\n vec2 shadowUV = projCoords * 0.5 + vec2(0.5);\n if (shadowUV.x < 0.0 || shadowUV.x > 1.0 || shadowUV.y < 0.0 || shadowUV.y > 1.0) {\n return 1.0;\n }\n float currentDepth = clamp(vDepth, 0.0, 1.0);\n float visibility = 1.0;\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[0] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[1] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[2] * texelSize)) < currentDepth) visibility -= 0.25;\n if (unpackRGBAToDepth(texture2D(shadowMap, shadowUV + poissonDisk[3] * texelSize)) < currentDepth) visibility -= 0.25;\n return computeFallOff(min(1.0, visibility + 1.0 - darkness), projCoords, frustumEdgeFalloff);\n}\nfloat computeShadow() {\n return computeShadowESM(cc_shadowMap, posLightspace, vDepth, cc_shadowParam1.w, cc_shadowParam2.x, cc_shadowParam2.y);\n}\n#endif\nvarying vec3 normal_w;\nvarying vec3 pos_w;\n#if USE_DIFFUSE_TEXTURE || USE_NORMAL_TEXTURE || USE_EMISSIVE_TEXTURE\n varying vec2 uv0;\n#endif\nstruct phongMaterial\n{\n vec3 diffuse;\n vec3 emissive;\n vec3 specular;\n float glossiness;\n float opacity;\n};\n uniform vec4 diffuseColor;\n uniform vec4 emissiveColor;\n uniform vec4 specularColor;\n uniform float glossiness;\n uniform float alphaTestThreshold;\n#if USE_DIFFUSE_TEXTURE\n uniform sampler2D diffuse_texture;\n#endif\n#if USE_EMISSIVE && USE_EMISSIVE_TEXTURE\n uniform sampler2D emissive_texture;\n#endif\n#if USE_SPECULAR && USE_SPECULAR_TEXTURE\n uniform sampler2D specular_texture;\n#endif\n#if USE_NORMAL_TEXTURE\n uniform sampler2D normal_texture;\n vec3 getNormal(vec3 pos, vec3 normal) {\n vec3 q0 = vec3( dFdx( pos.x ), dFdx( pos.y ), dFdx( pos.z ) );\n vec3 q1 = vec3( dFdy( pos.x ), dFdy( pos.y ), dFdy( pos.z ) );\n vec2 st0 = dFdx( uv0.st );\n vec2 st1 = dFdy( uv0.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normal;\n vec3 mapN = texture2D(normal_texture, uv0).rgb * 2.0 - 1.0;\n mapN.xy = 1.0 * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\nphongMaterial getPhongMaterial() {\n phongMaterial result;\n #if USE_DIFFUSE_TEXTURE\n vec4 baseColor = diffuseColor * gammaToLinearSpaceRGBA(texture2D(diffuse_texture, uv0));\n result.diffuse = baseColor.rgb;\n result.opacity = baseColor.a;\n #else\n result.diffuse = diffuseColor.rgb;\n result.opacity = diffuseColor.a;\n #endif\n #if USE_EMISSIVE\n result.emissive = emissiveColor.rgb;\n #if USE_EMISSIVE_TEXTURE\n result.emissive *= gammaToLinearSpaceRGB(texture2D(emissive_texture, uv0).rgb);\n #endif\n #endif\n #if USE_SPECULAR\n result.specular = specularColor.rgb;\n #if USE_SPECULAR_TEXTURE\n result.specular = gammaToLinearSpaceRGB(texture2D(specular_texture, uv0).rgb);\n #endif\n result.glossiness = glossiness;\n #endif\n return result;\n}\nvec4 composePhongShading(Lighting lighting, phongMaterial mtl, float shadow) {\n vec4 o = vec4(0.0, 0.0, 0.0, 1.0);\n \n o.xyz = lighting.diffuse * mtl.diffuse;\n #if USE_EMISSIVE\n o.xyz += mtl.emissive;\n #endif\n #if USE_SPECULAR\n o.xyz += lighting.specular * mtl.specular;\n #endif\n o.xyz *= shadow;\n o.w = mtl.opacity;\n return o;\n}\nvec4 frag () {\n Lighting phongLighting;\n vec3 viewDirection = normalize(cc_cameraPos.xyz - pos_w);\n phongMaterial mtl = getPhongMaterial();\n #if USE_ALPHA_TEST\n if(mtl.opacity < alphaTestThreshold) discard;\n #endif\n vec3 normal = normalize(normal_w);\n #if USE_NORMAL_TEXTURE\n normal = getNormal(pos_w, normal);\n #endif\n phongLighting = getPhongLighting(pos_w, normal, viewDirection, mtl.glossiness);\n phongLighting.diffuse += vec3(0.5); \n #if CC_USE_SHADOW_MAP\n vec4 finalColor = composePhongShading(phongLighting, mtl, computeShadow());\n #else\n vec4 finalColor = composePhongShading(phongLighting, mtl, 1.0);\n #endif\n return linearToGammaSpaceRGBA(finalColor);\n}\nvoid main() { gl_FragColor = frag(); }\n", - "defines": [ - {"name":"USE_DIFFUSE_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]}, - {"name":"CC_USE_SHADOW_MAP", "type":"boolean", "defines":[]}, - {"name":"USE_NORMAL_TEXTURE", "type":"boolean", "defines":[]}, - {"name":"CC_NUM_DIR_LIGHTS", "type":"number", "defines":[]}, - {"name":"CC_NUM_POINT_LIGHTS", "type":"number", "defines":[]}, - {"name":"CC_NUM_SPOT_LIGHTS", "type":"number", "defines":[]}, - {"name":"USE_EMISSIVE", "type":"boolean", "defines":[]}, - {"name":"USE_EMISSIVE_TEXTURE", "type":"boolean", "defines":["USE_EMISSIVE"]}, - {"name":"USE_SPECULAR", "type":"boolean", "defines":[]}, - {"name":"USE_SPECULAR_TEXTURE", "type":"boolean", "defines":["USE_SPECULAR"]}, - {"name":"USE_ALPHA_TEST", "type":"boolean", "defines":[]} - ], - "blocks": [ - {"name": "TexCoords", "size": 16, "defines": [], "binding": 0, "members": [ - {"name":"mainTiling", "type":14, "count":1, "size":8}, - {"name":"mainOffset", "type":14, "count":1, "size":8} - ]}, - {"name": "Constants", "size": 56, "defines": [], "binding": 1, "members": [ - {"name":"diffuseColor", "type":16, "count":1, "size":16}, - {"name":"emissiveColor", "type":16, "count":1, "size":16}, - {"name":"specularColor", "type":16, "count":1, "size":16}, - {"name":"glossiness", "type":13, "count":1, "size":4}, - {"name":"alphaTestThreshold", "type":13, "count":1, "size":4} - ]} - ], - "samplers": [ - {"name":"diffuse_texture", "type":29, "count":1, "defines":["USE_DIFFUSE_TEXTURE"], "binding":2}, - {"name":"emissive_texture", "type":29, "count":1, "defines":["USE_EMISSIVE", "USE_EMISSIVE_TEXTURE"], "binding":3}, - {"name":"specular_texture", "type":29, "count":1, "defines":["USE_SPECULAR", "USE_SPECULAR_TEXTURE"], "binding":4}, - {"name":"normal_texture", "type":29, "count":1, "defines":["USE_NORMAL_TEXTURE"], "binding":5} - ], - "dependencies": {"USE_NORMAL_TEXTURE":"OES_standard_derivatives"} - }, - { - "name": "builtin-effect-phong|shadow-depth-vs:vert|shadow-depth-fs:frag", - "vert": "\nattribute vec3 a_position;\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 float vDepth;\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 mat4 skinMat = skinMatrix();\n pos = skinMat * pos;\n #endif\n \n vDepth = ((gl_Position.z + cc_shadowParam1.x) / (cc_shadowParam1.x + cc_shadowParam1.y)) + cc_shadowParam1.z;\n return cc_matViewProjLight * cc_matWorld * pos;\n}\nvoid main() { gl_Position = vert(); }\n", - "frag": "\nvarying float vDepth;\nvec4 packDepthToRGBA(float depth) {\n vec4 ret = vec4(1.0, 255.0, 65025.0, 160581375.0) * depth;\n ret = fract(ret);\n ret -= ret.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return ret;\n}\nfloat unpackRGBAToDepth(vec4 color) {\n return dot(color, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nvec4 frag() {\n \n \n return packDepthToRGBA(vDepth);\n \n \n}\nvoid main() { gl_FragColor = frag(); }\n", - "defines": [ - {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]}, - {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]} - ], - "blocks": [], - "samplers": [], - "dependencies": {} - } - ] - }, { "name": "builtin-effect-skybox", "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}], diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts index ba271c4f83..56de33dff6 100644 --- a/cocos/3d/framework/light-component.ts +++ b/cocos/3d/framework/light-component.ts @@ -165,8 +165,8 @@ export default class LightComponent extends Component { } set type (val) { - this._type = val; this._destroyLight(); + this._type = parseInt(val); this._createLight(); } @@ -279,6 +279,9 @@ export default class LightComponent extends Component { this.range = this._range; this.spotAngle = this._spotAngle; break; + default: + console.warn(`illegal light type ${this._type}`); + return; } if (!this._light) { console.warn('we don\'t support this many lights in forward pipeline.'); } this.color = this._color; diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index 2488cfc3bd..e21d23bb81 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -104,7 +104,7 @@ export class ModelComponent extends RenderableComponent { set mesh (val) { this._mesh = val; - this._updateModels(true); + this._updateModels(); } /** @@ -167,12 +167,11 @@ export class ModelComponent extends RenderableComponent { } public onEnable () { - this._updateModels(); + if (!this._model) { this._updateModels(); } this._updateCastShadow(); this._updateReceiveShadow(); - if (this._model) { - this._model.enabled = this.enabledInHierarchy; + this._model.enabled = true; } } @@ -188,11 +187,8 @@ export class ModelComponent extends RenderableComponent { } } - protected _updateModels (forceUpdate: boolean = false) { - if (!this.enabled || !this.node._scene || !this._mesh || (this._model && !forceUpdate)) { - if (this._model) { - this._model.enabled = false; - } + protected _updateModels () { + if (!this.enabledInHierarchy || !this.node._scene || !this._mesh) { return; } @@ -205,6 +201,10 @@ export class ModelComponent extends RenderableComponent { this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); this._updateModelParams(); + + if (this._model) { + this._model.enabled = true; + } } protected _createModel () { @@ -252,7 +252,7 @@ export class ModelComponent extends RenderableComponent { } private _updateCastShadow () { - if (!this.enabled || !this._model) { + if (!this.enabledInHierarchy || !this._model) { return; } if (this._shadowCastingMode === ModelShadowCastingMode.Off) { @@ -271,15 +271,15 @@ export class ModelComponent extends RenderableComponent { } private _updateReceiveShadow () { - if (!this.enabled || !this._model) { + if (!this.enabledInHierarchy || !this._model) { return; } - for (let i = 0; i < this._model.subModelNum; ++i) { - const subModel = this._model.getSubModel(i); - // if (subModel._defines['CC_USE_SHADOW_MAP'] != undefined) { - // this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); - // } - } + // for (let i = 0; i < this._model.subModelNum; ++i) { + // const subModel = this._model.getSubModel(i); + // if (subModel._defines['CC_USE_SHADOW_MAP'] != undefined) { + // this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); + // } + // } } private _getBuiltinMaterial () { diff --git a/cocos/pipeline/render-pipeline.ts b/cocos/pipeline/render-pipeline.ts index 901713962f..369f8dad4a 100644 --- a/cocos/pipeline/render-pipeline.ts +++ b/cocos/pipeline/render-pipeline.ts @@ -1,6 +1,6 @@ import { intersect } from '../3d/geom-utils'; import { Root } from '../core/root'; -import { Mat4, Vec3 } from '../core/value-types'; +import { Mat4 } from '../core/value-types'; import { mat4, vec3 } from '../core/vmath'; import { GFXBuffer } from '../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXType } from '../gfx/define'; @@ -30,13 +30,13 @@ export class UBOGlobal { 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 + 16; - public static POINT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 16; - public static POINT_LIGHT_COLOR_OFFSET: number = UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + 16; - public static SPOT_LIGHT_POS_RANGE_OFFSET: number = UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 16; - public static SPOT_LIGHT_DIR_OFFSET: number = UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + 16; - public static SPOT_LIGHT_COLOR_OFFSET: number = UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 16; - public static COUNT: number = UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 16; + 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 SIZE: number = UBOGlobal.COUNT * 4; public static BLOCK: GFXUniformBlock = { @@ -363,11 +363,11 @@ export abstract class RenderPipeline { const light = dLights[i]; if (light && light.enabled) { light.update(); - this._uboGlobal.view.set(light.directionArray, UBOGlobal.DIR_LIGHT_DIR_OFFSET + 4 * i); - this._uboGlobal.view.set(light.colorData, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 4 * i); + 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 + 4 * i); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.DIR_LIGHT_COLOR_OFFSET + 4 * i); + 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; @@ -375,11 +375,11 @@ export abstract class RenderPipeline { const light = pLights[i]; if (light && light.enabled) { light.update(); - this._uboGlobal.view.set(light.positionAndRange, UBOGlobal.POINT_LIGHT_POS_RANGE_OFFSET + 4 * i); - this._uboGlobal.view.set(light.colorData, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 4 * i); + 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 + 4 * i); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.POINT_LIGHT_COLOR_OFFSET + 4 * i); + 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; @@ -387,13 +387,13 @@ export abstract class RenderPipeline { const light = sLights[i]; if (light && light.enabled) { light.update(); - this._uboGlobal.view.set(light.positionAndRange, UBOGlobal.SPOT_LIGHT_POS_RANGE_OFFSET + 4 * i); - this._uboGlobal.view.set(light.directionArray, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 4 * i); - this._uboGlobal.view.set(light.colorData, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 4 * i); + 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 + 4 * i); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_DIR_OFFSET + 4 * i); - this._uboGlobal.view.set(_idVec4Array, UBOGlobal.SPOT_LIGHT_COLOR_OFFSET + 4 * i); + 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); } } diff --git a/cocos/renderer/scene/directional-light.ts b/cocos/renderer/scene/directional-light.ts index 0072aa447b..4b254c3b4e 100644 --- a/cocos/renderer/scene/directional-light.ts +++ b/cocos/renderer/scene/directional-light.ts @@ -4,7 +4,7 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; import { Node } from '../../scene-graph/node'; -const _forward = new Vec3(0, 0, 1); +const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); const _qt = new Quat(); diff --git a/cocos/renderer/scene/light.ts b/cocos/renderer/scene/light.ts index 0c706a24a1..a8678cce03 100644 --- a/cocos/renderer/scene/light.ts +++ b/cocos/renderer/scene/light.ts @@ -2,10 +2,10 @@ import { RenderScene } from './render-scene'; import { Node } from '../../scene-graph/node'; export enum LightType { - UNKNOWN, DIRECTIONAL, POINT, SPOT, + UNKNOWN, } export class Light { diff --git a/cocos/renderer/scene/spot-light.ts b/cocos/renderer/scene/spot-light.ts index f741b94093..805f540a9d 100644 --- a/cocos/renderer/scene/spot-light.ts +++ b/cocos/renderer/scene/spot-light.ts @@ -4,7 +4,7 @@ import { Light, LightType } from './light'; import { RenderScene } from './render-scene'; import { Node } from '../../scene-graph/node'; -const _forward = new Vec3(0, 0, 1); +const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); const _qt = new Quat(); diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 058a9d3bbf..c9acd92d01 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -567,9 +567,9 @@ class Node extends EventTarget(BaseNode) { */ public setPosition (val: Vec3 | number, y?: number, z?: number) { if (y === undefined || z === undefined) { - vec3.copy(this._lpos, val); + vec3.copy(this._lpos, val as Vec3); } else if (arguments.length === 3) { - vec3.set(this._lpos, val, y, z); + vec3.set(this._lpos, val as number, y, z); } vec3.copy(this._pos, this._lpos); @@ -607,9 +607,9 @@ class Node extends EventTarget(BaseNode) { public setRotation (val: Quat | number, y?: number, z?: number, w?: number) { if (y === undefined || z === undefined || w === undefined) { - quat.copy(this._lrot, val); + quat.copy(this._lrot, val as Quat); } else if (arguments.length === 4) { - quat.set(this._lrot, val, y, z, w); + quat.set(this._lrot, val as number, y, z, w); } quat.copy(this._rot, this._lrot); this._eulerDirty = true; @@ -669,9 +669,9 @@ class Node extends EventTarget(BaseNode) { */ public setScale (val: Vec3 | number, y?: number, z?: number) { if (y === undefined || z === undefined) { - vec3.copy(this._lscale, val); + vec3.copy(this._lscale, val as Vec3); } else if (arguments.length === 3) { - vec3.set(this._lscale, val, y, z); + vec3.set(this._lscale, val as number, y, z); } vec3.copy(this._scale, this._lscale); @@ -714,9 +714,9 @@ class Node extends EventTarget(BaseNode) { */ public setWorldPosition (val: Vec3 | number, y?: number, z?: number) { if (y === undefined || z === undefined) { - vec3.copy(this._pos, val); + vec3.copy(this._pos, val as Vec3); } else if (arguments.length === 3) { - vec3.set(this._pos, val, y, z); + vec3.set(this._pos, val as number, y, z); } const parent = this._parent; const local = this._lpos; @@ -771,9 +771,9 @@ class Node extends EventTarget(BaseNode) { */ public setWorldRotation (val: Quat | number, y?: number, z?: number, w?: number) { if (y === undefined || z === undefined || w === undefined) { - quat.copy(this._rot, val); + quat.copy(this._rot, val as Quat); } else if (arguments.length === 4) { - quat.set(this._rot, val, y, z, w); + quat.set(this._rot, val as number, y, z, w); } if (this._parent) { this._parent.getWorldRotation(q_a); @@ -894,11 +894,8 @@ class Node extends EventTarget(BaseNode) { */ public getWorldRS (out?: Mat4): Mat4 { this.updateWorldTransformFull(); - if (out) { - mat4.copy(out, this._mat); - } else { - out = mat4.copy(new Mat4(), this._mat); - } + if (out === undefined) { out = new Mat4(); } + mat4.copy(out, this._mat); out.m12 = 0; out.m13 = 0; out.m14 = 0; return out; } From d1ade1d72149456b78f4c1b76b4616f7cf32d9b6 Mon Sep 17 00:00:00 2001 From: Jone <350791117@qq.com> Date: Fri, 25 Jan 2019 16:35:52 +0800 Subject: [PATCH 263/267] add UICanvas fix current ui priority sort and walk mode conflicts --- cocos/3d/ui/assembler/sprite/bar-filled.ts | 2 +- cocos/3d/ui/assembler/sprite/radial-filled.ts | 2 +- cocos/3d/ui/assembler/sprite/simple.ts | 2 +- cocos/3d/ui/assembler/sprite/sliced.ts | 2 +- cocos/3d/ui/assembler/sprite/tiled.ts | 2 +- cocos/3d/ui/components/canvas-component.ts | 26 ++--- cocos/3d/ui/components/ui-render-component.ts | 24 ++++- cocos/renderer/ui/ui.ts | 101 +++++++++++++----- 8 files changed, 114 insertions(+), 47 deletions(-) diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/3d/ui/assembler/sprite/bar-filled.ts index 2df303fa4c..c039b5d77a 100644 --- a/cocos/3d/ui/assembler/sprite/bar-filled.ts +++ b/cocos/3d/ui/assembler/sprite/bar-filled.ts @@ -292,7 +292,7 @@ export const barFilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.texture = sprite.spriteFrame!; - commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; + commitBuffer.priority = sprite.priority; renderer.addToQueue(commitBuffer); }, }; diff --git a/cocos/3d/ui/assembler/sprite/radial-filled.ts b/cocos/3d/ui/assembler/sprite/radial-filled.ts index 0dadfd690d..2175eeac93 100644 --- a/cocos/3d/ui/assembler/sprite/radial-filled.ts +++ b/cocos/3d/ui/assembler/sprite/radial-filled.ts @@ -381,7 +381,7 @@ export const radialFilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = comp.material!; commitBuffer.texture = comp.spriteFrame!; - commitBuffer.camera = renderer.getScreen(comp.visibility)!.camera!; + commitBuffer.priority = comp.priority; renderer.addToQueue(commitBuffer); }, }; diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts index b2d583fb56..45c66cc429 100644 --- a/cocos/3d/ui/assembler/sprite/simple.ts +++ b/cocos/3d/ui/assembler/sprite/simple.ts @@ -141,7 +141,7 @@ export const simple: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.texture = sprite.spriteFrame!; - commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; + commitBuffer.priority = sprite.priority; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/3d/ui/assembler/sprite/sliced.ts index d700e79790..979d3e30a0 100644 --- a/cocos/3d/ui/assembler/sprite/sliced.ts +++ b/cocos/3d/ui/assembler/sprite/sliced.ts @@ -172,7 +172,7 @@ export const sliced: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.texture = sprite.spriteFrame!; - commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; + commitBuffer.priority = sprite.priority; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/3d/ui/assembler/sprite/tiled.ts b/cocos/3d/ui/assembler/sprite/tiled.ts index bc686f44bc..234d66da96 100644 --- a/cocos/3d/ui/assembler/sprite/tiled.ts +++ b/cocos/3d/ui/assembler/sprite/tiled.ts @@ -241,7 +241,7 @@ export const tilled: IAssembler = { commitBuffer.meshBuffer = buffer; commitBuffer.material = sprite.material!; commitBuffer.texture = sprite.spriteFrame!; - commitBuffer.camera = renderer.getScreen(sprite.visibility)!.camera!; + commitBuffer.priority = sprite.priority; renderer.addToQueue(commitBuffer); }, diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 7841792d91..fde3a3a512 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -95,18 +95,18 @@ export class CanvasComponent extends Component { } } - /** - * !#en priority in render - * !#zh 显示优先级 - */ - @property - get priority () { - return this._priority; - } + // /** + // * !#en priority in render + // * !#zh 显示优先级 + // */ + // @property + // get priority () { + // return this._priority; + // } - set priority (value: number) { - this._priority = value; - } + // set priority (value: number) { + // this._priority = value; + // } get visibility () { if (this._camera) { @@ -133,8 +133,8 @@ export class CanvasComponent extends Component { private _fitWidth = false; @property private _fitHeight = true; - @property - private _priority = 0; + // @property + // private _priority = 0; private _thisOnResized: ()=>void; diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts index e97251a0a0..87b5b57160 100644 --- a/cocos/3d/ui/components/ui-render-component.ts +++ b/cocos/3d/ui/components/ui-render-component.ts @@ -95,11 +95,29 @@ export class UIRenderComponent extends RenderableComponent { this._updateBlendFunc(true); } - get color () { + /** + * !#en render order, render order according to width, and arrange once under the same level node. + * !#zh 渲染先后顺序,按照广度渲染排列,同级节点下进行一次排列 + */ + @property + get priority() { + return this._priority; + } + + set priority(value) { + this._priority = value; + } + + /** + * !#en render color + * !#zh 渲染颜色 + * @property color + */ + get color() { return this._color; } - set color (value) { + set color(value) { if (this._color === value) { return; } @@ -127,6 +145,8 @@ export class UIRenderComponent extends RenderableComponent { protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA; @property protected _color: Color = Color.WHITE; + @property + protected _priority: number = 0; protected _renderData: RenderData | null = null; // _allocedDatas = []; // _vertexFormat = null; diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 86186efead..5e03d89b72 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -25,10 +25,10 @@ import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler import { GFXUniformBlock } from '../../gfx/shader'; import { GFXTextureView } from '../../gfx/texture-view'; import { vfmt } from '../../gfx/vertex-format-sample'; -import { BaseNode } from '../../scene-graph/base-node'; import { Camera } from '../scene/camera'; import { RenderScene } from '../scene/render-scene'; import { IUIMaterialInfo, UIMaterial } from './ui-material'; +import { Node } from '../../scene-graph/node'; export class UBOUI { public static MAT_VIEW_PROJ_OFFSET: number = 0; @@ -76,7 +76,11 @@ export interface IUIRenderData { meshBuffer: MeshBuffer; material: Material; texture: SpriteFrame; + priority: number; +} +export interface IUICanvas { camera: Camera; + datas: IUIRenderData[]; } export class UI { @@ -107,6 +111,10 @@ export class UI { private _batches: CachedArray; private _bufferInitData: IMeshBufferInitData | null = null; private _commitUIRenderDatas: IUIRenderData[] = []; + private _commitUICanvasDatas: IUICanvas[] = []; + private _sortChildList: RecyclePool = new RecyclePool(() => { + return []; + }, 128); constructor (private _root: Root) { this._device = _root.device; @@ -201,15 +209,14 @@ export class UI { this._screens.push(comp); } - public getScreen (visibility: number) { - for (const screen of this._screens) { + public getScreen(visibility: number) { + this._screens.forEach((screen) => { if (screen.camera) { if (screen.camera.visibility === visibility) { return screen; } } - } - + }) return null; } @@ -237,7 +244,7 @@ export class UI { } public update (dt: number) { - + for (let i = 0; i < this._batches.length; ++i) { const batch = this._batches.array[i]; batch.clear(); @@ -245,7 +252,7 @@ export class UI { } this._batches.clear(); - this._commitUIRenderDatas = []; + // this._commitUIRenderDatas = []; this._renderScreens(); @@ -324,16 +331,52 @@ export class UI { } } - private _walk (node, fn1, fn2, level = 0) { - level += 1; - const len = node.children.length; - fn1(node); - for (let i = 0; i < len; ++i) { - const child = node.children[i]; - this._walk(child, fn1, fn2, level); + // skip the first object + private _walk (renderComp, fn1, fn2, level = 0) { + let renderCompList; + if(level === 0){ + level+=1; + renderCompList = this._defineNodeOrder(renderComp.children); + renderCompList.forEach(comp => { + this._walk(comp, fn1, fn2, level); + }); + this._sortChildList.remove(renderCompList); + return; } - fn2(node); + // const len = node.children.length; + fn1(renderComp); + + renderCompList = this._defineNodeOrder(renderComp.node.children); + for (const comp of renderCompList){ + this._walk(comp, fn1, fn2, level); + } + // for (let i = 0; i < len; ++i) { + // const child = node.children[i]; + // this._walk(child, fn1, fn2, level); + // } + + + this._sortChildList.remove(renderCompList); + fn2(renderComp); + level += 1; + } + + private _defineNodeOrder(childs: Node[]) { + let sortList = this._sortChildList.add(); + + childs.forEach((child) => { + let renderComp = child.getComponent(UIRenderComponent); + if (renderComp) { + sortList.push(renderComp); + } + }) + + sortList.sort((a, b) => { + return (a.priority - b.priority); + }); + + return sortList; } private _renderScreens () { @@ -343,24 +386,28 @@ export class UI { continue; } // this._currScreen = screen; + this._commitUIRenderDatas.length = 0; - this._walk(screen.node, (c: BaseNode) => { - const renderComponent = c.getComponent(UIRenderComponent); - if (renderComponent && renderComponent.enabledInHierarchy) { - this._commitComp(renderComponent); + this._walk(screen.node, (c: UIRenderComponent) => { + // const renderComponent = c.getComponent(UIRenderComponent); + if (c.enabledInHierarchy) { + this._commitComp(c); + } + }, (c: UIRenderComponent) => { + // const renderComponent = c.getComponent(UIRenderComponent); + if (c.enabledInHierarchy) { + this._postCommitComp(c); } - }, (c: BaseNode) => { - const renderComponent = c.getComponent(UIRenderComponent); - if (renderComponent && renderComponent.enabledInHierarchy) { - this._postCommitComp(renderComponent); - } }); + + this._commitUICanvasDatas.push({ camera: screen.camera!, datas: this._commitUIRenderDatas }); } } private _reset () { this._bufferPool.reset(); this._commitUIRenderDataPool.reset(); + this._commitUICanvasDatas.length = 0; } private _commitComp (comp: UIRenderComponent) { @@ -384,7 +431,7 @@ export class UI { let curBufferBatch: UIBufferBatch = this._bufferBatches[bufferBatchIdx++]; let idxCount = 0; let vertCount = 0; - + let vf32: Float32Array; let vui16: Uint16Array; let vbSize = 0; @@ -441,7 +488,7 @@ export class UI { isNewBatch = true; curCamera = uiRenderData.camera; } - + if (curTexView !== uiRenderData.texture.getGFXTextureView()) { curTexView = uiRenderData.texture.getGFXTextureView(); isNewBatch = true; @@ -454,7 +501,7 @@ export class UI { batch.uiMaterial = this._uiMaterial!; batch.texView = curTexView!; batch.idxCount = idxCount; - + this._batches.push(batch); } } // for From 10645448290b43bc585c84a00b2b0b6fd17414f9 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 25 Jan 2019 16:44:54 +0800 Subject: [PATCH 264/267] fix default material fallback --- cocos/3d/framework/model-component.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts index e21d23bb81..2063beb14c 100644 --- a/cocos/3d/framework/model-component.ts +++ b/cocos/3d/framework/model-component.ts @@ -233,10 +233,10 @@ export class ModelComponent extends RenderableComponent { if (this._model == null) { return; } - this._onRebuildPSO(idx, material); + this._onRebuildPSO(idx, material || this._getBuiltinMaterial()); } - protected _onRebuildPSO (idx, material) { + protected _onRebuildPSO (idx: number, material: Material) { if (this._model) { this._model.setSubModelMaterial(idx, material); } From 39927e48b587c995c531f3243baf27b7eba7260f Mon Sep 17 00:00:00 2001 From: zhuxuguang <247274249@qq.com> Date: Fri, 25 Jan 2019 16:47:08 +0800 Subject: [PATCH 265/267] refactor particle --- .../{color-overtime.js => color-overtime.ts} | 11 +- .../{curve-range.js => curve-range.ts} | 30 +- .../{force-overtime.js => force-overtime.ts} | 39 ++- .../{gradient-range.js => gradient-range.ts} | 108 +++--- .../animator/{gradient.js => gradient.ts} | 64 ++-- ...overtime.js => limit-velocity-overtime.ts} | 57 ++-- .../particle/animator/optimized-curve.js | 297 ----------------- .../particle/animator/optimized-curve.ts | 313 ++++++++++++++++++ ...ation-overtime.js => rotation-overtime.ts} | 31 +- .../{size-overtime.js => size-overtime.ts} | 26 +- ...ture-animation.js => texture-animation.ts} | 93 +++--- ...ocity-overtime.js => velocity-overtime.ts} | 45 ++- .../{shape-module.js => shape-module.ts} | 168 ++++++---- ...nction.js => particle-general-function.ts} | 55 +-- ...ponent.js => particle-system-component.ts} | 296 +++++++---------- .../renderer/particle-system-renderer.ts | 13 +- cocos/3d/geom-utils/{curve.js => curve.ts} | 132 ++++---- cocos/3d/memop/recycle-pool.ts | 2 +- 18 files changed, 925 insertions(+), 855 deletions(-) rename cocos/3d/framework/particle/animator/{color-overtime.js => color-overtime.ts} (78%) rename cocos/3d/framework/particle/animator/{curve-range.js => curve-range.ts} (73%) rename cocos/3d/framework/particle/animator/{force-overtime.js => force-overtime.ts} (50%) rename cocos/3d/framework/particle/animator/{gradient-range.js => gradient-range.ts} (56%) rename cocos/3d/framework/particle/animator/{gradient.js => gradient.ts} (66%) rename cocos/3d/framework/particle/animator/{limit-velocity-overtime.js => limit-velocity-overtime.ts} (64%) delete mode 100644 cocos/3d/framework/particle/animator/optimized-curve.js create mode 100644 cocos/3d/framework/particle/animator/optimized-curve.ts rename cocos/3d/framework/particle/animator/{rotation-overtime.js => rotation-overtime.ts} (65%) rename cocos/3d/framework/particle/animator/{size-overtime.js => size-overtime.ts} (69%) rename cocos/3d/framework/particle/animator/{texture-animation.js => texture-animation.ts} (51%) rename cocos/3d/framework/particle/animator/{velocity-overtime.js => velocity-overtime.ts} (51%) rename cocos/3d/framework/particle/emitter/{shape-module.js => shape-module.ts} (74%) rename cocos/3d/framework/particle/{particle-general-function.js => particle-general-function.ts} (63%) rename cocos/3d/framework/particle/{particle-system-component.js => particle-system-component.ts} (58%) rename cocos/3d/geom-utils/{curve.js => curve.ts} (53%) diff --git a/cocos/3d/framework/particle/animator/color-overtime.js b/cocos/3d/framework/particle/animator/color-overtime.ts similarity index 78% rename from cocos/3d/framework/particle/animator/color-overtime.js rename to cocos/3d/framework/particle/animator/color-overtime.ts index 0076e83137..082de437cb 100644 --- a/cocos/3d/framework/particle/animator/color-overtime.js +++ b/cocos/3d/framework/particle/animator/color-overtime.ts @@ -2,6 +2,9 @@ import { color4, pseudoRandom } from '../../../../core/vmath'; import { CCClass } from '../../../../core/data'; import GradientRange from './gradient-range'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import Particle from '../particle'; + +// tslint:disable: max-line-length const COLOR_OVERTIME_RAND_OFFSET = 91041; @@ -9,14 +12,14 @@ const COLOR_OVERTIME_RAND_OFFSET = 91041; export default class ColorOvertimeModule { @property - enable = false; + public enable = false; @property({ - type: GradientRange + type: GradientRange, }) - color = new GradientRange(); + public color = new GradientRange(); - animate(particle) { + public animate (particle: Particle) { if (this.enable) { color4.multiply(particle.color, particle.startColor01, this.color.evaluate(1.0 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET))); } diff --git a/cocos/3d/framework/particle/animator/curve-range.js b/cocos/3d/framework/particle/animator/curve-range.ts similarity index 73% rename from cocos/3d/framework/particle/animator/curve-range.js rename to cocos/3d/framework/particle/animator/curve-range.ts index 501e516025..0e47b42c6d 100644 --- a/cocos/3d/framework/particle/animator/curve-range.js +++ b/cocos/3d/framework/particle/animator/curve-range.ts @@ -8,49 +8,49 @@ const Mode = Enum({ Constant: 0, Curve: 1, TwoCurves: 2, - TwoConstants: 3 + TwoConstants: 3, }); @ccclass('cc.CurveRange') export default class CurveRange { @property({ - type: Mode + type: Mode, }) - mode = Mode.Constant; + public mode = Mode.Constant; @property({ - type: AnimationCurve + type: AnimationCurve, }) - curve = new AnimationCurve(); + public curve = new AnimationCurve(); @property({ - type: AnimationCurve + type: AnimationCurve, }) - curveMin = new AnimationCurve(); + public curveMin = new AnimationCurve(); @property({ - type: AnimationCurve + type: AnimationCurve, }) - curveMax = new AnimationCurve(); + public curveMax = new AnimationCurve(); @property - constant = 0; + public constant = 0; @property - constantMin = 0; + public constantMin = 0; @property - constantMax = 0; + public constantMax = 0; @property - multiplier = 1; + public multiplier = 1; - constructor() { + constructor () { } - evaluate(time, rndRatio) { + public evaluate (time: number, rndRatio: number) { switch (this.mode) { case Mode.Constant: return this.constant; diff --git a/cocos/3d/framework/particle/animator/force-overtime.js b/cocos/3d/framework/particle/animator/force-overtime.ts similarity index 50% rename from cocos/3d/framework/particle/animator/force-overtime.js rename to cocos/3d/framework/particle/animator/force-overtime.ts index cd5cac5587..3c3c35068f 100644 --- a/cocos/3d/framework/particle/animator/force-overtime.js +++ b/cocos/3d/framework/particle/animator/force-overtime.ts @@ -4,46 +4,53 @@ import CurveRange from './curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +// tslint:disable: max-line-length const FORCE_OVERTIME_RAND_OFFSET = 212165; @ccclass('cc.ForceOvertimeModule') export default class ForceOvertimeModule { @property - enable = false; + public enable = false; @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); - @property - space = Space.Local; + @property({ + type: Space, + }) + public space = Space.Local; // TODO:currently not supported - randomized = false; + public randomized = false; - constructor() { + private rotation: quat; + private needTransform: boolean; + + constructor () { this.rotation = quat.create(); + this.needTransform = false; } - update(space, worldTransform) { - this.needTransform = calculateTransform(space, this._space, worldTransform, this.rotation); + public update (space, worldTransform) { + this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } - animate(p, dt) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET))); + public animate (p, dt) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET))); if (this.needTransform) { vec3.transformQuat(force, force, this.rotation); } diff --git a/cocos/3d/framework/particle/animator/gradient-range.js b/cocos/3d/framework/particle/animator/gradient-range.ts similarity index 56% rename from cocos/3d/framework/particle/animator/gradient-range.js rename to cocos/3d/framework/particle/animator/gradient-range.ts index d716ba4d82..63f81192b4 100644 --- a/cocos/3d/framework/particle/animator/gradient-range.js +++ b/cocos/3d/framework/particle/animator/gradient-range.ts @@ -4,6 +4,8 @@ import Gradient from './gradient'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +// tslint:disable: max-line-length + const GRADIENT_MODE_FIX = 0; const GRADIENT_MODE_BLEND = 1; @@ -18,42 +20,42 @@ const Mode = Enum({ Gradient: 1, TwoColors: 2, TwoGradients: 3, - RandomColor: 4 + RandomColor: 4, }); @ccclass('cc.GradientRange') export default class GradientRange { @property({ - type: Mode + type: Mode, }) - mode = Mode.Color; + public mode = Mode.Color; @property - color = cc.Color.WHITE; + public color = cc.Color.WHITE; @property - colorMin = cc.Color.WHITE; + public colorMin = cc.Color.WHITE; @property - colorMax = cc.Color.WHITE; + public colorMax = cc.Color.WHITE; @property({ - type: Gradient + type: Gradient, }) - gradient = new Gradient(); + public gradient = new Gradient(); @property({ - type: Gradient + type: Gradient, }) - gradientMin = new Gradient(); + public gradientMin = new Gradient(); @property({ - type: Gradient + type: Gradient, }) - gradientMax = new Gradient(); + public gradientMax = new Gradient(); - evaluate(time, rndRatio) { + public evaluate (time: number, rndRatio: number) { switch (this.mode) { case Mode.Color: return this.color; @@ -84,60 +86,72 @@ export default class GradientRange { // }); export class GradientUniform { - constructor(gr) { + public gr: GradientRange; + public minColor: Float32Array; + public maxColor: Float32Array; + public minColorKeyTime: Float32Array; + public minColorKeyValue: Float32Array; + public minAlphaKeyTime: Float32Array; + public minAlphaKeyValue: Float32Array; + public maxColorKeyTime: Float32Array; + public maxColorKeyValue: Float32Array; + public maxAlphaKeyTime: Float32Array; + public maxAlphaKeyValue: Float32Array; + + constructor (gr: GradientRange) { this.gr = gr; - if (gr._mode == 'color') { + if (gr.mode === 'color') { this.minColor = new Float32Array(4); - color4.array(this.minColor, gr._color); - } else if (gr._mode == 'twoColors') { + color4.array(this.minColor, gr.color); + } else if (gr.mode === 'twoColors') { this.minColor = new Float32Array(4); this.maxColor = new Float32Array(4); - color4.array(this.minColor, gr._colorMin); - color4.array(this.maxColor, gr._colorMax); - } else if (gr._mode == 'gradient') { - this.minColorKeyTime = new Float32Array(gr._gradient._colorKeys.length); + color4.array(this.minColor, gr.colorMin); + color4.array(this.maxColor, gr.colorMax); + } else if (gr.mode === 'gradient') { + this.minColorKeyTime = new Float32Array(gr.gradient.colorKeys.length); this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length); - this.minAlphaKeyTime = new Float32Array(gr._gradient._alphaKeys.length); + this.minAlphaKeyTime = new Float32Array(gr.gradient.alphaKeys.length); this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length); - this.constructor.generateGradientUniform(gr._gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); - } else if (gr._mode == 'twoGradients') { - this.minColorKeyTime = new Float32Array(gr._gradientMin._colorKeys.length); + this.constructor.generateGradientUniform(gr.gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); + } else if (gr.mode === 'twoGradients') { + this.minColorKeyTime = new Float32Array(gr.gradientMin.colorKeys.length); this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length); - this.minAlphaKeyTime = new Float32Array(gr._gradientMin._alphaKeys.length); + this.minAlphaKeyTime = new Float32Array(gr.gradientMin.alphaKeys.length); this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length); - this.constructor.generateGradientUniform(gr._gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); - this.maxColorKeyTime = new Float32Array(gr._gradientMax._colorKeys.length); + this.constructor.generateGradientUniform(gr.gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue); + this.maxColorKeyTime = new Float32Array(gr.gradientMax.colorKeys.length); this.maxColorKeyValue = new Float32Array(3 * this.maxColorKeyTime.length); - this.maxAlphaKeyTime = new Float32Array(gr._gradientMax._alphaKeys.length); + this.maxAlphaKeyTime = new Float32Array(gr.gradientMax.alphaKeys.length); this.maxAlphaKeyValue = new Float32Array(this.maxAlphaKeyTime.length); - this.constructor.generateGradientUniform(gr._gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue); + this.constructor.generateGradientUniform(gr.gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue); } } - uploadUniform(device, name) { - if (this.gr._mode == 'color') { + public uploadUniform (device: any, name: string) { + if (this.gr.mode === 'color') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_COLOR); device.setUniform('u_' + name + '_minColor', this.minColor); - } else if (this.gr._mode == 'twoColors') { + } else if (this.gr.mode === 'twoColors') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_COLOR); device.setUniform('u_' + name + '_minColor', this.minColor); device.setUniform('u_' + name + '_maxColor', this.maxColor); - } else if (this.gr._mode == 'gradient') { + } else if (this.gr.mode === 'gradient') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_GRADIENT); - device.setUniform('u_' + name + '_minGradMode', this.gr._gradient._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); + device.setUniform('u_' + name + '_minGradMode', this.gr.gradient.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue); device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime); device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue); device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime); - } else if (this.gr._mode == 'twoGradients') { + } else if (this.gr.mode === 'twoGradients') { device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_GRADIENT); - device.setUniform('u_' + name + '_minGradMode', this.gr._gradientMin._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); + device.setUniform('u_' + name + '_minGradMode', this.gr.gradientMin.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue); device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime); device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue); device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime); - device.setUniform('u_' + name + '_maxGradMode', this.gr._gradientMax._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); + device.setUniform('u_' + name + '_maxGradMode', this.gr.gradientMax.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX); device.setUniform('u_' + name + '_maxColorKeyValue', this.maxColorKeyValue); device.setUniform('u_' + name + '_maxColorKeyTime', this.maxColorKeyTime); device.setUniform('u_' + name + '_maxAlphaKeyValue', this.maxAlphaKeyValue); @@ -145,16 +159,16 @@ export class GradientUniform { } } - static generateGradientUniform(gradient, colorKeyTime, colorKeyValue, alphaKeyTime, alphaKeyValue) { - for (let i = 0; i < gradient._colorKeys.length; i++) { - colorKeyTime[i] = gradient._colorKeys[i]._time; - colorKeyValue[i * 3] = gradient._colorKeys[i]._color.r; - colorKeyValue[i * 3 + 1] = gradient._colorKeys[i]._color.g; - colorKeyValue[i * 3 + 2] = gradient._colorKeys[i]._color.b; + public static generateGradientUniform (gradient: Gradient, colorKeyTime: number, colorKeyValue: Float32Array, alphaKeyTime: number, alphaKeyValue: Float32Array) { + for (let i = 0; i < gradient.colorKeys.length; i++) { + colorKeyTime[i] = gradient.colorKeys[i].time; + colorKeyValue[i * 3] = gradient.colorKeys[i].color.r; + colorKeyValue[i * 3 + 1] = gradient.colorKeys[i].color.g; + colorKeyValue[i * 3 + 2] = gradient.colorKeys[i].color.b; } - for (let i = 0; i < gradient._alphaKeys.length; i++) { - alphaKeyTime[i] = gradient._alphaKeys[i]._time; - alphaKeyValue[i] = gradient._alphaKeys[i]._alpha; + for (let i = 0; i < gradient.alphaKeys.length; i++) { + alphaKeyTime[i] = gradient.alphaKeys[i].time; + alphaKeyValue[i] = gradient.alphaKeys[i].alpha; } } } diff --git a/cocos/3d/framework/particle/animator/gradient.js b/cocos/3d/framework/particle/animator/gradient.ts similarity index 66% rename from cocos/3d/framework/particle/animator/gradient.js rename to cocos/3d/framework/particle/animator/gradient.ts index 2061b768d2..e1d81d01e2 100644 --- a/cocos/3d/framework/particle/animator/gradient.js +++ b/cocos/3d/framework/particle/animator/gradient.ts @@ -1,21 +1,21 @@ import { repeat } from '../../../../core/vmath'; -import { Enum, ValueType } from '../../../../core/value-types'; +import { Enum, ValueType, Color } from '../../../../core/value-types'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; const Mode = Enum({ Blend: 0, - Fixed: 1 + Fixed: 1, }); @ccclass('cc.ColorKey') export class ColorKey { @property - color = cc.Color.WHITE; + public color = cc.Color.WHITE; @property - time = 0; + public time = 0; } // CCClass.fastDefine('cc.ColorKey', ColorKey, { @@ -27,10 +27,10 @@ export class ColorKey { export class AlphaKey { @property - alpha = 1; + public alpha = 1; @property - time = 0; + public time = 0; } // CCClass.fastDefine('cc.AlphaKey', AlphaKey, { @@ -42,24 +42,26 @@ export class AlphaKey { export default class Gradient { @property - colorKeys = []; + public colorKeys = new Array(); @property - alphaKeys = [] + public alphaKeys = new Array(); @property - mode = Mode.Blend; + public mode = Mode.Blend; - constructor() { + private _color: Color; + + constructor () { this._color = cc.Color.WHITE; } - setKeys(colorKeys, alphaKeys) { + public setKeys (colorKeys, alphaKeys) { this.colorKeys = colorKeys; this.alphaKeys = alphaKeys; } - sortKeys() { + public sortKeys () { if (this.colorKeys.length > 1) { this.colorKeys.sort((a, b) => a.time - b.time); } @@ -68,17 +70,17 @@ export default class Gradient { } } - getRGB(time) { + private getRGB (time: number) { if (this.colorKeys.length > 1) { time = repeat(time, 1); for (let i = 1; i < this.colorKeys.length; ++i) { - let preTime = this.colorKeys[i - 1].time; - let curTime = this.colorKeys[i].time; + 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 === 'fixed') { return this.colorKeys[i].color; } - let factor = (time - preTime) / (curTime - preTime); + const factor = (time - preTime) / (curTime - preTime); this.colorKeys[i - 1].color.lerp(this.colorKeys[i].color, factor, this._color); return this._color; } @@ -96,17 +98,17 @@ export default class Gradient { } } - getAlpha(time) { + private getAlpha (time) { if (this.alphaKeys.length > 1) { time = repeat(time, 1); for (let i = 1; i < this.alphaKeys.length; ++i) { - let preTime = this.alphaKeys[i - 1].time; - let curTime = this.alphaKeys[i].time; + 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 === 'fixed') { return this.alphaKeys[i].alpha; } - let factor = (time - preTime) / (curTime - preTime); + const factor = (time - preTime) / (curTime - preTime); return (this.alphaKeys[i - 1].alpha * (1 - factor) + this.alphaKeys[i].alpha * factor); } } @@ -118,19 +120,19 @@ export default class Gradient { } } - evaluate(time) { + public evaluate (time) { this.getRGB(time); - this._color.a = this.getAlpha(time); + this._color.a = this.getAlpha(time)!; return this._color; } - randomColor() { - let c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; - let a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; - this._color.r = c.r; - this._color.g = c.g; - this._color.b = c.b; - this._color.a = a; + public randomColor () { + const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)]; + const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)]; + this._color.r = c.color.r; + this._color.g = c.color.g; + this._color.b = c.color.b; + this._color.a = a.alpha; return this._color; } } diff --git a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts similarity index 64% rename from cocos/3d/framework/particle/animator/limit-velocity-overtime.js rename to cocos/3d/framework/particle/animator/limit-velocity-overtime.ts index f7307cd5e5..5c7ad59f4a 100644 --- a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js +++ b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts @@ -3,73 +3,78 @@ import { CCClass } from '../../../../core/data'; import { Space } from '../particle-general-function'; import { property, ccclass } from '../../../../core/data/class-decorator'; import CurveRange from './curve-range'; +import Particle from '../particle'; +// tslint:disable: max-line-length const LIMIT_VELOCITY_RAND_OFFSET = 23541; @ccclass('cc.LimitVelocityOvertimeModule') export default class LimitVelocityOvertimeModule { - enable = false; + @property + public enable = false; @property({ - type: CurveRange + type: CurveRange, }) - limitX = new CurveRange(); + public limitX = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - limitY = new CurveRange(); + public limitY = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - limitZ = new CurveRange(); + public limitZ = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - limit = new CurveRange(); + public limit = new CurveRange(); @property - dampen = 0; + public dampen = 0; @property - separateAxes = false; + public separateAxes = false; - @property - space = Space.Local; + @property({ + type: Space, + }) + public space = Space.Local; // TODO:functions related to drag are temporarily not supported - drag = null; + public drag = null; - multiplyDragByParticleSize = false; + public multiplyDragByParticleSize = false; - multiplyDragByParticleVelocity = false; + public multiplyDragByParticleVelocity = false; - constructor() { + constructor () { } - animate(p) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let dampedVel = vec3.create(0, 0, 0); + public animate (p: Particle) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const dampedVel = vec3.create(0, 0, 0); if (this.separateAxes) { vec3.set(dampedVel, - dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen), - dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen), - dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen)); + dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen), + dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen), + dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen)); } else { vec3.normalize(dampedVel, p.ultimateVelocity); - vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen)); + vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen)); } vec3.copy(p.ultimateVelocity, dampedVel); } } -function dampenBeyondLimit(vel, limit, dampen) { - let sgn = Math.sign(vel); +function dampenBeyondLimit (vel: number, limit: number, dampen: number) { + const sgn = Math.sign(vel); let abs = Math.abs(vel); if (abs > limit) { abs = lerp(abs, limit, dampen); diff --git a/cocos/3d/framework/particle/animator/optimized-curve.js b/cocos/3d/framework/particle/animator/optimized-curve.js deleted file mode 100644 index c022c98dbe..0000000000 --- a/cocos/3d/framework/particle/animator/optimized-curve.js +++ /dev/null @@ -1,297 +0,0 @@ -import { OptimizedKey, evalOptCurve } from "../../../geom-utils/curve"; -import { repeat } from "../../../../core/vmath"; - -const CURVE_MODE_CONSTANT = 0; -const CURVE_MODE_RANDOM_CONSTANT = 1; -const CURVE_MODE_CURVE = 2; -const CURVE_MODE_RANDOM_CURVE = 3; - -const UNIFORM_CURVE_KEY_NUM = 8; - -//calculate the coefficience of the first order integral of the curve -function integrateKeyframe(coef) { - coef[0] = coef[0] / 4; - coef[1] = coef[1] / 3; - coef[2] = coef[2] / 2; - coef[3] = coef[3]; - return coef; -} - -//calculate the coefficience of the second order integral of the curve -function integrateKeyframeTwice(coef) { - coef[0] = coef[0] / 20; - coef[1] = coef[1] / 12; - coef[2] = coef[2] / 6; - coef[3] = coef[3] / 2; - return coef; -} - -export class OptimizedCurve { - constructor(constructUniform = false) { - this.optimizedKeys = new Array; //the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve. - this.integral = new Array; //the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored) - this.constructUniform = constructUniform; - } - - buildCurve(animationCurve, multiplier = 1) { - let keyNum = animationCurve.keyFrames.length - 1; - let i = 0; - if (this.optimizedKeys.length < keyNum) { - let keyToAdd = keyNum - this.optimizedKeys.length; - for (i = 0; i < keyToAdd; i++) { - let optKey = new OptimizedKey(); - this.optimizedKeys.push(optKey); - } - } else { - this.optimizedKeys.splice(keyNum); - } - if (animationCurve.keyFrames.length === 1) { - this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value * multiplier; - this.optimizedKeys[0].time = 0; - this.optimizedKeys[0].endTime = 1; - } else { - let keyOffset = 0; - if (animationCurve.keyFrames[0].time !== 0) { - this.optimizedKeys.splice(0, 0, new OptimizedKey()); - this.optimizedKeys[0].time = 0; - this.optimizedKeys[0].endTime = animationCurve.keyFrames[0].time; - this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value; - keyOffset = 1; - } - for (i = 0; i < keyNum; i++) { - animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum)); - this.optimizedKeys[i + keyOffset].index += keyOffset; - } - if (animationCurve.keyFrames[animationCurve.keyFrames.length - 1].time !== 1) { - this.optimizedKeys.push(new OptimizedKey()); - this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames[animationCurve.length - 1].time; - this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1; - this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames[animationCurve.length - 1].value; - } - } - for (i = 0; i < this.optimizedKeys.length; i++) { - this.optimizedKeys[i].coefficient[0] *= multiplier; - this.optimizedKeys[i].coefficient[1] *= multiplier; - this.optimizedKeys[i].coefficient[2] *= multiplier; - this.optimizedKeys[i].coefficient[3] *= multiplier; - } - if (this.constructUniform) { - this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4); - this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM); - this.updateKeyUniform(); - } - } - - evaluate(time) { - time = repeat(time, 1); - for (let i = 1; i < this.optimizedKeys.length; i++) { - if (time < this.optimizedKeys[i].time) { - return this.optimizedKeys[i - 1].evaluate(time); - } - } - return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time); - } - - //calculate first order integral coefficients of all keys - integrateOnce() { - let i = 0; - if (this.integral.length + 1 < this.optimizedKeys.length) { - for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { - this.integral.push(0); - } - } else { - this.integral.splice(this.optimizedKeys.length - 1); - } - for (i = 0; i < this.integral.length; i++) { - integrateKeyframe(this.optimizedKeys[i].coefficient); - let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; - let prevIntegral = i === 0 ? 0 : this.integral[i - 1]; - this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); - } - integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); - if (this.constructUniform) { - this.updateKeyUniform(); - this.updateIntegralUniform(); - } - } - - //get the integral of the curve using calculated coefficients - evaluateIntegral(t, ts = 1) { - t = repeat(t, 1); - for (let i = 1; i < this.optimizedKeys.length; i++) { - if (t < this.optimizedKeys[i].time) { - let prevInt = i === 1 ? 0 : this.integral[i - 2]; - let dt = t - this.optimizedKeys[i - 1].time; - return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); - } - } - let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; - return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); - } - - //calculate second order integral coefficients of all keys - integrateTwice() { - let i = 0; - if (this.integral.length + 1 < this.optimizedKeys.length) { - for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { - this.integral.push(0); - } - } else { - this.integral.splice(this.optimizedKeys.length - 1); - } - for (i = 0; i < this.integral.length; i++) { - integrateKeyframeTwice(this.optimizedKeys[i].coefficient); - let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; - let prevIntegral = i === 0 ? 0 : this.integral[i - 1]; - this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); - } - integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); - if (this.constructUniform) { - this.updateKeyUniform(); - this.updateIntegralUniform(); - } - } - - //get the second order integral of the curve using calculated coefficients - evaluateIntegralTwice(t, ts = 1) { - t = repeat(t, 1); - for (let i = 1; i < this.optimizedKeys.length; i++) { - if (t < this.optimizedKeys[i].time) { - let prevInt = i === 1 ? 0 : this.integral[i - 2]; - let dt = t - this.optimizedKeys[i - 1].time; - return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); - } - } - let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; - return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); - } - - updateKeyUniform() { - for (let i = 0; i < this.optimizedKeys.length; i++) { - this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0]; - this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1]; - this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2]; - this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3]; - this.timeUniform[i] = this.optimizedKeys[i].endTime; - } - } - - updateIntegralUniform() { - this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1); - for (let i = 0; i < this.integral.length; i++) { - this.integralUniform[i] = this.integral[i]; - } - } -} - -export class CurveUniform { - constructCurve(cr) { - this.mode = cr.mode; - switch (cr.mode) { - case 'constant': - this.minConstant = cr.constant; - break; - case 'twoConstants': - this.minConstant = cr.constantMin; - this.maxConstant = cr.constantMax; - break; - case 'curve': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curve, cr.multiplier); - break; - case 'twoCurves': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curveMin, cr.multiplier); - this.maxCurve = new OptimizedCurve(true); - this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); - break; - } - } - - constructCurveIntegral(cr) { - this.mode = cr.mode; - switch (cr.mode) { - case 'constant': - this.minConstant = cr.constant; - break; - case 'twoConstants': - this.minConstant = cr.constantMin; - this.maxConstant = cr.constantMax; - break; - case 'curve': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curve, cr.multiplier); - this.minCurve.integrateOnce(); - break; - case 'twoCurves': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curveMin, cr.multiplier); - this.minCurve.integrateOnce(); - this.maxCurve = new OptimizedCurve(true); - this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); - this.maxCurve.integrateOnce(); - break; - } - } - - constructCurveIntegralTwice(cr) { - this.mode = cr.mode; - switch (cr.mode) { - case 'constant': - this.minConstant = cr.constant; - break; - case 'twoConstants': - this.minConstant = cr.constantMin; - this.maxConstant = cr.constantMax; - break; - case 'curve': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curve, cr.multiplier); - this.minCurve.integrateTwice(); - break; - case 'twoCurves': - this.minCurve = new OptimizedCurve(true); - this.minCurve.buildCurve(cr.curveMin, cr.multiplier); - this.minCurve.integrateTwice(); - this.maxCurve = new OptimizedCurve(true); - this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); - this.maxCurve.integrateTwice(); - break; - } - } - - uploadUniform(device, name) { - switch (this.mode) { - case 'constant': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT); - device.setUniform('u_' + name + '_minConstant', this.minConstant); - break; - case 'twoConstants': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT); - device.setUniform('u_' + name + '_minConstant', this.minConstant); - device.setUniform('u_' + name + '_maxConstant', this.maxConstant); - break; - case 'curve': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE); - device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); - device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); - if (this.minCurve.integralUniform !== undefined) { - device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); - } - break; - case 'twoCurves': - device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE); - device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); - device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); - if (this.minCurve.integralUniform !== undefined) { - device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); - } - device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform); - device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform); - if (this.minCurve.integralUniform !== undefined) { - device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform); - } - break; - } - } -} diff --git a/cocos/3d/framework/particle/animator/optimized-curve.ts b/cocos/3d/framework/particle/animator/optimized-curve.ts new file mode 100644 index 0000000000..ded36f8cd3 --- /dev/null +++ b/cocos/3d/framework/particle/animator/optimized-curve.ts @@ -0,0 +1,313 @@ +import { OptimizedKey, evalOptCurve, AnimationCurve } from "../../../geom-utils/curve"; +import { repeat } from "../../../../core/vmath"; +import CurveRange from "./curve-range"; + +// tslint:disable: max-line-length + +const CURVE_MODE_CONSTANT = 0; +const CURVE_MODE_RANDOM_CONSTANT = 1; +const CURVE_MODE_CURVE = 2; +const CURVE_MODE_RANDOM_CURVE = 3; + +const UNIFORM_CURVE_KEY_NUM = 8; + +// calculate the coefficience of the first order integral of the curve +function integrateKeyframe (coef: Float32Array) { + coef[0] = coef[0] / 4; + coef[1] = coef[1] / 3; + coef[2] = coef[2] / 2; + coef[3] = coef[3]; + return coef; +} + +// calculate the coefficience of the second order integral of the curve +function integrateKeyframeTwice (coef: Float32Array) { + coef[0] = coef[0] / 20; + coef[1] = coef[1] / 12; + coef[2] = coef[2] / 6; + coef[3] = coef[3] / 2; + return coef; +} + +export class OptimizedCurve { + private optimizedKeys: OptimizedKey[]; + private integral: number[]; + private constructUniform: boolean; + private coefUniform: Float32Array; + private timeUniform: Float32Array; + private integralUniform: Float32Array; + + constructor (constructUniform = false) { + this.optimizedKeys = new Array(); // the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve. + this.integral = new Array(); // the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored) + this.constructUniform = constructUniform; + } + + public buildCurve (animationCurve: AnimationCurve, multiplier: number = 1) { + const keyNum = animationCurve.keyFrames!.length - 1; + let i = 0; + if (this.optimizedKeys.length < keyNum) { + const keyToAdd = keyNum - this.optimizedKeys.length; + for (i = 0; i < keyToAdd; i++) { + const optKey = new OptimizedKey(); + this.optimizedKeys.push(optKey); + } + } else { + this.optimizedKeys.splice(keyNum); + } + if (animationCurve.keyFrames!.length === 1) { + this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value * multiplier; + this.optimizedKeys[0].time = 0; + this.optimizedKeys[0].endTime = 1; + } else { + let keyOffset = 0; + if (animationCurve.keyFrames![0].time !== 0) { + this.optimizedKeys.splice(0, 0, new OptimizedKey()); + this.optimizedKeys[0].time = 0; + this.optimizedKeys[0].endTime = animationCurve.keyFrames![0].time; + this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value; + keyOffset = 1; + } + for (i = 0; i < keyNum; i++) { + animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum)); + this.optimizedKeys[i + keyOffset].index += keyOffset; + } + if (animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time !== 1) { + this.optimizedKeys.push(new OptimizedKey()); + this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time; + this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1; + this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].value; + } + } + for (i = 0; i < this.optimizedKeys.length; i++) { + this.optimizedKeys[i].coefficient[0] *= multiplier; + this.optimizedKeys[i].coefficient[1] *= multiplier; + this.optimizedKeys[i].coefficient[2] *= multiplier; + this.optimizedKeys[i].coefficient[3] *= multiplier; + } + if (this.constructUniform) { + this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4); + this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM); + this.updateKeyUniform(); + } + } + + public evaluate (time: number) { + time = repeat(time, 1); + for (let i = 1; i < this.optimizedKeys.length; i++) { + if (time < this.optimizedKeys[i].time) { + return this.optimizedKeys[i - 1].evaluate(time); + } + } + return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time); + } + + // calculate first order integral coefficients of all keys + public integrateOnce () { + let i = 0; + if (this.integral.length + 1 < this.optimizedKeys.length) { + for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { + this.integral.push(0); + } + } else { + this.integral.splice(this.optimizedKeys.length - 1); + } + for (i = 0; i < this.integral.length; i++) { + integrateKeyframe(this.optimizedKeys[i].coefficient); + const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; + const prevIntegral = i === 0 ? 0 : this.integral[i - 1]; + this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); + } + integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); + if (this.constructUniform) { + this.updateKeyUniform(); + this.updateIntegralUniform(); + } + } + + // get the integral of the curve using calculated coefficients + public evaluateIntegral (t: number, ts: number = 1) { + t = repeat(t, 1); + for (let i = 1; i < this.optimizedKeys.length; i++) { + if (t < this.optimizedKeys[i].time) { + const prevInt = i === 1 ? 0 : this.integral[i - 2]; + const dt = t - this.optimizedKeys[i - 1].time; + return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); + } + } + const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; + return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); + } + + // calculate second order integral coefficients of all keys + public integrateTwice () { + let i = 0; + if (this.integral.length + 1 < this.optimizedKeys.length) { + for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) { + this.integral.push(0); + } + } else { + this.integral.splice(this.optimizedKeys.length - 1); + } + for (i = 0; i < this.integral.length; i++) { + integrateKeyframeTwice(this.optimizedKeys[i].coefficient); + const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time; + const prevIntegral = i === 0 ? 0 : this.integral[i - 1]; + this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient)); + } + integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient); + if (this.constructUniform) { + this.updateKeyUniform(); + this.updateIntegralUniform(); + } + } + + // get the second order integral of the curve using calculated coefficients + public evaluateIntegralTwice (t: number, ts: number = 1) { + t = repeat(t, 1); + for (let i = 1; i < this.optimizedKeys.length; i++) { + if (t < this.optimizedKeys[i].time) { + const prevInt = i === 1 ? 0 : this.integral[i - 2]; + const dt = t - this.optimizedKeys[i - 1].time; + return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient))); + } + } + const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time; + return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient))); + } + + public updateKeyUniform () { + for (let i = 0; i < this.optimizedKeys.length; i++) { + this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0]; + this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1]; + this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2]; + this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3]; + this.timeUniform[i] = this.optimizedKeys[i].endTime; + } + } + + public updateIntegralUniform () { + this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1); + for (let i = 0; i < this.integral.length; i++) { + this.integralUniform[i] = this.integral[i]; + } + } +} + +export class CurveUniform { + private mode: number; + private minConstant: number; + private maxConstant: number; + private minCurve: OptimizedCurve; + private maxCurve: OptimizedCurve; + + public constructCurve (cr: CurveRange) { + this.mode = cr.mode; + switch (cr.mode) { + case 'constant': + this.minConstant = cr.constant; + break; + case 'twoConstants': + this.minConstant = cr.constantMin; + this.maxConstant = cr.constantMax; + break; + case 'curve': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curve, cr.multiplier); + break; + case 'twoCurves': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curveMin, cr.multiplier); + this.maxCurve = new OptimizedCurve(true); + this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); + break; + } + } + + public constructCurveIntegral (cr: CurveRange) { + this.mode = cr.mode; + switch (cr.mode) { + case 'constant': + this.minConstant = cr.constant; + break; + case 'twoConstants': + this.minConstant = cr.constantMin; + this.maxConstant = cr.constantMax; + break; + case 'curve': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curve, cr.multiplier); + this.minCurve.integrateOnce(); + break; + case 'twoCurves': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curveMin, cr.multiplier); + this.minCurve.integrateOnce(); + this.maxCurve = new OptimizedCurve(true); + this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); + this.maxCurve.integrateOnce(); + break; + } + } + + public constructCurveIntegralTwice (cr: CurveRange) { + this.mode = cr.mode; + switch (cr.mode) { + case 'constant': + this.minConstant = cr.constant; + break; + case 'twoConstants': + this.minConstant = cr.constantMin; + this.maxConstant = cr.constantMax; + break; + case 'curve': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curve, cr.multiplier); + this.minCurve.integrateTwice(); + break; + case 'twoCurves': + this.minCurve = new OptimizedCurve(true); + this.minCurve.buildCurve(cr.curveMin, cr.multiplier); + this.minCurve.integrateTwice(); + this.maxCurve = new OptimizedCurve(true); + this.maxCurve.buildCurve(cr.curveMax, cr.multiplier); + this.maxCurve.integrateTwice(); + break; + } + } + + public uploadUniform (device: any, name: number) { + switch (this.mode) { + case 'constant': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT); + device.setUniform('u_' + name + '_minConstant', this.minConstant); + break; + case 'twoConstants': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT); + device.setUniform('u_' + name + '_minConstant', this.minConstant); + device.setUniform('u_' + name + '_maxConstant', this.maxConstant); + break; + case 'curve': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE); + device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); + device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); + if (this.minCurve.integralUniform !== undefined) { + device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); + } + break; + case 'twoCurves': + device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE); + device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform); + device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform); + if (this.minCurve.integralUniform !== undefined) { + device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform); + } + device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform); + device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform); + if (this.minCurve.integralUniform !== undefined) { + device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform); + } + break; + } + } +} diff --git a/cocos/3d/framework/particle/animator/rotation-overtime.js b/cocos/3d/framework/particle/animator/rotation-overtime.ts similarity index 65% rename from cocos/3d/framework/particle/animator/rotation-overtime.js rename to cocos/3d/framework/particle/animator/rotation-overtime.ts index d015e9ceb5..29d1de795a 100644 --- a/cocos/3d/framework/particle/animator/rotation-overtime.js +++ b/cocos/3d/framework/particle/animator/rotation-overtime.ts @@ -2,23 +2,26 @@ import { pseudoRandom } from "../../../../core/vmath"; import { CCClass } from "../../../../core/data"; import CurveRange from "./curve-range"; import { property, ccclass } from "../../../../core/data/class-decorator"; +import Particle from "../particle"; +// tslint:disable: max-line-length const ROTATION_OVERTIME_RAND_OFFSET = 125292; @ccclass('cc.RotationOvertimeModule') export default class RotationOvertimeModule { @property - enable = false; + public enable = false; @property - _separateAxes = false; + private _separateAxes = false; - get separateAxes() { + @property + get separateAxes () { return this._separateAxes; } - set separateAxes(val) { + set separateAxes (val) { if (!val) { this._separateAxes = val; } @@ -28,28 +31,28 @@ export default class RotationOvertimeModule { } @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); - constructor() { + constructor () { } - animate(p, dt) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + public animate (p: Particle, dt: number) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; if (!this._separateAxes) { - p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET)) * dt; + p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET))! * dt; } else { // TODO: separateAxes is temporarily not supported! diff --git a/cocos/3d/framework/particle/animator/size-overtime.js b/cocos/3d/framework/particle/animator/size-overtime.ts similarity index 69% rename from cocos/3d/framework/particle/animator/size-overtime.js rename to cocos/3d/framework/particle/animator/size-overtime.ts index 63f77d09aa..d885bb5521 100644 --- a/cocos/3d/framework/particle/animator/size-overtime.js +++ b/cocos/3d/framework/particle/animator/size-overtime.ts @@ -2,41 +2,43 @@ import { vec3, pseudoRandom } from '../../../../core/vmath'; import CurveRange from './curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import Particle from '../particle'; +// tslint:disable: max-line-length const SIZE_OVERTIME_RAND_OFFSET = 39825; @ccclass('cc.SizeOvertimeModule') export default class SizeOvertimeModule { @property - enable = false; + public enable = false; @property - separateAxes = false; + public separateAxes = false; @property({ - type: CurveRange + type: CurveRange, }) - size = new CurveRange(); + public size = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); - animate(particle) { + public animate (particle: Particle) { if (!this.separateAxes) { - vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET))); + vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET))!); } } } diff --git a/cocos/3d/framework/particle/animator/texture-animation.js b/cocos/3d/framework/particle/animator/texture-animation.ts similarity index 51% rename from cocos/3d/framework/particle/animator/texture-animation.js rename to cocos/3d/framework/particle/animator/texture-animation.ts index 6c04f88d3b..071a112510 100644 --- a/cocos/3d/framework/particle/animator/texture-animation.js +++ b/cocos/3d/framework/particle/animator/texture-animation.ts @@ -3,42 +3,45 @@ import { Enum } from "../../../../core/value-types"; import CurveRange from "./curve-range"; import { CCClass } from "../../../../core/data"; import { property, ccclass } from "../../../../core/data/class-decorator"; +import ParticleSystemComponent from "../particle-system-component"; +import Particle from "../particle"; +// tslint:disable: max-line-length const TEXTURE_ANIMATION_RAND_OFFSET = 90794; const Mode = Enum({ Grid: 0, - Sprites: 1 + Sprites: 1, }); const Animation = Enum({ WholeSheet: 0, - SingleRow: 1 + SingleRow: 1, }); @ccclass('cc.TextureAnimationModule') export default class TextureAnimationModule { @property - _enable = false; + private _enable = false; - get enable() { + get enable () { return this._enable; } - set enable(val) { + set enable (val) { this._enable = val; - this.ps.renderer._updateMaterialParams(); + this.ps!.renderer!._updateMaterialParams(); } @property - _mode = Mode.Grid + private _mode = Mode.Grid; - get mode() { + get mode () { return this._mode; } - set mode(val) { + set mode (val) { if (val === Mode.Sprites) { console.error("particle texture animation's sprites is not supported!"); return; @@ -46,89 +49,91 @@ export default class TextureAnimationModule { } @property - numTilesX = 0; + public numTilesX = 0; @property - numTilesY = 0; + public numTilesY = 0; @property - animation = Animation.WholeSheet; + public animation = Animation.WholeSheet; @property({ - type: CurveRange + type: CurveRange, }) - frameOverTime = new CurveRange(); + public frameOverTime = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startFrame = new CurveRange(); + public startFrame = new CurveRange(); @property - cycleCount = 0; + public cycleCount = 0; @property - _flipU = 0; + private _flipU = 0; - get flipU() { + get flipU () { return this._flipU; } - set flipU(val) { + set flipU (val) { console.error("particle texture animation's flipU is not supported!"); } @property - _flipV = 0; + private _flipV = 0; - get flipV() { + get flipV () { return this._flipV; } - set flipV(val) { + set flipV (val) { console.error("particle texture animation's flipV is not supported!"); } @property - _uvChannelMask = -1 + private _uvChannelMask = -1; - get uvChannelMask() { + get uvChannelMask () { return this._uvChannelMask; } - set uvChannelMask(val) { + set uvChannelMask (val) { console.error("particle texture animation's uvChannelMask is not supported!"); } @property - randomRow = false; + public randomRow = false; @property - rowIndex = 0; + public rowIndex = 0; - onInit(ps) { + private ps: ParticleSystemComponent | null = null; + + public onInit (ps: ParticleSystemComponent) { this.ps = ps; } - animate(p) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) / (this.numTilesX * this.numTilesY); - if (this.animation == Animation.WholeSheet) { - p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1); + public animate (p: Particle) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! / (this.numTilesX * this.numTilesY); + if (this.animation === Animation.WholeSheet) { + p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1); } - else if (this.animation == Animation.SingleRow) { - let rowLength = 1 / this.numTilesY; - if (this._randomRow) { - let f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1); - let startRow = Math.floor(Math.random() * this.numTilesY); - let from = startRow * rowLength; - let to = from + rowLength; + else if (this.animation === Animation.SingleRow) { + const rowLength = 1 / this.numTilesY; + if (this.randomRow) { + const f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1); + const startRow = Math.floor(Math.random() * this.numTilesY); + const from = startRow * rowLength; + const to = from + rowLength; p.frameIndex = lerp(from, to, f); } else { - let from = this.rowIndex * rowLength; - let to = from + rowLength; - p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1)); + const from = this.rowIndex * rowLength; + const to = from + rowLength; + p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1)); } } } diff --git a/cocos/3d/framework/particle/animator/velocity-overtime.js b/cocos/3d/framework/particle/animator/velocity-overtime.ts similarity index 51% rename from cocos/3d/framework/particle/animator/velocity-overtime.js rename to cocos/3d/framework/particle/animator/velocity-overtime.ts index 465aaecb84..90acc40c17 100644 --- a/cocos/3d/framework/particle/animator/velocity-overtime.js +++ b/cocos/3d/framework/particle/animator/velocity-overtime.ts @@ -1,57 +1,66 @@ -import { vec3, quat, pseudoRandom } from '../../../../core/vmath'; +import { vec3, quat, pseudoRandom, mat4 } from '../../../../core/vmath'; import { calculateTransform, Space } from '../particle-general-function'; import CurveRange from './curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import Particle from '../particle'; +// tslint:disable: max-line-length const VELOCITY_OVERTIME_RAND_OFFSET = 197866; @ccclass('cc.VelocityOvertimeModule') export default class VelocityOvertimeModule { @property - enable = false; + public enable = false; @property({ - type: CurveRange + type: CurveRange, }) - x = new CurveRange(); + public x = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - y = new CurveRange(); + public y = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - z = new CurveRange(); + public z = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - speedModifier = new CurveRange(); + public speedModifier = new CurveRange(); - @property - space = Space.Local; + @property({ + type: Space, + }) + public space = Space.Local; - constructor() { + private rotation: quat; + private needTransform: boolean; + + constructor () { this.rotation = quat.create(); + this.speedModifier.constant = 1; + this.needTransform = false; } - update(space, worldTransform) { + public update (space: number, worldTransform: mat4) { this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation); } - animate(p) { - let normalizedTime = 1 - p.remainingLifetime / p.startLifetime; - let vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))); + public animate (p: Particle) { + const normalizedTime = 1 - p.remainingLifetime / p.startLifetime; + const vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))); if (this.needTransform) { vec3.transformQuat(vel, vel, this.rotation); } vec3.add(p.animatedVelocity, p.animatedVelocity, vel); vec3.add(p.ultimateVelocity, p.velocity, p.animatedVelocity); - vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))); + vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))!); } } diff --git a/cocos/3d/framework/particle/emitter/shape-module.js b/cocos/3d/framework/particle/emitter/shape-module.ts similarity index 74% rename from cocos/3d/framework/particle/emitter/shape-module.js rename to cocos/3d/framework/particle/emitter/shape-module.ts index a5bdd4af3f..031824820d 100644 --- a/cocos/3d/framework/particle/emitter/shape-module.js +++ b/cocos/3d/framework/particle/emitter/shape-module.ts @@ -1,12 +1,14 @@ import { randomUnitVector, particleEmitZAxis, randomSortArray, randomSign, randomPointBetweenSphere, randomPointInCube, randomPointBetweenCircleAtFixedAngle, fixedAngleUnitVector2 } from '../particle-general-function'; -import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong } from '../../../../core/vmath'; +import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong, toRadian, toDegree } from '../../../../core/vmath'; import { Enum, Vec3 } from '../../../../core/value-types'; import CurveRange from '../animator/curve-range'; import { CCClass } from '../../../../core/data'; import { property, ccclass } from '../../../../core/data/class-decorator'; +import ParticleSystemComponent from '../particle-system-component'; -let _intermediVec = vec3.create(0, 0, 0); -let _intermediArr = new Array(); +// tslint:disable: max-line-length +const _intermediVec = vec3.create(0, 0, 0); +const _intermediArr = new Array(); const _unitBoxExtent = vec3.create(0.5, 0.5, 0.5); const ShapeType = Enum({ @@ -14,130 +16,162 @@ const ShapeType = Enum({ Circle: 1, Cone: 2, Sphere: 3, - Hemisphere: 4 + Hemisphere: 4, }); const EmitLocation = Enum({ Base: 0, Edge: 1, Shell: 2, - Volume: 3 + Volume: 3, }); const ArcMode = Enum({ Random: 0, Loop: 1, - PingPong: 2 + PingPong: 2, }); @ccclass('cc.ShapeModule') export default class ShapeModule { @property - enable = false; + public enable = false; @property({ - type: ShapeType + type: ShapeType, }) - shapeType = ShapeType.Box; + public shapeType = ShapeType.Box; @property({ - type: EmitLocation + type: EmitLocation, }) - emitFrom = EmitLocation.Volume; + public emitFrom = EmitLocation.Volume; @property - _position = new Vec3(0, 0, 0); + private _position = new Vec3(0, 0, 0); - get position() { + @property + get position () { return this._position; } - set position(val) { + set position (val) { this._position = val; this.constructMat(); } @property - _rotation = new Vec3(0, 0, 0); + private _rotation = new Vec3(0, 0, 0); - get rotation() { + @property + get rotation () { return this._rotation; } - set rotation(val) { + set rotation (val) { this._rotation = val; this.constructMat(); } @property - _scale = new Vec3(0, 0, 0); + private _scale = new Vec3(1, 1, 1); - get scale() { + @property + get scale () { return this._scale; } - set scale(val) { + set scale (val) { this._scale = val; this.constructMat(); } @property - alignToDirection = false; + public alignToDirection = false; @property - randomDirectionAmount = 0; + public randomDirectionAmount = 0; @property - sphericalDirectionAmount = 0; + public sphericalDirectionAmount = 0; @property - randomPositionAmount = 0; + public randomPositionAmount = 0; @property - radius = 0; + public radius = 1; @property - radiusThickness = 1; + public radiusThickness = 1; @property - arc = 0; + private _arc = toRadian(360); @property - arcMode = ArcMode.Random; - - @property - arcSpread = 0; - - @property({ - type: CurveRange - }) - arcSpeed = new CurveRange(); - - @property - angle = 0; - - @property - length = 0; - - @property - boxThickness = new Vec3(0, 0, 0); - - constructor() { - this.mat = mat4.create(); - this.quat = quat.create(); + get arc () { + return toDegree(this._arc); } - onInit(ps) { + set arc (val) { + this._arc = toRadian(val); + } + + @property({ + type: ArcMode, + }) + public arcMode = ArcMode.Random; + + @property + public arcSpread = 0; + + @property({ + type: CurveRange, + }) + public arcSpeed = new CurveRange(); + + @property + private _angle = toRadian(25); + + @property + get angle () { + return toDegree(this._angle); + } + + set angle (val) { + this._angle = toRadian(val); + } + + @property + public length = 0; + + @property + public boxThickness = new Vec3(0, 0, 0); + + private mat: mat4; + private quat: quat; + private particleSystem: ParticleSystemComponent | null; + private lastTime: number; + private totalAngle: number; + + constructor () { + this.mat = mat4.create(); + this.quat = quat.create(); + this.particleSystem = null; + this.lastTime = 0; + this.totalAngle = 0; + } + + public onInit (ps: ParticleSystemComponent) { this.constructMat(); this.particleSystem = ps; this.lastTime = ps._time; this.totalAngle = 0; } - constructMat() { + private constructMat () { quat.fromEuler(this.quat, this._rotation.x, this._rotation.y, this._rotation.z); mat4.fromRTS(this.mat, this.quat, this._position, this._scale); } - emit(p) { + public emit (p) { switch (this.shapeType) { case ShapeType.Box: boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity); @@ -146,7 +180,7 @@ export default class ShapeModule { circleEmit(this.radius, this.radiusThickness, this.generateArcAngle(), p.position, p.velocity); break; case ShapeType.Cone: - coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this.angle, this.length, p.position, p.velocity); + coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this._angle, this.length, p.position, p.velocity); break; case ShapeType.Sphere: sphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity); @@ -165,31 +199,31 @@ export default class ShapeModule { vec3.transformQuat(p.velocity, p.velocity, this.quat); vec3.transformMat4(p.position, p.position, this.mat); if (this.sphericalDirectionAmount > 0) { - let sphericalVel = vec3.normalize(_intermediVec, p.position); + const sphericalVel = vec3.normalize(_intermediVec, p.position); vec3.lerp(p.velocity, p.velocity, sphericalVel, this.sphericalDirectionAmount); } - this.lastTime = this.particleSystem._time; + this.lastTime = this.particleSystem!._time; } - generateArcAngle() { + private generateArcAngle () { if (this.arcMode === ArcMode.Random) { - return randomRange(0, this.arc); + return randomRange(0, this._arc); } - let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem._time) * (this.particleSystem._time - this.lastTime); + let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem!._time, 1)! * (this.particleSystem!._time - this.lastTime); this.totalAngle = angle; if (this.arcSpread !== 0) { - angle = Math.floor(angle / (this.arc * this.arcSpread)) * this.arc * this.arcSpread; + angle = Math.floor(angle / (this._arc * this.arcSpread)) * this._arc * this.arcSpread; } switch (this.arcMode) { case ArcMode.Loop: - return repeat(angle, this.arc); + return repeat(angle, this._arc); case ArcMode.PingPong: - return pingPong(angle, this.arc); + return pingPong(angle, this._arc); } } } -function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) { +function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); @@ -206,7 +240,7 @@ function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) { } } -function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) { +function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); @@ -229,7 +263,7 @@ function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) { } } -function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) { +function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) { switch (emitFrom) { case EmitLocation.Base: randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); @@ -259,7 +293,7 @@ function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, } } -function boxEmit(emitFrom, boxThickness, pos, dir) { +function boxEmit (emitFrom, boxThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointInCube(pos, _unitBoxExtent); @@ -289,12 +323,12 @@ function boxEmit(emitFrom, boxThickness, pos, dir) { vec3.copy(dir, particleEmitZAxis); } -function circleEmit(radius, radiusThickness, theta, pos, dir) { +function circleEmit (radius, radiusThickness, theta, pos, dir) { randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta); vec3.normalize(dir, pos); } -function applyBoxThickness(pos, thickness) { +function applyBoxThickness (pos, thickness) { if (thickness.x > 0) { pos[0] += 0.5 * randomRange(-thickness.x, thickness.x); pos[0] = clamp(pos[0], -0.5, 0.5); diff --git a/cocos/3d/framework/particle/particle-general-function.js b/cocos/3d/framework/particle/particle-general-function.ts similarity index 63% rename from cocos/3d/framework/particle/particle-general-function.js rename to cocos/3d/framework/particle/particle-general-function.ts index 06076406e8..adc6ae69f9 100644 --- a/cocos/3d/framework/particle/particle-general-function.js +++ b/cocos/3d/framework/particle/particle-general-function.ts @@ -7,10 +7,10 @@ export const particleEmitZAxis = vec3.create(0, 0, -1); export const Space = Enum({ World: 0, Local: 1, - Custom: 2 + Custom: 2, }); -export function calculateTransform(systemSpace, moduleSpace, worldTransform, outQuat) { +export function calculateTransform (systemSpace, moduleSpace, worldTransform, outQuat) { if (moduleSpace !== systemSpace) { if (systemSpace === 'world') { mat4.getRotation(outQuat, worldTransform); @@ -27,67 +27,70 @@ export function calculateTransform(systemSpace, moduleSpace, worldTransform, out } } -export function fixedAngleUnitVector2(out, theta) { +export function fixedAngleUnitVector2 (out, theta) { vec2.set(out, Math.cos(theta), Math.sin(theta)); } -export function randomUnitVector2(out) { - let a = randomRange(0, 2 * Math.PI); - let x = Math.cos(a); - let y = Math.sin(a); +export function randomUnitVector2 (out) { + const a = randomRange(0, 2 * Math.PI); + const x = Math.cos(a); + const y = Math.sin(a); vec2.set(out, x, y); } -export function randomUnitVector(out) { - let z = randomRange(-1, 1); - let a = randomRange(0, 2 * Math.PI); - let r = Math.sqrt(1 - z * z); - let x = r * Math.cos(a); - let y = r * Math.sin(a); +export function randomUnitVector (out) { + const z = randomRange(-1, 1); + const a = randomRange(0, 2 * Math.PI); + const r = Math.sqrt(1 - z * z); + const x = r * Math.cos(a); + const y = r * Math.sin(a); vec3.set(out, x, y, z); } -export function randomPointInUnitSphere(out) { +export function randomPointInUnitSphere (out) { randomUnitVector(out); vec3.scale(out, out, random()); } -export function randomPointBetweenSphere(out, minRadius, maxRadius) { +export function randomPointBetweenSphere (out, minRadius, maxRadius) { randomUnitVector(out); vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointInUnitCircle(out) { +export function randomPointInUnitCircle (out) { randomUnitVector2(out); + out.z = 0; vec3.scale(out, out, random()); } -export function randomPointBetweenCircle(out, minRadius, maxRadius) { +export function randomPointBetweenCircle (out, minRadius, maxRadius) { randomUnitVector2(out); + out.z = 0; vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointBetweenCircleAtFixedAngle(out, minRadius, maxRadius, theta) { +export function randomPointBetweenCircleAtFixedAngle (out, minRadius, maxRadius, theta) { fixedAngleUnitVector2(out, theta); + out.z = 0; vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random()); } -export function randomPointInCube(out, extents) { +export function randomPointInCube (out, extents) { vec3.set(out, randomRange(-extents.x, extents.x), randomRange(-extents.y, extents.y), randomRange(-extents.z, extents.z)); } -export function randomPointBetweenCube(out, minBox, maxBox) { +export function randomPointBetweenCube (out, minBox, maxBox) { const subscript = ['x', 'y', 'z']; - let edge = randomRangeInt(0, 3); + const edge = randomRangeInt(0, 3); for (let i = 0; i < 3; i++) { if (i === edge) { out[subscript[i]] = randomRange(-maxBox[subscript[i]], maxBox[subscript[i]]); continue; } - let x = random() * 2 - 1; + const x = random() * 2 - 1; if (x < 0) { out[subscript[i]] = -minBox[subscript[i]] + x * (maxBox[subscript[i]] - minBox[subscript[i]]); } @@ -98,16 +101,16 @@ export function randomPointBetweenCube(out, minBox, maxBox) { } // Fisher–Yates shuffle -export function randomSortArray(arr) { +export function randomSortArray (arr) { for (let i = 0; i < arr.length; i++) { - let transpose = i + randomRangeInt(0, arr.length - i); - let val = arr[transpose]; + const transpose = i + randomRangeInt(0, arr.length - i); + const val = arr[transpose]; arr[transpose] = arr[i]; arr[i] = val; } } -export function randomSign() { +export function randomSign () { let sgn = randomRange(-1, 1); sgn === 0 ? sgn++ : sgn; return sign(sgn); diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.ts similarity index 58% rename from cocos/3d/framework/particle/particle-system-component.js rename to cocos/3d/framework/particle/particle-system-component.ts index 936c8494b5..b4092697d7 100644 --- a/cocos/3d/framework/particle/particle-system-component.js +++ b/cocos/3d/framework/particle/particle-system-component.ts @@ -18,7 +18,7 @@ import { particleEmitZAxis, Space } from './particle-general-function'; import { INT_MAX } from '../../../core/vmath/bits'; import { ccclass, executionOrder, executeInEditMode, property, requireComponent, menu } from '../../../core/data/class-decorator'; -let _world_mat = mat4.create(); +const _world_mat = mat4.create(); @ccclass('cc.ParticleSystemComponent') @menu('Components/ParticleSystemComponent') @@ -28,155 +28,165 @@ let _world_mat = mat4.create(); export default class ParticleSystemComponent extends Component { @property - capacity = 2000; + public capacity = 2000; @property({ - type:GradientRange + type: GradientRange, }) - startColor = new GradientRange(); + public startColor = new GradientRange(); @property({ - type: CurveRange + type: CurveRange, }) - startSize = new CurveRange(); + public startSize = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startSpeed = new CurveRange(); + public startSpeed = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startRotation = new CurveRange(); + public startRotation = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startDelay = new CurveRange(); + public startDelay = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - startLifetime = new CurveRange(); + public startLifetime = new CurveRange(); @property - duration = 5.0; + public duration = 5.0; @property - loop = true; + public loop = true; @property - _prewarm = false; + private _prewarm = false; @property - get prewarm() { + get prewarm () { return this._prewarm; } - set prewarm(val) { - if (val === true && this._loop === false) { + set prewarm (val) { + if (val === true && this.loop === false) { // console.warn('prewarm only works if loop is also enabled.'); } this._prewarm = val; } @property - _simulationSpace = Space.Local; + private _simulationSpace = Space.Local; @property({ - type: Space + type: Space, }) - get simulationSpace() { + get simulationSpace () { return this._simulationSpace; } - set simulationSpace(val) { - if (val === Space.World) { - this._renderer._material.define('USE_WORLD_SPACE', true); - } else { - this._renderer._material.define('USE_WORLD_SPACE', false); + set simulationSpace (val) { + if (val !== this._simulationSpace) { + this._simulationSpace = val; + this.renderer!._updateMaterialParams(); } - this._simulationSpace = val; } @property - simulationSpeed = 1.0; + public simulationSpeed = 1.0; @property - playOnAwake = true; + public playOnAwake = true; @property({ - type: CurveRange + type: CurveRange, }) - gravityModifier = new CurveRange(); + public gravityModifier = new CurveRange(); // emission module @property({ - type: CurveRange + type: CurveRange, }) - rateOverTime = new CurveRange(); + public rateOverTime = new CurveRange(); @property({ - type: CurveRange + type: CurveRange, }) - rateOverDistance = new CurveRange(); + public rateOverDistance = new CurveRange(); @property({ - type: [Burst] + type: [Burst], }) - bursts = new Array(); + public bursts = new Array(); // color over lifetime module @property({ - type: ColorOverLifetimeModule + type: ColorOverLifetimeModule, }) - colorOverLifetimeModule = new ColorOverLifetimeModule(); + public colorOverLifetimeModule = new ColorOverLifetimeModule(); // shpae module @property({ - type: ShapeModule + type: ShapeModule, }) - shapeModule = new ShapeModule(); - - // particle system renderer - @property({ - type: ParticleSystemRenderer - }) - renderer = null; + public shapeModule = new ShapeModule(); // size over lifetime module @property({ - type: SizeOvertimeModule + type: SizeOvertimeModule, }) - sizeOvertimeModule = new SizeOvertimeModule(); + public sizeOvertimeModule = new SizeOvertimeModule(); @property({ - type: VelocityOvertimeModule + type: VelocityOvertimeModule, }) - velocityOvertimeModule = new VelocityOvertimeModule(); + public velocityOvertimeModule = new VelocityOvertimeModule(); @property({ - type: ForceOvertimeModule + type: ForceOvertimeModule, }) - forceOvertimeModule = new ForceOvertimeModule(); + public forceOvertimeModule = new ForceOvertimeModule(); @property({ - type: LimitVelocityOvertimeModule + type: LimitVelocityOvertimeModule, }) - limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); + public limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); @property({ - type: RotationOvertimeModule + type: RotationOvertimeModule, }) - rotationOvertimeModule = new RotationOvertimeModule(); + public rotationOvertimeModule = new RotationOvertimeModule(); @property({ - type: TextureAnimationModule + type: TextureAnimationModule, }) - textureAnimationModule = new TextureAnimationModule(); + public textureAnimationModule = new TextureAnimationModule(); - constructor() { + // particle system renderer + private renderer: ParticleSystemRenderer | null; + private _isPlaying: boolean; + private _isPaused: boolean; + private _isStopped: boolean; + private _isEmitting: boolean; + + private _time: number; // playback position in seconds. + private _emitRateTimeCounter: number; + private _emitRateDistanceCounter: number; + private _oldWPos: vec3; + private _curWPos: vec3; + + private _customData1: vec2; + private _customData2: vec2; + + private _subEmitters: any[]; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'} + + constructor () { super(); this.rateOverTime.constant = 10; @@ -200,9 +210,10 @@ export default class ParticleSystemComponent extends Component { this._customData2 = vec2.create(0, 0); this._subEmitters = []; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'} + this.renderer = null; } - onLoad() { + private onLoad () { // HACK, TODO this.renderer = this.getComponent(ParticleSystemRenderer); this.renderer.onInit(); @@ -215,17 +226,17 @@ export default class ParticleSystemComponent extends Component { // this._system.add(this); } - onDestroy() { + private onDestroy () { // this._system.remove(this); } - onEnable() { + private onEnable () { if (this.playOnAwake) { this.play(); } } - onDisable() { + private onDisable () { } @@ -234,7 +245,7 @@ export default class ParticleSystemComponent extends Component { // } - play() { + public play () { if (this._isPaused) { this._isPaused = false; } @@ -254,7 +265,7 @@ export default class ParticleSystemComponent extends Component { } } - pause() { + public pause () { if (this._isStopped) { console.warn('pause(): particle system is already stopped.'); return; @@ -266,7 +277,7 @@ export default class ParticleSystemComponent extends Component { this._isPaused = true; } - stop() { + public stop () { if (this._isPlaying) { this._isPlaying = false; } @@ -283,21 +294,21 @@ export default class ParticleSystemComponent extends Component { } // remove all particles from current particle system. - clear() { - this._particles.reset(); - this._renderer._model.clear(); + public clear () { + this.renderer!.clear(); } - emit(count, emitParams = null) { + private emit (count, emitParams = null) { if (emitParams !== null) { // TODO: } for (let i = 0; i < count; ++i) { - let particle = this.renderer._getFreeParticle(); - if (particle === null) + const particle = this.renderer!._getFreeParticle(); + if (particle === null) { return; - let rand = pseudoRandom(randomRangeInt(0, INT_MAX)); + } + const rand = pseudoRandom(randomRangeInt(0, INT_MAX)); if (this.shapeModule.enable) { this.shapeModule.emit(particle); @@ -312,13 +323,12 @@ export default class ParticleSystemComponent extends Component { switch (this._simulationSpace) { case Space.Local: break; - case Space.World: { + case Space.World: this.node.getWorldMatrix(_world_mat); vec3.transformMat4(particle.position, particle.position, _world_mat); - let worldRot = quat.create(); + const worldRot = quat.create(); this.node.getWorldRotation(worldRot); vec3.transformQuat(particle.velocity, particle.velocity, worldRot); - } break; case Space.Custom: // TODO: @@ -342,88 +352,28 @@ export default class ParticleSystemComponent extends Component { particle.randomSeed = randomRangeInt(0, 233280); - this.renderer._setNewParticle(particle); + this.renderer!._setNewParticle(particle); } // end of particles forLoop. } - // simulation, update particles. - _updateParticles(dt) { - this._entity.getWorldMatrix(_world_mat); - if (this._velocityOvertimeModule.enable) { - this._velocityOvertimeModule.update(this._simulationSpace, _world_mat); - } - if (this._forceOvertimeModule.enable) { - this._forceOvertimeModule.update(this._simulationSpace, _world_mat); - } - for (let i = 0; i < this._particles.length; ++i) { - let p = this._particles.data[i]; - p.remainingLifetime -= dt; - vec3.set(p.animatedVelocity, 0, 0, 0); - - if (p.remainingLifetime < 0.0) { - // subEmitter - // if (this._subEmitters.length > 0) { - // for (let idx = 0; idx < this._subEmitters.length; ++idx) { - // let subEmitter = this._subEmitters[idx]; - // if (subEmitter.type === 'death') { - // vec3.copy(subEmitter.emitter.entity.lpos, p.position); - // subEmitter.emitter.play(); - // } - // } - // } - - this._particles.removeAt(i); - --i; - continue; - } - - p.velocity.y -= this._gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity. - if (this._sizeOvertimeModule.enable) { - this._sizeOvertimeModule.animate(p); - } - if (this._colorOverLifetimeModule.enable) { - this._colorOverLifetimeModule.animate(p); - } - if (this._forceOvertimeModule.enable) { - this._forceOvertimeModule.animate(p, dt); - } - if (this._velocityOvertimeModule.enable) { - this._velocityOvertimeModule.animate(p); - } - else { - vec3.copy(p.ultimateVelocity, p.velocity); - } - if (this._limitVelocityOvertimeModule.enable) { - this._limitVelocityOvertimeModule.animate(p); - } - if (this._rotationOvertimeModule.enable) { - this._rotationOvertimeModule.animate(p, dt); - } - if (this._textureAnimationModule.enable) { - this._textureAnimationModule.animate(p); - } - vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. - } - } - // initialize particle system as though it had already completed a full cycle. - _prewarmSystem() { - this._startDelay.mode = 'constant'; // clear startDelay. - this._startDelay.constant = 0; - let dt = 1.0; // should use varying value? - let cnt = this.duration / dt; + private _prewarmSystem () { + this.startDelay.mode = 'constant'; // clear startDelay. + this.startDelay.constant = 0; + const dt = 1.0; // should use varying value? + const cnt = this.duration / dt; for (let i = 0; i < cnt; ++i) { this._time += dt; this._emit(dt); - this._renderer._updateParticles(dt); + this.renderer!._updateParticles(dt); } } // internal function - _emit(dt) { + private _emit (dt) { // emit particles. - let startDelay = this.startDelay.evaluate(); + const startDelay = this.startDelay.evaluate(); if (this._time > startDelay) { if (!this._isStopped) { this._isEmitting = true; @@ -441,30 +391,30 @@ export default class ParticleSystemComponent extends Component { // emit by rateOverTime this._emitRateTimeCounter += this.rateOverTime.evaluate(this._time / this.duration, 1) * dt; if (this._emitRateTimeCounter > 1 && this._isEmitting) { - let emitNum = Math.floor(this._emitRateTimeCounter); + const emitNum = Math.floor(this._emitRateTimeCounter); this._emitRateTimeCounter -= emitNum; this.emit(emitNum); } // emit by rateOverDistance this.node.getWorldPosition(this._curWPos); - let distance = vec3.distance(this._curWPos, this._oldWPos); + const distance = vec3.distance(this._curWPos, this._oldWPos); vec3.copy(this._oldWPos, this._curWPos); this._emitRateDistanceCounter += distance * this.rateOverDistance.evaluate(this._time / this.duration, 1); if (this._emitRateDistanceCounter > 1 && this._isEmitting) { - let emitNum = Math.floor(this._emitRateDistanceCounter); + const emitNum = Math.floor(this._emitRateDistanceCounter); this._emitRateDistanceCounter -= emitNum; this.emit(emitNum); } // bursts - for (let i = 0; i < this.bursts.length; ++i) { - this.bursts[i].update(this, dt); + for (const burst of this.bursts) { + burst.update(this, dt); } } } - update(dt) { - let scaledDeltaTime = dt * this.simulationSpeed; + private update (dt) { + const scaledDeltaTime = dt * this.simulationSpeed; if (this._isPlaying) { this._time += scaledDeltaTime; @@ -472,58 +422,58 @@ export default class ParticleSystemComponent extends Component { this._emit(scaledDeltaTime); // simulation, update particles. - this.renderer._updateParticles(scaledDeltaTime); + this.renderer!._updateParticles(scaledDeltaTime); // update render data - this.renderer._updateRenderData(); + this.renderer!._updateRenderData(); } } - addSubEmitter(subEmitter) { + private addSubEmitter (subEmitter) { this._subEmitters.push(subEmitter); } - removeSubEmitter(idx) { - this._subEmitters.remove(idx); + private removeSubEmitter (idx) { + this._subEmitters.splice(this._subEmitters.indexOf(idx), 1); } - addBurst(burst) { - this._bursts.push(burst); + private addBurst (burst) { + this.bursts.push(burst); } - removeBurst(idx) { - this._bursts.remove(idx); + private removeBurst (idx) { + this.bursts.splice(this.bursts.indexOf(idx), 1); } - getParticleCount() { - return this._particles.length; + public getParticleCount () { + return this.renderer!.getParticleCount(); } - setCustomData1(x, y) { + public setCustomData1 (x, y) { vec2.set(this._customData1, x, y); } - setCustomData2(x, y) { + public setCustomData2 (x, y) { vec2.set(this._customData2, x, y); } - get isPlaying() { + get isPlaying () { return this._isPlaying; } - get isPaused() { + get isPaused () { return this._isPaused; } - get isStopped() { + get isStopped () { return this._isStopped; } - get isEmitting() { + get isEmitting () { return this._isEmitting; } - get time() { + get time () { return this._time; } } diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts index 030ff60024..af4d8caf62 100644 --- a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts +++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts @@ -7,7 +7,7 @@ import * as renderer from '../../../../renderer'; import gfx from '../../../../renderer/gfx'; import ParticleBatchModel from '../../../../renderer/models/particle-batch-model'; import { Material } from '../../../assets/material'; -import { RecyclePool } from '../../../memop'; +import RecyclePool from '../../../memop/recycle-pool'; import Particle from '../particle'; import { RenderableComponent } from '../../renderable-component'; import { Space } from '../particle-general-function'; @@ -157,7 +157,12 @@ export default class ParticleSystemRenderer extends RenderableComponent { this._model!.destroy(); } - public _getFreeParticle () { + private clear () { + this._particles.reset(); + this._model!.destroy(); + } + + public _getFreeParticle (): Particle | null { if (this._particles.length >= this.particleSystem._capacity) { return null; } @@ -256,6 +261,10 @@ export default class ParticleSystemRenderer extends RenderableComponent { } + public getParticleCount (): number { + return this._particles.length; + } + public _onMaterialModified (index: number, material: Material) { this._updateMaterialParams(); this._updateModel(); diff --git a/cocos/3d/geom-utils/curve.js b/cocos/3d/geom-utils/curve.ts similarity index 53% rename from cocos/3d/geom-utils/curve.js rename to cocos/3d/geom-utils/curve.ts index cbf3d1e342..0824fcf8d2 100644 --- a/cocos/3d/geom-utils/curve.js +++ b/cocos/3d/geom-utils/curve.ts @@ -9,70 +9,77 @@ const WrapMode = Enum({ Once: 1, Loop: 2, PingPong: 3, - ClampForever: 4 + ClampForever: 4, }); export class Keyframe { - time = 0; + public time = 0; - value = 0; + public value = 0; - inTangent = 0; + public inTangent = 0; - outTangent = 0; + public outTangent = 0; } CCClass.fastDefine('cc.Keyframe', Keyframe, { time: 0, value: 0, inTangent: 0, - outTangent: 0 + outTangent: 0, }); export class OptimizedKey { - constructor() { + public index: number; + public time: number; + public endTime: number; + public coefficient: Float32Array; + constructor () { this.index = -1; this.time = 0; this.endTime = 0; this.coefficient = new Float32Array(4); } - evaluate(T) { - let t = T - this.time; + public evaluate (T: number) { + const t = T - this.time; return evalOptCurve(t, this.coefficient); } } -export function evalOptCurve(t, coefs) { +export function evalOptCurve (t: number, coefs: Float32Array) { return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3]; } export class AnimationCurve { - keyFrames = null; + public keyFrames: Keyframe[] | null; - preWrapMode = WrapMode.Default; + public preWrapMode: number = WrapMode.Default; - postWrapMode = WrapMode.Default; + public postWrapMode: number = WrapMode.Default; - constructor(keyFrames) { + private cachedKey: OptimizedKey; + + constructor (keyFrames: Keyframe[] | null = null) { this.keyFrames = keyFrames; this.cachedKey = new OptimizedKey(); } - addKey(keyFrame) { - if (this.keyFrames == null) + public addKey (keyFrame: Keyframe) { + if (this.keyFrames == null) { this.keyFrames = []; + } this.keyFrames.push(keyFrame); } - //cubic Hermite spline - evaluate_slow(time) { + // cubic Hermite spline + public evaluate_slow (time: number) { let wrappedTime = time; - let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; - let startTime = this.keyFrames[0].time; - let endTime = this.keyFrames[this.keyFrames.length - 1].time; + const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; + const startTime = this.keyFrames![0].time; + const endTime = this.keyFrames![this.keyFrames!.length - 1].time; switch (wrapMode) { case WrapMode.Loop: wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; @@ -85,43 +92,44 @@ export class AnimationCurve { break; } let preKFIndex = 0; - if (wrappedTime > this.keyFrames[0].time) { - if (wrappedTime >= this.keyFrames[this.keyFrames.length - 1].time) - preKFIndex = this.keyFrames.length - 2; + if (wrappedTime > this.keyFrames![0].time) { + if (wrappedTime >= this.keyFrames![this.keyFrames!.length - 1].time) { + preKFIndex = this.keyFrames!.length - 2; + } else { - for (let i = 0; i < this.keyFrames.length - 1; i++) { - if (wrappedTime >= this.keyFrames[0].time && wrappedTime <= this.keyFrames[i + 1].time) { + for (let i = 0; i < this.keyFrames!.length - 1; i++) { + if (wrappedTime >= this.keyFrames![0].time && wrappedTime <= this.keyFrames![i + 1].time) { preKFIndex = i; break; } } } } - let keyframe0 = this.keyFrames[preKFIndex]; - let keyframe1 = this.keyFrames[preKFIndex + 1]; + const keyframe0 = this.keyFrames![preKFIndex]; + const keyframe1 = this.keyFrames![preKFIndex + 1]; - let t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime); - let dt = keyframe1.time - keyframe0.time; + const t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime); + const dt = keyframe1.time - keyframe0.time; - let m0 = keyframe0.outTangent * dt; - let m1 = keyframe1.inTangent * dt; + const m0 = keyframe0.outTangent * dt; + const m1 = keyframe1.inTangent * dt; - let t2 = t * t; - let t3 = t2 * t; + const t2 = t * t; + const t3 = t2 * t; - let a = 2 * t3 - 3 * t2 + 1; - let b = t3 - 2 * t2 + t; - let c = t3 - t2; - let d = -2 * t3 + 3 * t2; + const a = 2 * t3 - 3 * t2 + 1; + const b = t3 - 2 * t2 + t; + const c = t3 - t2; + const d = -2 * t3 + 3 * t2; return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value; } - evaluate(time) { + public evaluate (time) { let wrappedTime = time; - let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; - let startTime = this.keyFrames[0].time; - let endTime = this.keyFrames[this.keyFrames.length - 1].time; + const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode; + const startTime = this.keyFrames![0].time; + const endTime = this.keyFrames![this.keyFrames!.length - 1].time; switch (wrapMode) { case WrapMode.Loop: wrappedTime = repeat(time - startTime, endTime - startTime) + startTime; @@ -136,9 +144,9 @@ export class AnimationCurve { if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) { return this.cachedKey.evaluate(wrappedTime); } else { - let leftIndex = this.findIndex(this.cachedKey, wrappedTime); + const leftIndex = this.findIndex(this.cachedKey, wrappedTime); let rightIndex = leftIndex + 1; - if (rightIndex == this.keyFrames.length) { + if (rightIndex === this.keyFrames!.length) { rightIndex -= 1; } this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex); @@ -146,18 +154,18 @@ export class AnimationCurve { } } - calcOptimizedKey(optKey, leftIndex, rightIndex) { - let lhs = this.keyFrames[leftIndex]; - let rhs = this.keyFrames[rightIndex]; + private calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number) { + const lhs = this.keyFrames![leftIndex]; + const rhs = this.keyFrames![rightIndex]; optKey.index = leftIndex; optKey.time = lhs.time; optKey.endTime = rhs.time; - let dx = rhs.time - lhs.time; - let dy = rhs.value - lhs.value; - let length = 1 / (dx * dx); - let d1 = lhs.outTangent * dx; - let d2 = rhs.inTangent * dx; + const dx = rhs.time - lhs.time; + const dy = rhs.value - lhs.value; + const length = 1 / (dx * dx); + const d1 = lhs.outTangent * dx; + const d2 = rhs.inTangent * dx; optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx; optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length; @@ -165,31 +173,31 @@ export class AnimationCurve { optKey.coefficient[3] = lhs.value; } - findIndex(optKey, t) { - let cachedIndex = optKey.index; + private findIndex (optKey: OptimizedKey, t: number) { + const cachedIndex = optKey.index; if (cachedIndex !== -1) { - let cachedTime = this.keyFrames[cachedIndex].time; + const cachedTime = this.keyFrames![cachedIndex].time; if (t > cachedTime) { for (let i = 0; i < LOOK_FORWARD; i++) { - let currIndex = cachedIndex + i; - if (currIndex + 1 < this.keyFrames.length && this.keyFrames[currIndex + 1].time > t) { + const currIndex = cachedIndex + i; + if (currIndex + 1 < this.keyFrames!.length && this.keyFrames![currIndex + 1].time > t) { return currIndex; } } } else { for (let i = 0; i < LOOK_FORWARD; i++) { - let currIndex = cachedIndex - i; - if (currIndex >= 0 && this.keyFrames[currIndex - 1].time <= t) { + const currIndex = cachedIndex - i; + if (currIndex >= 0 && this.keyFrames![currIndex - 1].time <= t) { return currIndex - 1; } } } } let left = 0; - let right = this.keyFrames.length; + let right = this.keyFrames!.length; let mid = parseInt((left + right) / 2); while (right - left > 1) { - if (this.keyFrames[mid].time >= t) { + if (this.keyFrames![mid].time >= t) { right = mid; } else { left = mid + 1; @@ -203,5 +211,5 @@ export class AnimationCurve { CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, { preWrapMode: WrapMode.Default, postWrapMode: WrapMode.Default, - keyFrames: [] + keyFrames: [], }); diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/3d/memop/recycle-pool.ts index 1fac7f0aba..67f8b5a89f 100644 --- a/cocos/3d/memop/recycle-pool.ts +++ b/cocos/3d/memop/recycle-pool.ts @@ -62,7 +62,7 @@ export default class RecyclePool { public remove (obj: T) { if (this._objIdx.has(obj)) { - this.removeAt(this._objIdx.get(obj)); + this.removeAt(this._objIdx.get(obj)!); } } From 1ca2d71276fcf430245464c80b3f1d6f3ff33b6c Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 25 Jan 2019 17:55:11 +0800 Subject: [PATCH 266/267] fix uniform cache error --- cocos/gfx/webgl/webgl-commands.ts | 231 +++++++++------------------ cocos/gfx/webgl/webgl-gpu-objects.ts | 5 +- cocos/renderer/ui/ui.ts | 1 - cocos/scene-graph/scene.js | 4 +- 4 files changed, 78 insertions(+), 163 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index e466db03b6..050181c8be 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1011,7 +1011,9 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web const stride = WebGLGetTypeSize(glType); const size = stride * uniform.count; const begin = glBlock.size / 4; - // const count = size / 4; + const count = size / 4; + const array = new Array(count); + array.fill(0); glBlock.glUniforms[u] = { binding: -1, @@ -1024,14 +1026,15 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web glType, glLoc: -1, - vi32: null, - vf32: null, + array, begin, + isFirst: true, }; glBlock.size += size; } + /* glBlock.buffer = new ArrayBuffer(glBlock.size); for (const glUniform of glBlock.glUniforms) { @@ -1054,6 +1057,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } } } + */ } } @@ -1655,16 +1659,13 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web switch (glUniform.glType) { case WebGLRenderingContext.BOOL: case WebGLRenderingContext.INT: { - for (let u = 0; u < glUniform.count; ++u) { - if (gpuBinding.gpuBuffer.vf32[glUniform.begin + u] !== glUniform.vi32![u]) { - - _uniformValues.length = glUniform.count; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vi32!.set(_uniformValues); - gl.uniform1iv(glUniform.glLoc, _uniformValues); + gl.uniform1iv(glUniform.glLoc, glUniform.array); break; } } @@ -1672,19 +1673,13 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.BOOL_VEC2: case WebGLRenderingContext.INT_VEC2: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 2; - const uidx = glUniform.begin + idx; - if (gpuBinding.gpuBuffer.vf32[uidx] !== glUniform.vi32![idx] || - gpuBinding.gpuBuffer.vf32[uidx + 1] !== glUniform.vi32![idx + 1]) { - - _uniformValues.length = glUniform.count * 2; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vi32!.set(_uniformValues); - gl.uniform2iv(glUniform.glLoc, _uniformValues); + gl.uniform2iv(glUniform.glLoc, glUniform.array); break; } } @@ -1692,20 +1687,13 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.BOOL_VEC3: case WebGLRenderingContext.INT_VEC3: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 3; - const uidx = glUniform.begin + idx; - if (gpuBinding.gpuBuffer.vf32[uidx] !== glUniform.vi32![idx] || - gpuBinding.gpuBuffer.vf32[uidx + 1] !== glUniform.vi32![idx + 1] || - gpuBinding.gpuBuffer.vf32[uidx + 2] !== glUniform.vi32![idx + 2]) { - - _uniformValues.length = glUniform.count * 3; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vi32!.set(_uniformValues); - gl.uniform3iv(glUniform.glLoc, _uniformValues); + gl.uniform3iv(glUniform.glLoc, glUniform.array); break; } } @@ -1713,177 +1701,104 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web } case WebGLRenderingContext.BOOL_VEC4: case WebGLRenderingContext.INT_VEC4: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 4; - const uidx = glUniform.begin + idx; - if (gpuBinding.gpuBuffer.vf32[uidx] !== glUniform.vi32![idx] || - gpuBinding.gpuBuffer.vf32[uidx + 1] !== glUniform.vi32![idx + 1] || - gpuBinding.gpuBuffer.vf32[uidx + 2] !== glUniform.vi32![idx + 2] || - gpuBinding.gpuBuffer.vf32[uidx + 3] !== glUniform.vi32![idx + 3]) { - - _uniformValues.length = glUniform.count * 4; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vi32!.set(_uniformValues); - gl.uniform4iv(glUniform.glLoc, _uniformValues); + gl.uniform4iv(glUniform.glLoc, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT: { - for (let u = 0; u < glUniform.count; ++u) { - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[glUniform.begin + u], glUniform.vf32![u])) { - - _uniformValues.length = glUniform.count; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniform1fv(glUniform.glLoc, _uniformValues); + gl.uniform1fv(glUniform.glLoc, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT_VEC2: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 2; - const uidx = glUniform.begin + idx; - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1])) { - - _uniformValues.length = glUniform.count * 2; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniform2fv(glUniform.glLoc, _uniformValues); + gl.uniform2fv(glUniform.glLoc, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT_VEC3: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 3; - const uidx = glUniform.begin + idx; - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2])) { - - _uniformValues.length = glUniform.count * 3; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniform3fv(glUniform.glLoc, _uniformValues); + gl.uniform3fv(glUniform.glLoc, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT_VEC4: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 4; - const uidx = glUniform.begin + idx; - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3])) { - - _uniformValues.length = glUniform.count * 4; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniform4fv(glUniform.glLoc, _uniformValues); + gl.uniform4fv(glUniform.glLoc, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT_MAT2: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 4; - const uidx = glUniform.begin + idx; - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3])) { - - _uniformValues.length = glUniform.count * 4; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniformMatrix2fv(glUniform.glLoc, false, _uniformValues); + gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT_MAT3: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 9; - const uidx = glUniform.begin + idx; - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 4], glUniform.vf32![idx + 4]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 5], glUniform.vf32![idx + 5]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 6], glUniform.vf32![idx + 6]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 7], glUniform.vf32![idx + 7]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 8], glUniform.vf32![idx + 8])) { - - _uniformValues.length = glUniform.count * 9; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniformMatrix3fv(glUniform.glLoc, false, _uniformValues); + gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array); break; } } break; } case WebGLRenderingContext.FLOAT_MAT4: { - for (let u = 0; u < glUniform.count; ++u) { - const idx = u * 16; - const uidx = glUniform.begin + idx; - if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx], glUniform.vf32![idx]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 1], glUniform.vf32![idx + 1]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 2], glUniform.vf32![idx + 2]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 3], glUniform.vf32![idx + 3]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 4], glUniform.vf32![idx + 4]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 5], glUniform.vf32![idx + 5]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 6], glUniform.vf32![idx + 6]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 7], glUniform.vf32![idx + 7]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 8], glUniform.vf32![idx + 8]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 9], glUniform.vf32![idx + 9]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 10], glUniform.vf32![idx + 10]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 11], glUniform.vf32![idx + 11]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 12], glUniform.vf32![idx + 12]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 13], glUniform.vf32![idx + 13]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 14], glUniform.vf32![idx + 14]) || - CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[uidx + 15], glUniform.vf32![idx + 15])) { - - _uniformValues.length = glUniform.count * 16; - for (let n = 0, m = glUniform.begin; n < _uniformValues.length; ++n, ++m) { - _uniformValues[n] = gpuBinding.gpuBuffer.vf32[m]; + for (let u = 0; u < glUniform.array.length; ++u) { + const idx = glUniform.begin + u; + if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { + for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } - - glUniform.vf32!.set(_uniformValues); - gl.uniformMatrix4fv(glUniform.glLoc, false, _uniformValues); + gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array); break; } } diff --git a/cocos/gfx/webgl/webgl-gpu-objects.ts b/cocos/gfx/webgl/webgl-gpu-objects.ts index f0c338c69c..ea6ab2456e 100644 --- a/cocos/gfx/webgl/webgl-gpu-objects.ts +++ b/cocos/gfx/webgl/webgl-gpu-objects.ts @@ -170,9 +170,9 @@ export interface IWebGLGPUUniform { glType: GLenum; glLoc: WebGLUniformLocation; - vi32: Int32Array | null; - vf32: Float32Array | null; + array: number[]; begin: number; + isFirst: boolean; } export class WebGLGPUUniformBlock { @@ -183,7 +183,6 @@ export class WebGLGPUUniformBlock { public glActiveUniforms: IWebGLGPUUniform[] = []; public isUniformPackage: boolean = false; // Is a single uniform package? - public buffer: ArrayBuffer | null = null; // for cache } export class WebGLGPUUniformSampler { diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts index 86186efead..65ad4ae270 100644 --- a/cocos/renderer/ui/ui.ts +++ b/cocos/renderer/ui/ui.ts @@ -112,7 +112,6 @@ export class UI { this._device = _root.device; this._scene = this._root.createScene({ name: 'GUIScene', - isUIScene: true, }); this._batches = new CachedArray(64); diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js index b20719bbc1..e35a4bdef8 100644 --- a/cocos/scene-graph/scene.js +++ b/cocos/scene-graph/scene.js @@ -53,7 +53,9 @@ export default class Scene extends Node { // cache all depend assets for auto release this.dependAssets = null; - this._renderScene = cc.director.root.createScene({}); + if (cc.director && cc.director.root) { + this._renderScene = cc.director.root.createScene({}); + } } /** From 90e666e4f0f454ef685405ad787957f867603a59 Mon Sep 17 00:00:00 2001 From: jerrywwl Date: Fri, 25 Jan 2019 18:27:11 +0800 Subject: [PATCH 267/267] optimize cache update --- cocos/gfx/webgl/webgl-commands.ts | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/cocos/gfx/webgl/webgl-commands.ts b/cocos/gfx/webgl/webgl-commands.ts index 050181c8be..cc02069999 100644 --- a/cocos/gfx/webgl/webgl-commands.ts +++ b/cocos/gfx/webgl/webgl-commands.ts @@ -1000,7 +1000,6 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web glUniforms: new Array(block.members.length), glActiveUniforms: [], isUniformPackage: true, - buffer: null, }; gpuShader.glBlocks[i] = glBlock; @@ -1662,7 +1661,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform1iv(glUniform.glLoc, glUniform.array); @@ -1676,7 +1675,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform2iv(glUniform.glLoc, glUniform.array); @@ -1690,7 +1689,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform3iv(glUniform.glLoc, glUniform.array); @@ -1704,7 +1703,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (gpuBinding.gpuBuffer.vf32[idx] !== glUniform.array[u]) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform4iv(glUniform.glLoc, glUniform.array); @@ -1717,7 +1716,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform1fv(glUniform.glLoc, glUniform.array); @@ -1730,7 +1729,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform2fv(glUniform.glLoc, glUniform.array); @@ -1743,7 +1742,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform3fv(glUniform.glLoc, glUniform.array); @@ -1756,7 +1755,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniform4fv(glUniform.glLoc, glUniform.array); @@ -1769,7 +1768,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array); @@ -1782,7 +1781,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array); @@ -1795,7 +1794,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web for (let u = 0; u < glUniform.array.length; ++u) { const idx = glUniform.begin + u; if (CmpF32NotEuqal(gpuBinding.gpuBuffer.vf32[idx], glUniform.array[u])) { - for (let n = 0, m = glUniform.begin; n < glUniform.array.length; ++n, ++m) { + for (let n = u, m = glUniform.begin + u; n < glUniform.array.length; ++n, ++m) { glUniform.array[n] = gpuBinding.gpuBuffer.vf32[m]; } gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array);